{ "version": 3, "sources": ["../../../node_modules/toastify-js/src/toastify.js", "../../../node_modules/@rails/actioncable/src/adapters.js", "../../../node_modules/@rails/actioncable/src/logger.js", "../../../node_modules/@rails/actioncable/src/connection_monitor.js", "../../../node_modules/@rails/actioncable/src/internal.js", "../../../node_modules/@rails/actioncable/src/connection.js", "../../../node_modules/@rails/actioncable/src/subscription.js", "../../../node_modules/@rails/actioncable/src/subscription_guarantor.js", "../../../node_modules/@rails/actioncable/src/subscriptions.js", "../../../node_modules/@rails/actioncable/src/consumer.js", "../../../node_modules/@rails/actioncable/src/index.js", "../../../node_modules/regenerator-runtime/runtime.js", "../../../node_modules/tesseract.js/src/utils/getId.js", "../../../node_modules/tesseract.js/src/createJob.js", "../../../node_modules/tesseract.js/src/utils/log.js", "../../../node_modules/tesseract.js/src/createScheduler.js", "../../../node_modules/tesseract.js/src/utils/getEnvironment.js", "../../../node_modules/tesseract.js/src/utils/resolvePaths.js", "../../../node_modules/tesseract.js/src/constants/OEM.js", "../../../node_modules/tesseract.js/package.json", "../../../node_modules/tesseract.js/src/constants/defaultOptions.js", "../../../node_modules/tesseract.js/src/worker/browser/defaultOptions.js", "../../../node_modules/tesseract.js/src/worker/browser/spawnWorker.js", "../../../node_modules/tesseract.js/src/worker/browser/terminateWorker.js", "../../../node_modules/tesseract.js/src/worker/browser/onMessage.js", "../../../node_modules/tesseract.js/src/worker/browser/send.js", "../../../node_modules/tesseract.js/src/worker/browser/loadImage.js", "../../../node_modules/tesseract.js/src/worker/browser/index.js", "../../../node_modules/tesseract.js/src/createWorker.js", "../../../node_modules/tesseract.js/src/Tesseract.js", "../../../node_modules/tesseract.js/src/constants/languages.js", "../../../node_modules/tesseract.js/src/constants/PSM.js", "../../../node_modules/tesseract.js/src/index.js", "../../../node_modules/grapheme-splitter/index.js", "../../../node_modules/sms-segments-calculator/src/libs/UserDataHeader.ts", "../../../node_modules/sms-segments-calculator/src/libs/Segment.ts", "../../../node_modules/sms-segments-calculator/src/libs/UnicodeToGSM.ts", "../../../node_modules/sms-segments-calculator/src/libs/EncodedChar.ts", "../../../node_modules/sms-segments-calculator/src/libs/SmartEncodingMap.ts", "../../../node_modules/sms-segments-calculator/src/libs/SegmentedMessage.ts", "../../../node_modules/sms-segments-calculator/src/index.ts", "../../javascript/application.js", "../../javascript/boot.js", "../../../node_modules/@sentry/core/src/debug-build.ts", "../../../node_modules/@sentry/core/src/utils/worldwide.ts", "../../../node_modules/@sentry/core/src/utils/version.ts", "../../../node_modules/@sentry/core/src/carrier.ts", "../../../node_modules/@sentry/core/src/utils/debug-logger.ts", "../../../node_modules/@sentry/core/src/utils/stacktrace.ts", "../../../node_modules/@sentry/core/src/instrument/handlers.ts", "../../../node_modules/@sentry/core/src/instrument/globalError.ts", "../../../node_modules/@sentry/core/src/instrument/globalUnhandledRejection.ts", "../../../node_modules/@sentry/core/src/utils/is.ts", "../../../node_modules/@sentry/core/src/utils/browser.ts", "../../../node_modules/@sentry/core/src/utils/object.ts", "../../../node_modules/@sentry/core/src/utils/string.ts", "../../../node_modules/@sentry/core/src/utils/misc.ts", "../../../node_modules/@sentry/core/src/utils/time.ts", "../../../node_modules/@sentry/core/src/session.ts", "../../../node_modules/@sentry/core/src/utils/merge.ts", "../../../node_modules/@sentry/core/src/utils/propagationContext.ts", "../../../node_modules/@sentry/core/src/utils/spanOnScope.ts", "../../../node_modules/@sentry/core/src/scope.ts", "../../../node_modules/@sentry/core/src/defaultScopes.ts", "../../../node_modules/@sentry/core/src/asyncContext/stackStrategy.ts", "../../../node_modules/@sentry/core/src/asyncContext/index.ts", "../../../node_modules/@sentry/core/src/currentScopes.ts", "../../../node_modules/@sentry/core/src/semanticAttributes.ts", "../../../node_modules/@sentry/core/src/tracing/spanstatus.ts", "../../../node_modules/@sentry/core/src/tracing/utils.ts", "../../../node_modules/@sentry/core/src/utils/baggage.ts", "../../../node_modules/@sentry/core/src/utils/dsn.ts", "../../../node_modules/@sentry/core/src/utils/parseSampleRate.ts", "../../../node_modules/@sentry/core/src/utils/tracing.ts", "../../../node_modules/@sentry/core/src/utils/spanUtils.ts", "../../../node_modules/@sentry/core/src/tracing/errors.ts", "../../../node_modules/@sentry/core/src/utils/hasSpansEnabled.ts", "../../../node_modules/@sentry/core/src/utils/should-ignore-span.ts", "../../../node_modules/@sentry/core/src/constants.ts", "../../../node_modules/@sentry/core/src/tracing/dynamicSamplingContext.ts", "../../../node_modules/@sentry/core/src/tracing/sentryNonRecordingSpan.ts", "../../../node_modules/@sentry/core/src/utils/normalize.ts", "../../../node_modules/@sentry/core/src/utils/envelope.ts", "../../../node_modules/@sentry/core/src/envelope.ts", "../../../node_modules/@sentry/core/src/tracing/logSpans.ts", "../../../node_modules/@sentry/core/src/tracing/measurement.ts", "../../../node_modules/@sentry/core/src/tracing/sentrySpan.ts", "../../../node_modules/@sentry/core/src/utils/handleCallbackErrors.ts", "../../../node_modules/@sentry/core/src/tracing/sampling.ts", "../../../node_modules/@sentry/core/src/tracing/trace.ts", "../../../node_modules/@sentry/core/src/tracing/idleSpan.ts", "../../../node_modules/@sentry/core/src/utils/syncpromise.ts", "../../../node_modules/@sentry/core/src/eventProcessors.ts", "../../../node_modules/@sentry/core/src/utils/applyScopeDataToEvent.ts", "../../../node_modules/@sentry/core/src/utils/debug-ids.ts", "../../../node_modules/@sentry/core/src/utils/prepareEvent.ts", "../../../node_modules/@sentry/core/src/exports.ts", "../../../node_modules/@sentry/core/src/api.ts", "../../../node_modules/@sentry/core/src/integration.ts", "../../../node_modules/@sentry/core/src/logs/envelope.ts", "../../../node_modules/@sentry/core/src/logs/internal.ts", "../../../node_modules/@sentry/core/src/metrics/envelope.ts", "../../../node_modules/@sentry/core/src/metrics/internal.ts", "../../../node_modules/@sentry/core/src/utils/promisebuffer.ts", "../../../node_modules/@sentry/core/src/utils/ratelimit.ts", "../../../node_modules/@sentry/core/src/transports/base.ts", "../../../node_modules/@sentry/core/src/utils/clientreport.ts", "../../../node_modules/@sentry/core/src/utils/eventUtils.ts", "../../../node_modules/@sentry/core/src/utils/transactionEvent.ts", "../../../node_modules/@sentry/core/src/client.ts", "../../../node_modules/@sentry/core/src/sdk.ts", "../../../node_modules/@sentry/core/src/utils/url.ts", "../../../node_modules/@sentry/core/src/utils/isSentryRequestUrl.ts", "../../../node_modules/@sentry/core/src/utils/ipAddress.ts", "../../../node_modules/@sentry/core/src/utils/sdkMetadata.ts", "../../../node_modules/@sentry/core/src/utils/traceData.ts", "../../../node_modules/@sentry/core/src/utils/debounce.ts", "../../../node_modules/@sentry/core/src/breadcrumbs.ts", "../../../node_modules/@sentry/core/src/integrations/functiontostring.ts", "../../../node_modules/@sentry/core/src/integrations/eventFilters.ts", "../../../node_modules/@sentry/core/src/utils/aggregate-errors.ts", "../../../node_modules/@sentry/core/src/instrument/console.ts", "../../../node_modules/@sentry/core/src/utils/severity.ts", "../../../node_modules/@sentry/core/src/integrations/dedupe.ts", "../../../node_modules/@sentry/core/src/fetch.ts", "../../../node_modules/@sentry/core/src/utils/breadcrumb-log-level.ts", "../../../node_modules/@sentry/core/src/utils/supports.ts", "../../../node_modules/@sentry/core/src/instrument/fetch.ts", "../../../node_modules/@sentry/core/src/utils/env.ts", "../../../node_modules/@sentry/core/src/utils/node.ts", "../../../node_modules/@sentry/core/src/utils/isBrowser.ts", "../../../node_modules/@sentry/browser/src/helpers.ts", "../../../node_modules/@sentry/browser/src/eventbuilder.ts", "../../../node_modules/@sentry/browser/src/client.ts", "../../../node_modules/@sentry-internal/browser-utils/src/debug-build.ts", "../../../node_modules/@sentry-internal/browser-utils/src/types.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/bindReporter.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/getNavigationEntry.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/getActivationStart.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/globalListeners.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/getVisibilityWatcher.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/generateUniqueID.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/initMetric.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/initUnique.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/LayoutShiftManager.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/observe.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/runOnce.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/whenActivated.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/onFCP.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/getCLS.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/polyfills/interactionCountPolyfill.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/InteractionManager.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/onHidden.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/whenIdleOrHidden.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/getINP.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/LCPEntryManager.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/getLCP.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/onTTFB.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/instrument.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/utils.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/cls.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/lcp.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/resourceTiming.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/browserMetrics.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/elementTiming.ts", "../../../node_modules/@sentry-internal/browser-utils/src/instrument/dom.ts", "../../../node_modules/@sentry-internal/browser-utils/src/instrument/history.ts", "../../../node_modules/@sentry-internal/browser-utils/src/getNativeImplementation.ts", "../../../node_modules/@sentry-internal/browser-utils/src/instrument/xhr.ts", "../../../node_modules/@sentry-internal/browser-utils/src/networkUtils.ts", "../../../node_modules/@sentry-internal/browser-utils/src/metrics/inp.ts", "../../../node_modules/@sentry/browser/src/transports/fetch.ts", "../../../node_modules/@sentry/browser/src/debug-build.ts", "../../../node_modules/@sentry/browser/src/stack-parsers.ts", "../../../node_modules/@sentry/browser/src/integrations/breadcrumbs.ts", "../../../node_modules/@sentry/browser/src/integrations/browserapierrors.ts", "../../../node_modules/@sentry/browser/src/integrations/browsersession.ts", "../../../node_modules/@sentry/browser/src/integrations/globalhandlers.ts", "../../../node_modules/@sentry/browser/src/integrations/httpcontext.ts", "../../../node_modules/@sentry/browser/src/integrations/linkederrors.ts", "../../../node_modules/@sentry/browser/src/utils/detectBrowserExtension.ts", "../../../node_modules/@sentry/browser/src/sdk.ts", "../../../node_modules/@sentry-internal/replay/src/constants.ts", "../../../node_modules/node_modules/@sentry-internal/rrweb/dist/rrweb.js", "../../../node_modules/@sentry-internal/replay/src/types/rrweb.ts", "../../../node_modules/@sentry-internal/replay/src/util/timestamp.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/util/addBreadcrumbEvent.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/util/domUtils.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/util/onWindowOpen.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/handleClick.ts", "../../../node_modules/@sentry-internal/replay/src/util/createBreadcrumb.ts", "../../../node_modules/node_modules/@sentry-internal/rrweb-snapshot/dist/rrweb-snapshot.js", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/util/getAttributesToRecord.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/handleDom.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/handleKeyboardEvent.ts", "../../../node_modules/@sentry-internal/replay/src/util/createPerformanceEntries.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/performanceObserver.ts", "../../../node_modules/@sentry-internal/replay/src/debug-build.ts", "../../../node_modules/@sentry-internal/replay-worker/build/esm/worker.ts", "../../../node_modules/@sentry-internal/replay-worker/build/esm/index.js", "../../../node_modules/@sentry-internal/replay/src/util/logger.ts", "../../../node_modules/@sentry-internal/replay/src/eventBuffer/error.ts", "../../../node_modules/@sentry-internal/replay/src/eventBuffer/EventBufferArray.ts", "../../../node_modules/@sentry-internal/replay/src/eventBuffer/WorkerHandler.ts", "../../../node_modules/@sentry-internal/replay/src/eventBuffer/EventBufferCompressionWorker.ts", "../../../node_modules/@sentry-internal/replay/src/eventBuffer/EventBufferProxy.ts", "../../../node_modules/@sentry-internal/replay/src/eventBuffer/index.ts", "../../../node_modules/@sentry-internal/replay/src/util/hasSessionStorage.ts", "../../../node_modules/@sentry-internal/replay/src/session/clearSession.ts", "../../../node_modules/@sentry-internal/replay/src/util/isSampled.ts", "../../../node_modules/@sentry-internal/replay/src/session/saveSession.ts", "../../../node_modules/@sentry-internal/replay/src/session/Session.ts", "../../../node_modules/@sentry-internal/replay/src/session/createSession.ts", "../../../node_modules/@sentry-internal/replay/src/session/fetchSession.ts", "../../../node_modules/@sentry-internal/replay/src/util/isExpired.ts", "../../../node_modules/@sentry-internal/replay/src/util/isSessionExpired.ts", "../../../node_modules/@sentry-internal/replay/src/session/shouldRefreshSession.ts", "../../../node_modules/@sentry-internal/replay/src/session/loadOrCreateSession.ts", "../../../node_modules/@sentry-internal/replay/src/util/addEvent.ts", "../../../node_modules/@sentry-internal/replay/src/util/eventUtils.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/handleAfterSendEvent.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/handleBeforeSendEvent.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/handleBreadcrumbs.ts", "../../../node_modules/@sentry-internal/replay/src/util/isRrwebError.ts", "../../../node_modules/@sentry-internal/replay/src/util/resetReplayIdOnDynamicSamplingContext.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/util/addFeedbackBreadcrumb.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/util/shouldSampleForBufferEvent.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/handleGlobalEvent.ts", "../../../node_modules/@sentry-internal/replay/src/util/createPerformanceSpans.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/handleHistory.ts", "../../../node_modules/@sentry-internal/replay/src/util/shouldFilterRequest.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/util/addNetworkBreadcrumb.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/util/networkUtils.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/util/fetchUtils.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/util/xhrUtils.ts", "../../../node_modules/@sentry-internal/replay/src/coreHandlers/handleNetworkBreadcrumbs.ts", "../../../node_modules/@sentry-internal/replay/src/util/addGlobalListeners.ts", "../../../node_modules/@sentry-internal/replay/src/util/addMemoryEntry.ts", "../../../node_modules/@sentry-internal/replay/src/util/debounce.ts", "../../../node_modules/@sentry-internal/replay/src/util/getRecordingSamplingOptions.ts", "../../../node_modules/@sentry-internal/replay/src/util/handleRecordingEmit.ts", "../../../node_modules/@sentry-internal/replay/src/util/rrweb.ts", "../../../node_modules/@sentry-internal/replay/src/util/createReplayEnvelope.ts", "../../../node_modules/@sentry-internal/replay/src/util/prepareRecordingData.ts", "../../../node_modules/@sentry-internal/replay/src/util/prepareReplayEvent.ts", "../../../node_modules/@sentry-internal/replay/src/util/sendReplayRequest.ts", "../../../node_modules/@sentry-internal/replay/src/util/sendReplay.ts", "../../../node_modules/@sentry-internal/replay/src/util/throttle.ts", "../../../node_modules/@sentry-internal/replay/src/replay.ts", "../../../node_modules/@sentry-internal/replay/src/util/getPrivacyOptions.ts", "../../../node_modules/@sentry-internal/replay/src/util/maskAttribute.ts", "../../../node_modules/@sentry-internal/replay/src/integration.ts", "../../../node_modules/@sentry-internal/replay/src/util/getReplay.ts", "../../../node_modules/@sentry/browser/src/tracing/utils.ts", "../../../node_modules/@sentry/browser/src/tracing/request.ts", "../../../node_modules/@sentry/browser/src/tracing/backgroundtab.ts", "../../../node_modules/@sentry/browser/src/tracing/linkedTraces.ts", "../../../node_modules/@sentry/browser/src/tracing/browserTracingIntegration.ts", "../../javascript/sentry.js", "../../javascript/error_notifier.js", "../../javascript/extensions/arrays.js", "../../javascript/extensions/highlight.js", "../../javascript/concerns/spinners.js", "../../javascript/utils/elements.js", "../../javascript/utils/analytics.js", "../../../node_modules/posthog-js/src/utils/globals.ts", "../../../node_modules/posthog-js/src/config.ts", "../../../node_modules/core/dist/gzip.mjs", "../../../node_modules/core/dist/types.mjs", "../../../node_modules/core/dist/utils/bot-detection.mjs", "../../../node_modules/core/dist/utils/string-utils.mjs", "../../../node_modules/core/dist/utils/type-utils.mjs", "../../../node_modules/core/dist/utils/number-utils.mjs", "../../../node_modules/core/dist/utils/bucketed-rate-limiter.mjs", "../../../node_modules/core/dist/utils/user-agent-utils.mjs", "../../../node_modules/core/dist/error-tracking/chunk-ids.mjs", "../../../node_modules/core/dist/utils/index.mjs", "../../../node_modules/core/dist/error-tracking/error-properties-builder.mjs", "../../../node_modules/core/dist/error-tracking/parsers/base.mjs", "../../../node_modules/core/dist/error-tracking/parsers/safari.mjs", "../../../node_modules/core/dist/error-tracking/parsers/chrome.mjs", "../../../node_modules/core/dist/error-tracking/parsers/gecko.mjs", "../../../node_modules/core/dist/error-tracking/parsers/index.mjs", "../../../node_modules/core/dist/error-tracking/coercers/dom-exception-coercer.mjs", "../../../node_modules/core/dist/error-tracking/coercers/error-coercer.mjs", "../../../node_modules/core/dist/error-tracking/coercers/error-event-coercer.mjs", "../../../node_modules/core/dist/error-tracking/coercers/string-coercer.mjs", "../../../node_modules/core/dist/error-tracking/types.mjs", "../../../node_modules/core/dist/error-tracking/coercers/utils.mjs", "../../../node_modules/core/dist/error-tracking/coercers/object-coercer.mjs", "../../../node_modules/core/dist/error-tracking/coercers/event-coercer.mjs", "../../../node_modules/core/dist/error-tracking/coercers/primitive-coercer.mjs", "../../../node_modules/core/dist/error-tracking/coercers/promise-rejection-event.mjs", "../../../node_modules/posthog-js/src/utils/logger.ts", "../../../node_modules/posthog-js/src/entrypoints/external-scripts-loader.ts", "../../../node_modules/posthog-js/src/constants.ts", "../../../node_modules/posthog-js/src/utils/index.ts", "../../../node_modules/posthog-js/src/uuidv7.ts", "../../../node_modules/posthog-js/src/storage.ts", "../../../node_modules/posthog-js/src/consent.ts", "../../../node_modules/posthog-js/src/extensions/dead-clicks-autocapture.ts", "../../../node_modules/posthog-js/src/extensions/segment-integration.ts", "../../../node_modules/posthog-js/src/extensions/sentry-integration.ts", "../../../node_modules/posthog-js/src/page-view.ts", "../../../node_modules/posthog-js/src/utils/request-utils.ts", "../../../node_modules/posthog-js/src/utils/event-utils.ts", "../../../node_modules/posthog-js/src/posthog-persistence.ts", "../../../node_modules/posthog-js/src/posthog-surveys-types.ts", "../../../node_modules/posthog-js/src/posthog-product-tours-types.ts", "../../../node_modules/posthog-js/src/rate-limiter.ts", "../../../node_modules/posthog-js/src/remote-config.ts", "../../../node_modules/posthog-js/src/types.ts", "../../../node_modules/.pnpm/fflate@0.4.8/node_modules/fflate/esm/browser.js", "../../../node_modules/posthog-js/src/request.ts", "../../../node_modules/posthog-js/src/utils/encode-utils.ts", "../../../node_modules/posthog-js/src/request-queue.ts", "../../../node_modules/posthog-js/src/retry-queue.ts", "../../../node_modules/posthog-js/src/scroll-manager.ts", "../../../node_modules/posthog-js/src/session-props.ts", "../../../node_modules/posthog-js/src/utils/simple-event-emitter.ts", "../../../node_modules/posthog-js/src/sessionid.ts", "../../../node_modules/posthog-js/src/utils/blocked-uas.ts", "../../../node_modules/posthog-js/src/utils/regex-utils.ts", "../../../node_modules/posthog-js/src/utils/property-utils.ts", "../../../node_modules/posthog-js/src/utils/request-router.ts", "../../../node_modules/posthog-js/src/utils/survey-utils.ts", "../../../node_modules/posthog-js/src/extensions/external-integration.ts", "../../../node_modules/posthog-js/src/posthog-core.ts", "../../../node_modules/posthog-js/src/utils/element-utils.ts", "../../../node_modules/posthog-js/src/autocapture-utils.ts", "../../../node_modules/posthog-js/src/extensions/rageclick.ts", "../../../node_modules/posthog-js/src/autocapture.ts", "../../../node_modules/posthog-js/src/extensions/exception-autocapture/index.ts", "../../../node_modules/posthog-js/src/extensions/replay/rrweb-plugins/patch.ts", "../../../node_modules/posthog-js/src/extensions/tracing-headers.ts", "../../../node_modules/posthog-js/src/extensions/web-vitals/index.ts", "../../../node_modules/posthog-js/src/extensions/replay/external/triggerMatching.ts", "../../../node_modules/posthog-js/src/extensions/replay/external/recording-strategies.ts", "../../../node_modules/posthog-js/src/extensions/replay/external/lazy-loaded-session-recorder.ts", "../../../node_modules/posthog-js/src/extensions/replay/session-recording.ts", "../../../node_modules/posthog-js/src/heatmaps.ts", "../../../node_modules/posthog-js/src/posthog-product-tours.ts", "../../../node_modules/posthog-js/src/site-apps.ts", "../../../node_modules/posthog-js/src/utils/elements-chain-utils.ts", "../../../node_modules/posthog-js/src/extensions/surveys/action-matcher.ts", "../../../node_modules/posthog-js/src/utils/event-receiver.ts", "../../../node_modules/posthog-js/src/utils/survey-event-receiver.ts", "../../../node_modules/posthog-js/src/posthog-surveys.ts", "../../../node_modules/posthog-js/src/extensions/toolbar.ts", "../../../node_modules/posthog-js/src/posthog-featureflags.ts", "../../../node_modules/posthog-js/src/posthog-exceptions.ts", "../../../node_modules/posthog-js/src/web-experiments.ts", "../../../node_modules/posthog-js/src/extensions/conversations/posthog-conversations.ts", "../../../node_modules/posthog-js/src/logs-utils.ts", "../../../node_modules/posthog-js/src/extensions/extension-bundles.ts", "../../../node_modules/posthog-js/src/extensions/history-autocapture.ts", "../../../node_modules/posthog-js/src/posthog-logs.ts", "../../../node_modules/posthog-js/src/entrypoints/default-extensions.ts", "../../../node_modules/posthog-js/src/entrypoints/module.no-external.es.ts", "../../javascript/utils/posthog.js", "../../javascript/ui/flash.js", "../../javascript/logic/vin.js", "../../javascript/editor/config/toolbar.js", "../../javascript/forms/editor.js", "../../javascript/ui/integration_questionnaire.js", "../../javascript/views/upsheet.js", "../../javascript/app.js", "../../../node_modules/@firebase/util/dist/postinstall.mjs", "../../../node_modules/@firebase/util/src/constants.ts", "../../../node_modules/@firebase/util/src/assert.ts", "../../../node_modules/@firebase/util/src/crypt.ts", "../../../node_modules/@firebase/util/src/deepCopy.ts", "../../../node_modules/@firebase/util/src/global.ts", "../../../node_modules/@firebase/util/src/defaults.ts", "../../../node_modules/@firebase/util/src/deferred.ts", "../../../node_modules/@firebase/util/src/url.ts", "../../../node_modules/@firebase/util/src/emulator.ts", "../../../node_modules/@firebase/util/src/environment.ts", "../../../node_modules/@firebase/util/src/errors.ts", "../../../node_modules/@firebase/util/src/json.ts", "../../../node_modules/@firebase/util/src/jwt.ts", "../../../node_modules/@firebase/util/src/obj.ts", "../../../node_modules/@firebase/util/src/promise.ts", "../../../node_modules/@firebase/util/src/query.ts", "../../../node_modules/@firebase/util/src/sha1.ts", "../../../node_modules/@firebase/util/src/subscribe.ts", "../../../node_modules/@firebase/util/src/validation.ts", "../../../node_modules/@firebase/util/src/utf8.ts", "../../../node_modules/@firebase/util/src/exponential_backoff.ts", "../../../node_modules/@firebase/util/src/formatters.ts", "../../../node_modules/@firebase/util/src/compat.ts", "../../../node_modules/@firebase/component/src/component.ts", "../../../node_modules/@firebase/component/src/constants.ts", "../../../node_modules/@firebase/component/src/provider.ts", "../../../node_modules/@firebase/component/src/component_container.ts", "../../../node_modules/@firebase/logger/src/logger.ts", "../../../node_modules/idb/build/wrap-idb-value.js", "../../../node_modules/idb/build/index.js", "../../../node_modules/@firebase/app/src/platformLoggerService.ts", "../../../node_modules/@firebase/app/src/logger.ts", "../../../node_modules/@firebase/app/src/constants.ts", "../../../node_modules/@firebase/app/src/internal.ts", "../../../node_modules/@firebase/app/src/errors.ts", "../../../node_modules/@firebase/app/src/firebaseApp.ts", "../../../node_modules/@firebase/app/src/firebaseServerApp.ts", "../../../node_modules/@firebase/app/src/api.ts", "../../../node_modules/@firebase/app/src/indexeddb.ts", "../../../node_modules/@firebase/app/src/heartbeatService.ts", "../../../node_modules/@firebase/app/src/registerCoreComponents.ts", "../../../node_modules/@firebase/app/src/index.ts", "../../../node_modules/firebase/app/index.ts", "../../../node_modules/@firebase/installations/src/util/constants.ts", "../../../node_modules/@firebase/installations/src/util/errors.ts", "../../../node_modules/@firebase/installations/src/functions/common.ts", "../../../node_modules/@firebase/installations/src/functions/create-installation-request.ts", "../../../node_modules/@firebase/installations/src/util/sleep.ts", "../../../node_modules/@firebase/installations/src/helpers/buffer-to-base64-url-safe.ts", "../../../node_modules/@firebase/installations/src/helpers/generate-fid.ts", "../../../node_modules/@firebase/installations/src/util/get-key.ts", "../../../node_modules/@firebase/installations/src/helpers/fid-changed.ts", "../../../node_modules/@firebase/installations/src/helpers/idb-manager.ts", "../../../node_modules/@firebase/installations/src/helpers/get-installation-entry.ts", "../../../node_modules/@firebase/installations/src/functions/generate-auth-token-request.ts", "../../../node_modules/@firebase/installations/src/helpers/refresh-auth-token.ts", "../../../node_modules/@firebase/installations/src/api/get-id.ts", "../../../node_modules/@firebase/installations/src/api/get-token.ts", "../../../node_modules/@firebase/installations/src/functions/delete-installation-request.ts", "../../../node_modules/@firebase/installations/src/api/delete-installations.ts", "../../../node_modules/@firebase/installations/src/api/on-id-change.ts", "../../../node_modules/@firebase/installations/src/api/get-installations.ts", "../../../node_modules/@firebase/installations/src/helpers/extract-app-config.ts", "../../../node_modules/@firebase/installations/src/functions/config.ts", "../../../node_modules/@firebase/installations/src/index.ts", "../../../node_modules/@firebase/messaging/src/util/constants.ts", "../../../node_modules/@firebase/messaging/src/interfaces/internal-message-payload.ts", "../../../node_modules/@firebase/messaging/src/helpers/array-base64-translator.ts", "../../../node_modules/@firebase/messaging/src/helpers/migrate-old-database.ts", "../../../node_modules/@firebase/messaging/src/internals/idb-manager.ts", "../../../node_modules/@firebase/messaging/src/util/errors.ts", "../../../node_modules/@firebase/messaging/src/internals/requests.ts", "../../../node_modules/@firebase/messaging/src/internals/token-manager.ts", "../../../node_modules/@firebase/messaging/src/helpers/externalizePayload.ts", "../../../node_modules/@firebase/messaging/src/helpers/is-console-message.ts", "../../../node_modules/@firebase/messaging/src/helpers/logToFirelog.ts", "../../../node_modules/@firebase/messaging/src/helpers/extract-app-config.ts", "../../../node_modules/@firebase/messaging/src/messaging-service.ts", "../../../node_modules/@firebase/messaging/src/helpers/registerDefaultSw.ts", "../../../node_modules/@firebase/messaging/src/helpers/updateSwReg.ts", "../../../node_modules/@firebase/messaging/src/helpers/updateVapidKey.ts", "../../../node_modules/@firebase/messaging/src/api/getToken.ts", "../../../node_modules/@firebase/messaging/src/helpers/logToScion.ts", "../../../node_modules/@firebase/messaging/src/listeners/window-listener.ts", "../../../node_modules/@firebase/messaging/src/helpers/register.ts", "../../../node_modules/@firebase/messaging/src/api/isSupported.ts", "../../../node_modules/@firebase/messaging/src/api/deleteToken.ts", "../../../node_modules/@firebase/messaging/src/api/onMessage.ts", "../../../node_modules/@firebase/messaging/src/api.ts", "../../../node_modules/@firebase/messaging/src/index.ts", "../../javascript/firebase.js", "../../javascript/turbo.js", "../../javascript/editor/config/setup.js", "../../javascript/upsheets/attachments.js", "../../../node_modules/@hotwired/stimulus/dist/stimulus.js", "../../javascript/utils/debounce.js", "../../javascript/controllers/validator_controller.js", "../../javascript/billing/payments.js", "../../javascript/forms/contact_editor.js", "../../../node_modules/@rails/activestorage/app/assets/javascripts/activestorage.esm.js", "../../../node_modules/rhino-editor/src/exports/events/base-event.ts", "../../../node_modules/rhino-editor/src/exports/events/add-attachment-event.ts", "../../../node_modules/rhino-editor/src/exports/events/rhino-focus-event.ts", "../../../node_modules/rhino-editor/src/exports/events/rhino-change-event.ts", "../../../node_modules/rhino-editor/src/exports/events/rhino-blur-event.ts", "../../../node_modules/rhino-editor/src/exports/events/initialize-event.ts", "../../../node_modules/rhino-editor/src/exports/events/file-accept-event.ts", "../../../node_modules/rhino-editor/src/exports/events/before-initialize-event.ts", "../../../node_modules/rhino-editor/src/exports/events/selection-change-event.ts", "../../../node_modules/@lit/reactive-element/src/css-tag.ts", "../../../node_modules/@lit/reactive-element/src/reactive-element.ts", "../../../node_modules/lit-html/src/lit-html.ts", "../../../node_modules/lit-element/src/lit-element.ts", "../../../node_modules/rhino-editor/src/exports/styles/editor.js", "../../../node_modules/orderedmap/dist/index.js", "../../../node_modules/prosemirror-model/dist/index.js", "../../../node_modules/prosemirror-transform/dist/index.js", "../../../node_modules/prosemirror-state/dist/index.js", "../../../node_modules/prosemirror-view/dist/index.js", "../../../node_modules/w3c-keyname/index.js", "../../../node_modules/prosemirror-keymap/dist/index.js", "../../../node_modules/prosemirror-commands/dist/index.js", "../../../node_modules/prosemirror-schema-list/dist/index.js", "../../../node_modules/@tiptap/core/src/helpers/createChainableState.ts", "../../../node_modules/@tiptap/core/src/CommandManager.ts", "../../../node_modules/@tiptap/core/src/EventEmitter.ts", "../../../node_modules/@tiptap/core/src/helpers/getExtensionField.ts", "../../../node_modules/@tiptap/core/src/helpers/splitExtensions.ts", "../../../node_modules/@tiptap/core/src/helpers/getAttributesFromExtensions.ts", "../../../node_modules/@tiptap/core/src/helpers/getNodeType.ts", "../../../node_modules/@tiptap/core/src/utilities/mergeAttributes.ts", "../../../node_modules/@tiptap/core/src/helpers/getRenderedAttributes.ts", "../../../node_modules/@tiptap/core/src/utilities/isFunction.ts", "../../../node_modules/@tiptap/core/src/utilities/callOrReturn.ts", "../../../node_modules/@tiptap/core/src/utilities/isEmptyObject.ts", "../../../node_modules/@tiptap/core/src/utilities/fromString.ts", "../../../node_modules/@tiptap/core/src/helpers/injectExtensionAttributesToParseRule.ts", "../../../node_modules/@tiptap/core/src/helpers/getSchemaByResolvedExtensions.ts", "../../../node_modules/@tiptap/core/src/helpers/getSchemaTypeByName.ts", "../../../node_modules/@tiptap/core/src/helpers/isExtensionRulesEnabled.ts", "../../../node_modules/@tiptap/core/src/helpers/getHTMLFromFragment.ts", "../../../node_modules/@tiptap/core/src/helpers/getTextContentFromNodes.ts", "../../../node_modules/@tiptap/core/src/utilities/isRegExp.ts", "../../../node_modules/@tiptap/core/src/InputRule.ts", "../../../node_modules/@tiptap/core/src/utilities/isPlainObject.ts", "../../../node_modules/@tiptap/core/src/utilities/mergeDeep.ts", "../../../node_modules/@tiptap/core/src/Mark.ts", "../../../node_modules/@tiptap/core/src/utilities/isNumber.ts", "../../../node_modules/@tiptap/core/src/PasteRule.ts", "../../../node_modules/@tiptap/core/src/utilities/findDuplicates.ts", "../../../node_modules/@tiptap/core/src/ExtensionManager.ts", "../../../node_modules/@tiptap/core/src/Extension.ts", "../../../node_modules/@tiptap/core/src/helpers/getTextBetween.ts", "../../../node_modules/@tiptap/core/src/helpers/getTextSerializersFromSchema.ts", "../../../node_modules/@tiptap/core/src/extensions/clipboardTextSerializer.ts", "../../../node_modules/@tiptap/core/src/commands/blur.ts", "../../../node_modules/@tiptap/core/src/commands/clearContent.ts", "../../../node_modules/@tiptap/core/src/commands/clearNodes.ts", "../../../node_modules/@tiptap/core/src/commands/command.ts", "../../../node_modules/@tiptap/core/src/commands/createParagraphNear.ts", "../../../node_modules/@tiptap/core/src/commands/cut.ts", "../../../node_modules/@tiptap/core/src/commands/deleteCurrentNode.ts", "../../../node_modules/@tiptap/core/src/commands/deleteNode.ts", "../../../node_modules/@tiptap/core/src/commands/deleteRange.ts", "../../../node_modules/@tiptap/core/src/commands/deleteSelection.ts", "../../../node_modules/@tiptap/core/src/commands/enter.ts", "../../../node_modules/@tiptap/core/src/commands/exitCode.ts", "../../../node_modules/@tiptap/core/src/utilities/objectIncludes.ts", "../../../node_modules/@tiptap/core/src/helpers/getMarkRange.ts", "../../../node_modules/@tiptap/core/src/helpers/getMarkType.ts", "../../../node_modules/@tiptap/core/src/commands/extendMarkRange.ts", "../../../node_modules/@tiptap/core/src/commands/first.ts", "../../../node_modules/@tiptap/core/src/helpers/isTextSelection.ts", "../../../node_modules/@tiptap/core/src/utilities/minMax.ts", "../../../node_modules/@tiptap/core/src/helpers/resolveFocusPosition.ts", "../../../node_modules/@tiptap/core/src/utilities/isAndroid.ts", "../../../node_modules/@tiptap/core/src/utilities/isiOS.ts", "../../../node_modules/@tiptap/core/src/utilities/isSafari.ts", "../../../node_modules/@tiptap/core/src/commands/focus.ts", "../../../node_modules/@tiptap/core/src/commands/forEach.ts", "../../../node_modules/@tiptap/core/src/commands/insertContent.ts", "../../../node_modules/@tiptap/core/src/utilities/elementFromString.ts", "../../../node_modules/@tiptap/core/src/helpers/createNodeFromContent.ts", "../../../node_modules/@tiptap/core/src/helpers/selectionToInsertionEnd.ts", "../../../node_modules/@tiptap/core/src/commands/insertContentAt.ts", "../../../node_modules/@tiptap/core/src/commands/join.ts", "../../../node_modules/@tiptap/core/src/commands/joinItemBackward.ts", "../../../node_modules/@tiptap/core/src/commands/joinItemForward.ts", "../../../node_modules/@tiptap/core/src/commands/joinTextblockBackward.ts", "../../../node_modules/@tiptap/core/src/commands/joinTextblockForward.ts", "../../../node_modules/@tiptap/core/src/utilities/isMacOS.ts", "../../../node_modules/@tiptap/core/src/commands/keyboardShortcut.ts", "../../../node_modules/@tiptap/core/src/helpers/isNodeActive.ts", "../../../node_modules/@tiptap/core/src/commands/lift.ts", "../../../node_modules/@tiptap/core/src/commands/liftEmptyBlock.ts", "../../../node_modules/@tiptap/core/src/commands/liftListItem.ts", "../../../node_modules/@tiptap/core/src/commands/newlineInCode.ts", "../../../node_modules/@tiptap/core/src/helpers/getSchemaTypeNameByName.ts", "../../../node_modules/@tiptap/core/src/utilities/deleteProps.ts", "../../../node_modules/@tiptap/core/src/commands/resetAttributes.ts", "../../../node_modules/@tiptap/core/src/commands/scrollIntoView.ts", "../../../node_modules/@tiptap/core/src/commands/selectAll.ts", "../../../node_modules/@tiptap/core/src/commands/selectNodeBackward.ts", "../../../node_modules/@tiptap/core/src/commands/selectNodeForward.ts", "../../../node_modules/@tiptap/core/src/commands/selectParentNode.ts", "../../../node_modules/@tiptap/core/src/commands/selectTextblockEnd.ts", "../../../node_modules/@tiptap/core/src/commands/selectTextblockStart.ts", "../../../node_modules/@tiptap/core/src/helpers/createDocument.ts", "../../../node_modules/@tiptap/core/src/commands/setContent.ts", "../../../node_modules/@tiptap/core/src/helpers/getMarkAttributes.ts", "../../../node_modules/@tiptap/core/src/helpers/combineTransactionSteps.ts", "../../../node_modules/@tiptap/core/src/helpers/defaultBlockAt.ts", "../../../node_modules/@tiptap/core/src/helpers/findChildren.ts", "../../../node_modules/@tiptap/core/src/helpers/findChildrenInRange.ts", "../../../node_modules/@tiptap/core/src/helpers/findParentNodeClosestToPos.ts", "../../../node_modules/@tiptap/core/src/helpers/findParentNode.ts", "../../../node_modules/@tiptap/core/src/helpers/getSchema.ts", "../../../node_modules/@tiptap/core/src/helpers/generateHTML.ts", "../../../node_modules/@tiptap/core/src/helpers/generateJSON.ts", "../../../node_modules/@tiptap/core/src/helpers/getText.ts", "../../../node_modules/@tiptap/core/src/helpers/generateText.ts", "../../../node_modules/@tiptap/core/src/helpers/getNodeAttributes.ts", "../../../node_modules/@tiptap/core/src/helpers/getAttributes.ts", "../../../node_modules/@tiptap/core/src/utilities/removeDuplicates.ts", "../../../node_modules/@tiptap/core/src/helpers/getChangedRanges.ts", "../../../node_modules/@tiptap/core/src/helpers/getDebugJSON.ts", "../../../node_modules/@tiptap/core/src/helpers/getMarksBetween.ts", "../../../node_modules/@tiptap/core/src/helpers/getNodeAtPosition.ts", "../../../node_modules/@tiptap/core/src/helpers/getSplittedAttributes.ts", "../../../node_modules/@tiptap/core/src/helpers/isMarkActive.ts", "../../../node_modules/@tiptap/core/src/helpers/isActive.ts", "../../../node_modules/@tiptap/core/src/helpers/isAtEndOfNode.ts", "../../../node_modules/@tiptap/core/src/helpers/isAtStartOfNode.ts", "../../../node_modules/@tiptap/core/src/helpers/isList.ts", "../../../node_modules/@tiptap/core/src/helpers/isNodeEmpty.ts", "../../../node_modules/@tiptap/core/src/helpers/isNodeSelection.ts", "../../../node_modules/@tiptap/core/src/helpers/posToDOMRect.ts", "../../../node_modules/@tiptap/core/src/helpers/rewriteUnknownContent.ts", "../../../node_modules/@tiptap/core/src/commands/setMark.ts", "../../../node_modules/@tiptap/core/src/commands/setMeta.ts", "../../../node_modules/@tiptap/core/src/commands/setNode.ts", "../../../node_modules/@tiptap/core/src/commands/setNodeSelection.ts", "../../../node_modules/@tiptap/core/src/commands/setTextSelection.ts", "../../../node_modules/@tiptap/core/src/commands/sinkListItem.ts", "../../../node_modules/@tiptap/core/src/commands/splitBlock.ts", "../../../node_modules/@tiptap/core/src/commands/splitListItem.ts", "../../../node_modules/@tiptap/core/src/commands/toggleList.ts", "../../../node_modules/@tiptap/core/src/commands/toggleMark.ts", "../../../node_modules/@tiptap/core/src/commands/toggleNode.ts", "../../../node_modules/@tiptap/core/src/commands/toggleWrap.ts", "../../../node_modules/@tiptap/core/src/commands/undoInputRule.ts", "../../../node_modules/@tiptap/core/src/commands/unsetAllMarks.ts", "../../../node_modules/@tiptap/core/src/commands/unsetMark.ts", "../../../node_modules/@tiptap/core/src/commands/updateAttributes.ts", "../../../node_modules/@tiptap/core/src/commands/wrapIn.ts", "../../../node_modules/@tiptap/core/src/commands/wrapInList.ts", "../../../node_modules/@tiptap/core/src/extensions/commands.ts", "../../../node_modules/@tiptap/core/src/extensions/drop.ts", "../../../node_modules/@tiptap/core/src/extensions/editable.ts", "../../../node_modules/@tiptap/core/src/extensions/focusEvents.ts", "../../../node_modules/@tiptap/core/src/extensions/keymap.ts", "../../../node_modules/@tiptap/core/src/extensions/paste.ts", "../../../node_modules/@tiptap/core/src/extensions/tabindex.ts", "../../../node_modules/@tiptap/core/src/NodePos.ts", "../../../node_modules/@tiptap/core/src/style.ts", "../../../node_modules/@tiptap/core/src/utilities/createStyleTag.ts", "../../../node_modules/@tiptap/core/src/Editor.ts", "../../../node_modules/@tiptap/core/src/inputRules/markInputRule.ts", "../../../node_modules/@tiptap/core/src/inputRules/nodeInputRule.ts", "../../../node_modules/@tiptap/core/src/inputRules/textblockTypeInputRule.ts", "../../../node_modules/@tiptap/core/src/inputRules/textInputRule.ts", "../../../node_modules/@tiptap/core/src/inputRules/wrappingInputRule.ts", "../../../node_modules/@tiptap/core/src/Node.ts", "../../../node_modules/@tiptap/core/src/NodeView.ts", "../../../node_modules/@tiptap/core/src/pasteRules/markPasteRule.ts", "../../../node_modules/@tiptap/core/src/utilities/canInsertNode.ts", "../../../node_modules/@tiptap/core/src/utilities/escapeForRegEx.ts", "../../../node_modules/@tiptap/core/src/utilities/isString.ts", "../../../node_modules/@tiptap/core/src/pasteRules/nodePasteRule.ts", "../../../node_modules/@tiptap/core/src/pasteRules/textPasteRule.ts", "../../../node_modules/@tiptap/core/src/Tracker.ts", "../../../node_modules/rhino-editor/src/exports/extensions/figcaption.ts", "../../../node_modules/prosemirror-codemark/src/utils.ts", "../../../node_modules/prosemirror-codemark/src/inputRules.ts", "../../../node_modules/prosemirror-codemark/src/actions.ts", "../../../node_modules/prosemirror-codemark/src/plugin.ts", "../../../node_modules/prosemirror-codemark/src/index.ts", "../../../node_modules/rhino-editor/src/exports/extensions/codemark-plugin.ts", "../../../node_modules/rhino-editor/src/exports/extensions/bubble-menu.ts", "../../../node_modules/@tiptap/extension-strike/src/strike.ts", "../../../node_modules/rhino-editor/src/exports/extensions/strike.ts", "../../../node_modules/rhino-editor/src/exports/extensions/selection.ts", "../../../node_modules/rhino-editor/src/exports/events/rhino-paste-event.ts", "../../../node_modules/rhino-editor/src/exports/extensions/paste.ts", "../../../node_modules/rhino-editor/src/exports/extensions/find-attribute.ts", "../../../node_modules/rhino-editor/src/exports/extensions/image.ts", "../../../node_modules/rhino-editor/src/exports/events/attachment-remove-event.ts", "../../../node_modules/rhino-editor/src/exports/styles/normalize.ts", "../../../node_modules/rhino-editor/src/exports/translations.ts", "../../../node_modules/rhino-editor/exports/chunks/chunk-54KOYG5C.js", "../../../node_modules/rhino-editor/src/exports/elements/attachment-editor.ts", "../../../node_modules/rhino-editor/src/internal/icons.ts", "../../../node_modules/rhino-editor/src/internal/to-memory-size.ts", "../../../node_modules/rhino-editor/src/internal/elements/base-element.ts", "../../../node_modules/rhino-editor/src/exports/attachment-upload.ts", "../../../node_modules/rhino-editor/src/internal/uuidv4.ts", "../../../node_modules/rhino-editor/src/internal/to-default-caption.ts", "../../../node_modules/rhino-editor/src/exports/attachment-manager.ts", "../../../node_modules/prosemirror-utils/src/selection.ts", "../../../node_modules/prosemirror-utils/src/helpers.ts", "../../../node_modules/prosemirror-utils/src/transforms.ts", "../../../node_modules/prosemirror-utils/src/node.ts", "../../../node_modules/lit-html/src/directive.ts", "../../../node_modules/lit-html/src/directives/unsafe-html.ts", "../../../node_modules/lit-html/src/directives/if-defined.ts", "../../../node_modules/lit-html/src/directives/when.ts", "../../../node_modules/rhino-editor/src/exports/extensions/attachment.ts", "../../../node_modules/rhino-editor/src/internal/selection-to-insertion-end.ts", "../../../node_modules/rhino-editor/src/exports/extensions/gallery.ts", "../../../node_modules/@tiptap/extension-placeholder/src/placeholder.ts", "../../../node_modules/@tiptap/extension-focus/src/focus.ts", "../../../node_modules/linkifyjs/dist/linkify.mjs", "../../../node_modules/@tiptap/extension-link/src/helpers/whitespace.ts", "../../../node_modules/@tiptap/extension-link/src/helpers/autolink.ts", "../../../node_modules/@tiptap/extension-link/src/helpers/clickHandler.ts", "../../../node_modules/@tiptap/extension-link/src/helpers/pasteHandler.ts", "../../../node_modules/@tiptap/extension-link/src/link.ts", "../../../node_modules/rhino-editor/src/exports/extensions/rhino-starter-kit.ts", "../../../node_modules/rhino-editor/src/exports/styles/tip-tap-core-styles.ts", "../../../node_modules/@tiptap/extension-blockquote/src/blockquote.ts", "../../../node_modules/@tiptap/extension-bold/src/bold.ts", "../../../node_modules/@tiptap/extension-bullet-list/src/bullet-list.ts", "../../../node_modules/@tiptap/extension-code/src/code.ts", "../../../node_modules/@tiptap/extension-code-block/src/code-block.ts", "../../../node_modules/@tiptap/extension-document/src/document.ts", "../../../node_modules/prosemirror-dropcursor/dist/index.js", "../../../node_modules/@tiptap/extension-dropcursor/src/dropcursor.ts", "../../../node_modules/prosemirror-gapcursor/dist/index.js", "../../../node_modules/@tiptap/extension-gapcursor/src/gapcursor.ts", "../../../node_modules/@tiptap/extension-hard-break/src/hard-break.ts", "../../../node_modules/@tiptap/extension-heading/src/heading.ts", "../../../node_modules/rope-sequence/dist/index.js", "../../../node_modules/prosemirror-history/dist/index.js", "../../../node_modules/@tiptap/extension-history/src/history.ts", "../../../node_modules/@tiptap/extension-horizontal-rule/src/horizontal-rule.ts", "../../../node_modules/@tiptap/extension-italic/src/italic.ts", "../../../node_modules/@tiptap/extension-list-item/src/list-item.ts", "../../../node_modules/@tiptap/extension-ordered-list/src/ordered-list.ts", "../../../node_modules/@tiptap/extension-paragraph/src/paragraph.ts", "../../../node_modules/@tiptap/extension-text/src/text.ts", "../../../node_modules/@tiptap/starter-kit/src/starter-kit.ts", "../../../node_modules/rhino-editor/src/exports/elements/tip-tap-editor-base.ts", "../../../node_modules/lit-html/src/directive-helpers.ts", "../../../node_modules/lit-html/src/async-directive.ts", "../../../node_modules/lit-html/src/directives/ref.ts", "../../../node_modules/web-component-define/src/internal/defineable-mixin.js", "../../../node_modules/@open-wc/dedupe-mixin/src/dedupeMixin.js", "../../../node_modules/web-component-define/src/internal/scoped-elements-mixin.js", "../../../node_modules/web-component-define/src/internal/create-render-root-mixin.js", "../../../node_modules/role-components/internal/uuid.js", "../../../node_modules/role-components/internal/language-observer.js", "../../../node_modules/role-components/internal/base-element.js", "../../../node_modules/role-components/exports/styles/host-styles.js", "../../../node_modules/role-components/exports/components/toolbar/toolbar.js", "../../../node_modules/@floating-ui/dom/node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs", "../../../node_modules/@floating-ui/dom/node_modules/@floating-ui/core/dist/floating-ui.core.mjs", "../../../node_modules/@floating-ui/dom/node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs", "../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs", "../../../node_modules/lit-html/src/directives/class-map.ts", "../../../node_modules/role-components/internal/string-map.js", "../../../node_modules/role-components/exports/events/base-event.js", "../../../node_modules/role-components/exports/events/role-reposition-event.js", "../../../node_modules/role-components/exports/components/anchored-region/anchored-region.js", "../../../node_modules/role-components/exports/events/role-tooltip-toggle-event.js", "../../../node_modules/role-components/exports/components/tooltip/tooltip.js", "../../../node_modules/rhino-editor/src/exports/elements/tip-tap-editor.ts", "../../../node_modules/rhino-editor/src/internal/string-map.ts", "../../../node_modules/rhino-editor/src/internal/is-exact-node-active.ts", "../../../node_modules/rhino-editor/src/exports/index.ts", "../../../node_modules/@hotwired/turbo/dist/turbo.es2017-esm.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/snakeize.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable_stream_source_element.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/fetch_requests.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/index.js", "../../javascript/controllers/application.js", "../../javascript/controllers/academy/banner_controller.js", "../../javascript/controllers/academy/lesson_form_controller.js", "../../javascript/academy/video_player.js", "../../javascript/academy/watch_tracker.js", "../../javascript/controllers/academy/player_controller.js", "../../javascript/controllers/academy/upload_controller.js", "../../javascript/utils/fetch.js", "../../javascript/utils/ui_preference.js", "../../javascript/controllers/accordion_controller.js", "../../javascript/utils/confirm.js", "../../javascript/controllers/account/sources_controller.js", "../../javascript/controllers/activity_controller.js", "../../javascript/controllers/admin/account_health_controller.js", "../../javascript/controllers/admin/billing/dashboard_controller.js", "../../javascript/controllers/admin/penciling/dashboard_controller.js", "../../javascript/controllers/after_hours_toggle_controller.js", "../../javascript/controllers/ai_sales_bot_tabs_controller.js", "../../javascript/controllers/aisa/auto_save_controller.js", "../../javascript/controllers/aisa/escalation_confirmation_preview_controller.js", "../../javascript/controllers/aisa_followups/at_times_controller.js", "../../javascript/controllers/aisa_followups/main_controller.js", "../../javascript/controllers/aisa_followups/rule_item_controller.js", "../../javascript/controllers/aisa_pause_controller.js", "../../javascript/controllers/aisa_message_controller.js", "../../javascript/controllers/aisa_reasoning_modal_controller.js", "../../javascript/controllers/aisa_upsheet_toggle_controller.js", "../../javascript/controllers/banner_controller.js", "../../javascript/controllers/beta_features_controller.js", "../../javascript/controllers/appointment_duration_controller.js", "../../javascript/controllers/auto_check/refresh_controller.js", "../../javascript/controllers/buyers/trades_controller.js", "../../javascript/controllers/cascading_select_controller.js", "../../javascript/controllers/clickable_controller.js", "../../javascript/controllers/clipboard_controller.js", "../../javascript/controllers/column_mapping_controller.js", "../../javascript/controllers/communications/call_dialer_controller.js", "../../javascript/controllers/communications/call_transcript_controller.js", "../../javascript/controllers/communications/card_controller.js", "../../javascript/controllers/communications/compose_controller.js", "../../javascript/utils/dictation.ts", "../../javascript/utils/posthog_capture.js", "../../javascript/controllers/communications/dictation_controller.js", "../../javascript/controllers/communications/email_draft_controller.js", "../../javascript/utils/regex.js", "../../../node_modules/@tiptap/extension-image/src/image.ts", "../../javascript/communications/inlineable_types.ts", "../../javascript/controllers/communications/email_editor_controller.js", "../../javascript/controllers/communications/insert_content_controller.js", "../../javascript/controllers/communications/text_url_shortener_controller.js", "../../javascript/controllers/composer_task_picker_controller.js", "../../javascript/controllers/confirm_controller.js", "../../javascript/controllers/consent_modal_controller.js", "../../javascript/controllers/contact/editor_controller.js", "../../javascript/controllers/contact/input_collection_controller.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-SP3HSP4K.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-2QPETYTY.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-QCZSSQAQ.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-FSQXZE3N.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-ZAOFG2OQ.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-HIOHGPUS.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-FGO2SSRS.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-FTD535WI.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-VJB527QZ.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-FGCJ3ZLG.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-JKL2W65E.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-NMX4VHW2.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-T5EUB6UG.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-4ZMCJXZS.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-UHFABUTI.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-AXTXPLXP.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-JUG6FO4O.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-GX4YCYCH.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-N4NOODAT.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-5Y4OYXNX.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-KW3YSGJX.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-ANTPRJPM.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-3A4KLILV.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-U6BTTEV6.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-EV4OEANA.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-MAMZS5CH.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-5IVFVUF4.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-M46MIHI5.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-MSPQDVWJ.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-GE4CBD4E.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-U2VVDSM3.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-CNCPCHBZ.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-5S537AFM.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-R6E4CT22.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-RZAO2YPF.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-GXUTZY74.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-DTSV5FYV.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-436XQ2I6.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-GPJEB376.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-PSQ6LAQA.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-SK45SCLY.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-IWMYUNZ3.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-SZ672BOB.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-MW5PTAU7.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-QHBIT2WY.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-FSH6LHLS.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-SD5C67QU.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-XLX4QIMT.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-36CGJKPG.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-45EBHQYM.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-5YHTIVUK.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-4ZLDSFCW.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-N5YZEC56.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-44B7Z6ZZ.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-JFRSUCMO.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-COBZKSUV.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-QBDQQMQ5.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-LA6TM76R.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-457L5N2F.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-QR4TEDGM.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-IGJQFAQU.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-EP3GI7KA.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-XVLYCDJL.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-KYNYQBNF.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-PXXUQXGB.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-N5F43TUJ.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-WUHKODFA.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-RLD35PR2.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-AWSARCBG.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-G7A5SQZE.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-F3A3WWOG.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-6H6FKGVE.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-EMHHC6NB.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-7SW2PEHB.js", "../../../node_modules/scandit-web-datacapture-core/build/js/chunks/chunk-EGMJHFGI.js", "../../../node_modules/scandit-web-datacapture-core/build/js/index.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-3UG34CP2.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-7SWSAHI5.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-KBO3YYBN.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-LBAL6OCN.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-TRWFJYCT.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-J4VFWBJ7.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-IEE5MKEA.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-BW3FAMLI.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-CEZOMS4Y.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-LKZBVQXD.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-SIFQ2OI6.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-JYVE7GVH.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-VRFFR4LU.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-D3GTNMBR.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-TNZN2NNC.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-INN4TPZ4.js", "../../../node_modules/scandit-web-datacapture-barcode/build/js/chunks/chunk-XHKV6SNE.js", "../../javascript/ui/scandit/index.js", "../../javascript/ui/scandit/id_parser.js", "../../javascript/utils/strings.js", "../../javascript/controllers/contact/search_controller.js", "../../javascript/controllers/crs_theme_preview_controller.js", "../../javascript/controllers/custom_field_controller.js", "../../javascript/controllers/dashboard/builder_controller.js", "../../javascript/controllers/dashboard/bulletin_controller.js", "../../javascript/controllers/dashboard/chart_controller.js", "../../javascript/controllers/dashboard/stats_controller.js", "../../javascript/controllers/reports/insight_charts.js", "../../javascript/controllers/dashboard/widget_chart_controller.js", "../../javascript/controllers/dealership/lead_assignment_settings_controller.js", "../../javascript/controllers/dealership/insights_poller_controller.js", "../../javascript/controllers/dealership/lead_provider_controller.js", "../../javascript/controllers/dealership/lead_provider_form_controller.js", "../../javascript/controllers/dealership/merge_timeframe_controller.js", "../../javascript/controllers/dealership/routing_composer_controller.js", "../../javascript/controllers/dealership/rule_fallback_controller.js", "../../javascript/controllers/dealership/schedule_editor_controller.js", "../../javascript/controllers/dealertrack_selector_controller.js", "../../javascript/controllers/delete_payment_deal_controller.js", "../../javascript/controllers/dms_fee_filter_controller.js", "../../javascript/controllers/dms_fee_sync_controller.js", "../../javascript/controllers/dms_push_controller.js", "../../javascript/controllers/document_generate_controller.js", "../../javascript/controllers/editor/popover_controller.js", "../../javascript/controllers/email/attachment_controller.js", "../../javascript/controllers/email/draft_controller.js", "../../javascript/controllers/email/editor_controller.js", "../../javascript/controllers/email/spam_controller.js", "../../javascript/controllers/email_campaign/compose_controller.js", "../../javascript/controllers/equity_report_controller.js", "../../javascript/controllers/esignature_modal_controller.js", "../../javascript/controllers/expandable_controller.js", "../../javascript/controllers/filterable_table_controller.js", "../../../node_modules/imask/esm/core/utils.js", "../../../node_modules/imask/esm/core/action-details.js", "../../../node_modules/imask/esm/core/holder.js", "../../../node_modules/imask/esm/masked/factory.js", "../../../node_modules/imask/esm/controls/mask-element.js", "../../../node_modules/imask/esm/controls/html-mask-element.js", "../../../node_modules/imask/esm/controls/html-input-mask-element.js", "../../../node_modules/imask/esm/controls/html-contenteditable-mask-element.js", "../../../node_modules/imask/esm/controls/input-history.js", "../../../node_modules/imask/esm/controls/input.js", "../../../node_modules/imask/esm/core/change-details.js", "../../../node_modules/imask/esm/core/continuous-tail-details.js", "../../../node_modules/imask/esm/masked/base.js", "../../../node_modules/imask/esm/masked/pattern/chunk-tail-details.js", "../../../node_modules/imask/esm/masked/pattern/cursor.js", "../../../node_modules/imask/esm/masked/pattern/fixed-definition.js", "../../../node_modules/imask/esm/masked/pattern/input-definition.js", "../../../node_modules/imask/esm/masked/regexp.js", "../../../node_modules/imask/esm/masked/pattern.js", "../../../node_modules/imask/esm/masked/range.js", "../../../node_modules/imask/esm/masked/date.js", "../../../node_modules/imask/esm/masked/dynamic.js", "../../../node_modules/imask/esm/masked/enum.js", "../../../node_modules/imask/esm/masked/function.js", "../../../node_modules/imask/esm/masked/number.js", "../../../node_modules/imask/esm/masked/pipe.js", "../../../node_modules/imask/esm/masked/repeat.js", "../../../node_modules/imask/esm/index.js", "../../javascript/controllers/form_controller.js", "../../javascript/controllers/format_controller.js", "../../javascript/controllers/ga_controller.js", "../../javascript/controllers/goals/progress_controller.js", "../../javascript/controllers/iframe_controller.js", "../../javascript/controllers/imm/media/description_modal_controller.js", "../../javascript/controllers/imm/media/gallery_controller.js", "../../javascript/controllers/imm/media/item_controller.js", "../../javascript/controllers/imm/media/lightbox_controller.js", "../../../node_modules/sortablejs/modular/sortable.esm.js", "../../javascript/controllers/imm/media/sortable_controller.js", "../../javascript/controllers/imm/media/upload_controller.js", "../../javascript/controllers/import_config_form_controller.js", "../../javascript/controllers/import_connection_reorder_controller.js", "../../javascript/controllers/import_source_fields_controller.js", "../../javascript/controllers/import_progress_controller.js", "../../javascript/controllers/import_type_controller.js", "../../javascript/controllers/inventory/vin_decode_controller.js", "../../javascript/ui/vin_text_reader.js", "../../javascript/utils/vin.js", "../../javascript/controllers/inventory/vin_text_controller.js", "../../javascript/controllers/knowledge_help_modal_controller.js", "../../javascript/controllers/layout/global_search_controller.js", "../../javascript/controllers/layout/header_controller.js", "../../javascript/controllers/layout/omnibox_controller.js", "../../javascript/controllers/lead_resurrection_settings_controller.js", "../../javascript/controllers/mainline_assignment_controller.js", "../../javascript/controllers/mainline_call_group_controller.js", "../../javascript/controllers/mainline_hold_music_preview_controller.js", "../../javascript/mainline/phone_layouts.js", "../../javascript/controllers/mainline_provisioning_controller.js", "../../javascript/controllers/mainline_recording_playback_controller.js", "../../javascript/controllers/call_log_row_controller.js", "../../javascript/controllers/call_modal_controller.js", "../../javascript/BF-blank-template.json", "../../../node_modules/@mailupinc/bee-plugin/node_modules/load-script/index.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/fp-ts/lib/function.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/fp-ts/lib/internal.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/fp-ts/lib/Apply.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/fp-ts/lib/Functor.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/fp-ts/lib/Applicative.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/fp-ts/lib/Chain.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/fp-ts/lib/ChainRec.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/fp-ts/lib/FromEither.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/fp-ts/lib/Separated.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/fp-ts/lib/Witherable.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/fp-ts/lib/Either.js", "../../../node_modules/@mailupinc/bee-plugin/src/types/bee.ts", "../../../node_modules/@mailupinc/bee-plugin/src/utils/Constants.ts", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/bind.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/utils.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/core/AxiosError.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/null.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/toFormData.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/AxiosURLSearchParams.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/buildURL.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/core/InterceptorManager.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/defaults/transitional.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/platform/browser/classes/URLSearchParams.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/platform/browser/classes/FormData.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/platform/browser/classes/Blob.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/platform/browser/index.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/toURLEncodedForm.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/formDataToJSON.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/defaults/index.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/parseHeaders.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/core/AxiosHeaders.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/core/transformData.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/cancel/isCancel.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/cancel/CanceledError.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/core/settle.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/cookies.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/isAbsoluteURL.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/combineURLs.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/core/buildFullPath.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/isURLSameOrigin.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/parseProtocol.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/speedometer.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/adapters/xhr.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/adapters/adapters.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/core/dispatchRequest.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/core/mergeConfig.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/env/data.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/validator.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/core/Axios.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/cancel/CancelToken.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/spread.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/isAxiosError.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/helpers/HttpStatusCode.js", "../../../node_modules/@mailupinc/bee-plugin/node_modules/axios/lib/axios.js", "../../../node_modules/@mailupinc/bee-plugin/src/services/axios.ts", "../../../node_modules/@mailupinc/bee-plugin/src/services/api.ts", "../../../node_modules/@mailupinc/bee-plugin/src/utils/utils.ts", "../../../node_modules/@mailupinc/bee-plugin/src/index.ts", "../../javascript/controllers/marketing_templates_controller.js", "../../javascript/controllers/message_templates/image_controller.js", "../../javascript/controllers/message_templates/type_selection_controller.js", "../../javascript/controllers/messenger_access_controller.js", "../../javascript/controllers/mfa_controller.js", "../../javascript/controllers/modal_controller.js", "../../javascript/controllers/notifications/dropdown_controller.js", "../../javascript/controllers/pdf_fill_drawer_controller.js", "../../javascript/controllers/popover_controller.js", "../../javascript/controllers/posthog_controller.js", "../../javascript/controllers/prompt_controller.js", "../../javascript/controllers/quote_sheets/quotes_controller.js", "../../javascript/controllers/quote_sheets/summaries_controller.js", "../../javascript/controllers/quote_sheets/taxes_controller.js", "../../javascript/controllers/quote_sheets/vehicles_controller.js", "../../javascript/utils/modal.js", "../../javascript/controllers/reassignment_controller.js", "../../javascript/controllers/release_notes/load_more_controller.js", "../../javascript/controllers/reports/activity_controller.js", "../../javascript/controllers/reports/aisa_dashboard_controller.js", "../../javascript/controllers/reports/elead_provider_controller.js", "../../javascript/controllers/reports/insights_controller.js", "../../javascript/controllers/reports/performance_controller.js", "../../javascript/controllers/reports/sources_controller.js", "../../javascript/controllers/reports/sr_activity_controller.js", "../../javascript/controllers/resizable_controller.js", "../../javascript/controllers/resizable_text_messages_controller.js", "../../javascript/controllers/sales_stages_settings_controller.js", "../../javascript/controllers/scandit/vin_controller.js", "../../javascript/controllers/scheduled_message_edit_controller.js", "../../javascript/controllers/scheduled_messages_controller.js", "../../javascript/controllers/scheduled_task_edit_controller.js", "../../javascript/controllers/settings_mode_controller.js", "../../javascript/controllers/signature/picker_controller.js", "../../javascript/sms/gsm7.ts", "../../javascript/sms/delivery_risk.ts", "../../javascript/controllers/sms_campaign/compose_controller.js", "../../javascript/controllers/sticky_table_header_controller.js", "../../javascript/controllers/support_chat_controller.js", "../../javascript/controllers/task_gating_toggle_controller.js", "../../javascript/controllers/task_templates/form_controller.js", "../../javascript/controllers/template_fields_filter_controller.js", "../../../node_modules/flatpickr/dist/esm/types/options.js", "../../../node_modules/flatpickr/dist/esm/l10n/default.js", "../../../node_modules/flatpickr/dist/esm/utils/index.js", "../../../node_modules/flatpickr/dist/esm/utils/dom.js", "../../../node_modules/flatpickr/dist/esm/utils/formatting.js", "../../../node_modules/flatpickr/dist/esm/utils/dates.js", "../../../node_modules/flatpickr/dist/esm/utils/polyfills.js", "../../../node_modules/flatpickr/dist/esm/index.js", "../../javascript/controllers/time_picker_controller.js", "../../javascript/controllers/toggle_switch_controller.js", "../../javascript/controllers/tooltip_controller.js", "../../javascript/controllers/transient_controller.js", "../../javascript/controllers/tree_controller.js", "../../javascript/controllers/ui/collection_controller.js", "../../javascript/controllers/ui/copyable_controller.js", "../../javascript/controllers/ui/date_range_picker_controller.js", "../../javascript/controllers/ui/password_toggle_controller.js", "../../javascript/utils/template_renderer.js", "../../javascript/controllers/ui/select_controller.js", "../../javascript/controllers/ui/sortable_controller.js", "../../javascript/controllers/ui/tabs_controller.js", "../../javascript/controllers/upsheet/action_bar_controller.js", "../../javascript/controllers/upsheet/appointment_controller.js", "../../javascript/controllers/upsheet/appointment_time_range_controller.js", "../../javascript/controllers/upsheet/bulk_assign_controller.js", "../../javascript/controllers/upsheet/bulk_sales_stage_controller.js", "../../javascript/controllers/upsheet/buyer_invite_controller.js", "../../javascript/controllers/upsheet/category_descriptions_controller.js", "../../javascript/controllers/upsheet/contact_summary_controller.js", "../../javascript/controllers/upsheet/contacts_merge_controller.js", "../../javascript/controllers/upsheet/crs_score_update_controller.js", "../../javascript/controllers/upsheet/crs_soft_pull_controller.js", "../../javascript/controllers/upsheet/delivery_controller.js", "../../javascript/controllers/upsheet/file_controller.js", "../../javascript/controllers/upsheet/form_controller.js", "../../javascript/controllers/upsheet/inline_schedule_controller.js", "../../javascript/controllers/upsheet/integration_controller.js", "../../javascript/controllers/upsheet/list/cards_controller.js", "../../javascript/controllers/upsheet/lost_controller.js", "../../javascript/controllers/upsheet/mention_autocomplete_controller.js", "../../javascript/controllers/upsheet/metadata_controller.js", "../../javascript/controllers/upsheet/note_editor_controller.js", "../../javascript/controllers/upsheet/sales_stage_controller.js", "../../javascript/controllers/upsheet/search_controller.js", "../../javascript/controllers/upsheet/sms_draft_controller.js", "../../javascript/controllers/upsheet/tasks_controller.js", "../../javascript/controllers/upsheet/temp_chooser_controller.js", "../../javascript/controllers/upsheet/temp_popover_controller.js", "../../javascript/sms/segments.ts", "../../javascript/controllers/upsheet/text_conversation_controller.js", "../../javascript/controllers/upsheet/text_schedule_controller.js", "../../javascript/controllers/upsheet/texting_controller.js", "../../javascript/controllers/upsheet/texting_permissions_controller.js", "../../javascript/controllers/upsheet/trades_controller.js", "../../javascript/controllers/upsheet/vehicle_chooser_controller.js", "../../javascript/controllers/url_shortener_controller.js", "../../javascript/controllers/user/billing_controller.js", "../../javascript/controllers/user/debug_controller.js", "../../javascript/controllers/user/settings_controller.js", "../../javascript/controllers/user/work_hours_controller.js", "../../javascript/controllers/vehicles/chrome_option_controller.js", "../../javascript/controllers/vehicles/chrome_picker_controller.js", "../../javascript/controllers/vehicles/live_search_controller.js", "../../javascript/controllers/vehicles/search_controller.js", "../../javascript/controllers/voice_agent_preview_controller.js", "../../javascript/controllers/vonage_form_controller.js", "../../javascript/controllers/index.js"], "sourcesContent": ["/*!\n * Toastify js 1.12.0\n * https://github.com/apvarun/toastify-js\n * @license MIT licensed\n *\n * Copyright (C) 2018 Varun A P\n */\n(function(root, factory) {\n if (typeof module === \"object\" && module.exports) {\n module.exports = factory();\n } else {\n root.Toastify = factory();\n }\n})(this, function(global) {\n // Object initialization\n var Toastify = function(options) {\n // Returning a new init object\n return new Toastify.lib.init(options);\n },\n // Library version\n version = \"1.12.0\";\n\n // Set the default global options\n Toastify.defaults = {\n oldestFirst: true,\n text: \"Toastify is awesome!\",\n node: undefined,\n duration: 3000,\n selector: undefined,\n callback: function () {\n },\n destination: undefined,\n newWindow: false,\n close: false,\n gravity: \"toastify-top\",\n positionLeft: false,\n position: '',\n backgroundColor: '',\n avatar: \"\",\n className: \"\",\n stopOnFocus: true,\n onClick: function () {\n },\n offset: {x: 0, y: 0},\n escapeMarkup: true,\n ariaLive: 'polite',\n style: {background: ''}\n };\n\n // Defining the prototype of the object\n Toastify.lib = Toastify.prototype = {\n toastify: version,\n\n constructor: Toastify,\n\n // Initializing the object with required parameters\n init: function(options) {\n // Verifying and validating the input object\n if (!options) {\n options = {};\n }\n\n // Creating the options object\n this.options = {};\n\n this.toastElement = null;\n\n // Validating the options\n this.options.text = options.text || Toastify.defaults.text; // Display message\n this.options.node = options.node || Toastify.defaults.node; // Display content as node\n this.options.duration = options.duration === 0 ? 0 : options.duration || Toastify.defaults.duration; // Display duration\n this.options.selector = options.selector || Toastify.defaults.selector; // Parent selector\n this.options.callback = options.callback || Toastify.defaults.callback; // Callback after display\n this.options.destination = options.destination || Toastify.defaults.destination; // On-click destination\n this.options.newWindow = options.newWindow || Toastify.defaults.newWindow; // Open destination in new window\n this.options.close = options.close || Toastify.defaults.close; // Show toast close icon\n this.options.gravity = options.gravity === \"bottom\" ? \"toastify-bottom\" : Toastify.defaults.gravity; // toast position - top or bottom\n this.options.positionLeft = options.positionLeft || Toastify.defaults.positionLeft; // toast position - left or right\n this.options.position = options.position || Toastify.defaults.position; // toast position - left or right\n this.options.backgroundColor = options.backgroundColor || Toastify.defaults.backgroundColor; // toast background color\n this.options.avatar = options.avatar || Toastify.defaults.avatar; // img element src - url or a path\n this.options.className = options.className || Toastify.defaults.className; // additional class names for the toast\n this.options.stopOnFocus = options.stopOnFocus === undefined ? Toastify.defaults.stopOnFocus : options.stopOnFocus; // stop timeout on focus\n this.options.onClick = options.onClick || Toastify.defaults.onClick; // Callback after click\n this.options.offset = options.offset || Toastify.defaults.offset; // toast offset\n this.options.escapeMarkup = options.escapeMarkup !== undefined ? options.escapeMarkup : Toastify.defaults.escapeMarkup;\n this.options.ariaLive = options.ariaLive || Toastify.defaults.ariaLive;\n this.options.style = options.style || Toastify.defaults.style;\n if(options.backgroundColor) {\n this.options.style.background = options.backgroundColor;\n }\n\n // Returning the current object for chaining functions\n return this;\n },\n\n // Building the DOM element\n buildToast: function() {\n // Validating if the options are defined\n if (!this.options) {\n throw \"Toastify is not initialized\";\n }\n\n // Creating the DOM object\n var divElement = document.createElement(\"div\");\n divElement.className = \"toastify on \" + this.options.className;\n\n // Positioning toast to left or right or center\n if (!!this.options.position) {\n divElement.className += \" toastify-\" + this.options.position;\n } else {\n // To be depreciated in further versions\n if (this.options.positionLeft === true) {\n divElement.className += \" toastify-left\";\n console.warn('Property `positionLeft` will be depreciated in further versions. Please use `position` instead.')\n } else {\n // Default position\n divElement.className += \" toastify-right\";\n }\n }\n\n // Assigning gravity of element\n divElement.className += \" \" + this.options.gravity;\n\n if (this.options.backgroundColor) {\n // This is being deprecated in favor of using the style HTML DOM property\n console.warn('DEPRECATION NOTICE: \"backgroundColor\" is being deprecated. Please use the \"style.background\" property.');\n }\n\n // Loop through our style object and apply styles to divElement\n for (var property in this.options.style) {\n divElement.style[property] = this.options.style[property];\n }\n\n // Announce the toast to screen readers\n if (this.options.ariaLive) {\n divElement.setAttribute('aria-live', this.options.ariaLive)\n }\n\n // Adding the toast message/node\n if (this.options.node && this.options.node.nodeType === Node.ELEMENT_NODE) {\n // If we have a valid node, we insert it\n divElement.appendChild(this.options.node)\n } else {\n if (this.options.escapeMarkup) {\n divElement.innerText = this.options.text;\n } else {\n divElement.innerHTML = this.options.text;\n }\n\n if (this.options.avatar !== \"\") {\n var avatarElement = document.createElement(\"img\");\n avatarElement.src = this.options.avatar;\n\n avatarElement.className = \"toastify-avatar\";\n\n if (this.options.position == \"left\" || this.options.positionLeft === true) {\n // Adding close icon on the left of content\n divElement.appendChild(avatarElement);\n } else {\n // Adding close icon on the right of content\n divElement.insertAdjacentElement(\"afterbegin\", avatarElement);\n }\n }\n }\n\n // Adding a close icon to the toast\n if (this.options.close === true) {\n // Create a span for close element\n var closeElement = document.createElement(\"button\");\n closeElement.type = \"button\";\n closeElement.setAttribute(\"aria-label\", \"Close\");\n closeElement.className = \"toast-close\";\n closeElement.innerHTML = \"✖\";\n\n // Triggering the removal of toast from DOM on close click\n closeElement.addEventListener(\n \"click\",\n function(event) {\n event.stopPropagation();\n this.removeElement(this.toastElement);\n window.clearTimeout(this.toastElement.timeOutValue);\n }.bind(this)\n );\n\n //Calculating screen width\n var width = window.innerWidth > 0 ? window.innerWidth : screen.width;\n\n // Adding the close icon to the toast element\n // Display on the right if screen width is less than or equal to 360px\n if ((this.options.position == \"left\" || this.options.positionLeft === true) && width > 360) {\n // Adding close icon on the left of content\n divElement.insertAdjacentElement(\"afterbegin\", closeElement);\n } else {\n // Adding close icon on the right of content\n divElement.appendChild(closeElement);\n }\n }\n\n // Clear timeout while toast is focused\n if (this.options.stopOnFocus && this.options.duration > 0) {\n var self = this;\n // stop countdown\n divElement.addEventListener(\n \"mouseover\",\n function(event) {\n window.clearTimeout(divElement.timeOutValue);\n }\n )\n // add back the timeout\n divElement.addEventListener(\n \"mouseleave\",\n function() {\n divElement.timeOutValue = window.setTimeout(\n function() {\n // Remove the toast from DOM\n self.removeElement(divElement);\n },\n self.options.duration\n )\n }\n )\n }\n\n // Adding an on-click destination path\n if (typeof this.options.destination !== \"undefined\") {\n divElement.addEventListener(\n \"click\",\n function(event) {\n event.stopPropagation();\n if (this.options.newWindow === true) {\n window.open(this.options.destination, \"_blank\");\n } else {\n window.location = this.options.destination;\n }\n }.bind(this)\n );\n }\n\n if (typeof this.options.onClick === \"function\" && typeof this.options.destination === \"undefined\") {\n divElement.addEventListener(\n \"click\",\n function(event) {\n event.stopPropagation();\n this.options.onClick();\n }.bind(this)\n );\n }\n\n // Adding offset\n if(typeof this.options.offset === \"object\") {\n\n var x = getAxisOffsetAValue(\"x\", this.options);\n var y = getAxisOffsetAValue(\"y\", this.options);\n\n var xOffset = this.options.position == \"left\" ? x : \"-\" + x;\n var yOffset = this.options.gravity == \"toastify-top\" ? y : \"-\" + y;\n\n divElement.style.transform = \"translate(\" + xOffset + \",\" + yOffset + \")\";\n\n }\n\n // Returning the generated element\n return divElement;\n },\n\n // Displaying the toast\n showToast: function() {\n // Creating the DOM object for the toast\n this.toastElement = this.buildToast();\n\n // Getting the root element to with the toast needs to be added\n var rootElement;\n if (typeof this.options.selector === \"string\") {\n rootElement = document.getElementById(this.options.selector);\n } else if (this.options.selector instanceof HTMLElement || (typeof ShadowRoot !== 'undefined' && this.options.selector instanceof ShadowRoot)) {\n rootElement = this.options.selector;\n } else {\n rootElement = document.body;\n }\n\n // Validating if root element is present in DOM\n if (!rootElement) {\n throw \"Root element is not defined\";\n }\n\n // Adding the DOM element\n var elementToInsert = Toastify.defaults.oldestFirst ? rootElement.firstChild : rootElement.lastChild;\n rootElement.insertBefore(this.toastElement, elementToInsert);\n\n // Repositioning the toasts in case multiple toasts are present\n Toastify.reposition();\n\n if (this.options.duration > 0) {\n this.toastElement.timeOutValue = window.setTimeout(\n function() {\n // Remove the toast from DOM\n this.removeElement(this.toastElement);\n }.bind(this),\n this.options.duration\n ); // Binding `this` for function invocation\n }\n\n // Supporting function chaining\n return this;\n },\n\n hideToast: function() {\n if (this.toastElement.timeOutValue) {\n clearTimeout(this.toastElement.timeOutValue);\n }\n this.removeElement(this.toastElement);\n },\n\n // Removing the element from the DOM\n removeElement: function(toastElement) {\n // Hiding the element\n // toastElement.classList.remove(\"on\");\n toastElement.className = toastElement.className.replace(\" on\", \"\");\n\n // Removing the element from DOM after transition end\n window.setTimeout(\n function() {\n // remove options node if any\n if (this.options.node && this.options.node.parentNode) {\n this.options.node.parentNode.removeChild(this.options.node);\n }\n\n // Remove the element from the DOM, only when the parent node was not removed before.\n if (toastElement.parentNode) {\n toastElement.parentNode.removeChild(toastElement);\n }\n\n // Calling the callback function\n this.options.callback.call(toastElement);\n\n // Repositioning the toasts again\n Toastify.reposition();\n }.bind(this),\n 400\n ); // Binding `this` for function invocation\n },\n };\n\n // Positioning the toasts on the DOM\n Toastify.reposition = function() {\n\n // Top margins with gravity\n var topLeftOffsetSize = {\n top: 15,\n bottom: 15,\n };\n var topRightOffsetSize = {\n top: 15,\n bottom: 15,\n };\n var offsetSize = {\n top: 15,\n bottom: 15,\n };\n\n // Get all toast messages on the DOM\n var allToasts = document.getElementsByClassName(\"toastify\");\n\n var classUsed;\n\n // Modifying the position of each toast element\n for (var i = 0; i < allToasts.length; i++) {\n // Getting the applied gravity\n if (containsClass(allToasts[i], \"toastify-top\") === true) {\n classUsed = \"toastify-top\";\n } else {\n classUsed = \"toastify-bottom\";\n }\n\n var height = allToasts[i].offsetHeight;\n classUsed = classUsed.substr(9, classUsed.length-1)\n // Spacing between toasts\n var offset = 15;\n\n var width = window.innerWidth > 0 ? window.innerWidth : screen.width;\n\n // Show toast in center if screen with less than or equal to 360px\n if (width <= 360) {\n // Setting the position\n allToasts[i].style[classUsed] = offsetSize[classUsed] + \"px\";\n\n offsetSize[classUsed] += height + offset;\n } else {\n if (containsClass(allToasts[i], \"toastify-left\") === true) {\n // Setting the position\n allToasts[i].style[classUsed] = topLeftOffsetSize[classUsed] + \"px\";\n\n topLeftOffsetSize[classUsed] += height + offset;\n } else {\n // Setting the position\n allToasts[i].style[classUsed] = topRightOffsetSize[classUsed] + \"px\";\n\n topRightOffsetSize[classUsed] += height + offset;\n }\n }\n }\n\n // Supporting function chaining\n return this;\n };\n\n // Helper function to get offset.\n function getAxisOffsetAValue(axis, options) {\n\n if(options.offset[axis]) {\n if(isNaN(options.offset[axis])) {\n return options.offset[axis];\n }\n else {\n return options.offset[axis] + 'px';\n }\n }\n\n return '0px';\n\n }\n\n function containsClass(elem, yourClass) {\n if (!elem || typeof yourClass !== \"string\") {\n return false;\n } else if (\n elem.className &&\n elem.className\n .trim()\n .split(/\\s+/gi)\n .indexOf(yourClass) > -1\n ) {\n return true;\n } else {\n return false;\n }\n }\n\n // Setting up the prototype for the init object\n Toastify.lib.init.prototype = Toastify.lib;\n\n // Returning the Toastify function to be assigned to the window object/module\n return Toastify;\n});\n", "export default {\n logger: typeof console !== \"undefined\" ? console : undefined,\n WebSocket: typeof WebSocket !== \"undefined\" ? WebSocket : undefined,\n}\n", "import adapters from \"./adapters\"\n\n// The logger is disabled by default. You can enable it with:\n//\n// ActionCable.logger.enabled = true\n//\n// Example:\n//\n// import * as ActionCable from '@rails/actioncable'\n//\n// ActionCable.logger.enabled = true\n// ActionCable.logger.log('Connection Established.')\n//\n\nexport default {\n log(...messages) {\n if (this.enabled) {\n messages.push(Date.now())\n adapters.logger.log(\"[ActionCable]\", ...messages)\n }\n },\n}\n", "import logger from \"./logger\"\n\n// Responsible for ensuring the cable connection is in good health by validating the heartbeat pings sent from the server, and attempting\n// revival reconnections if things go astray. Internal class, not intended for direct user manipulation.\n\nconst now = () => new Date().getTime()\n\nconst secondsSince = time => (now() - time) / 1000\n\nclass ConnectionMonitor {\n constructor(connection) {\n this.visibilityDidChange = this.visibilityDidChange.bind(this)\n this.connection = connection\n this.reconnectAttempts = 0\n }\n\n start() {\n if (!this.isRunning()) {\n this.startedAt = now()\n delete this.stoppedAt\n this.startPolling()\n addEventListener(\"visibilitychange\", this.visibilityDidChange)\n logger.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`)\n }\n }\n\n stop() {\n if (this.isRunning()) {\n this.stoppedAt = now()\n this.stopPolling()\n removeEventListener(\"visibilitychange\", this.visibilityDidChange)\n logger.log(\"ConnectionMonitor stopped\")\n }\n }\n\n isRunning() {\n return this.startedAt && !this.stoppedAt\n }\n\n recordMessage() {\n this.pingedAt = now()\n }\n\n recordConnect() {\n this.reconnectAttempts = 0\n delete this.disconnectedAt\n logger.log(\"ConnectionMonitor recorded connect\")\n }\n\n recordDisconnect() {\n this.disconnectedAt = now()\n logger.log(\"ConnectionMonitor recorded disconnect\")\n }\n\n // Private\n\n startPolling() {\n this.stopPolling()\n this.poll()\n }\n\n stopPolling() {\n clearTimeout(this.pollTimeout)\n }\n\n poll() {\n this.pollTimeout = setTimeout(() => {\n this.reconnectIfStale()\n this.poll()\n }\n , this.getPollInterval())\n }\n\n getPollInterval() {\n const { staleThreshold, reconnectionBackoffRate } = this.constructor\n const backoff = Math.pow(1 + reconnectionBackoffRate, Math.min(this.reconnectAttempts, 10))\n const jitterMax = this.reconnectAttempts === 0 ? 1.0 : reconnectionBackoffRate\n const jitter = jitterMax * Math.random()\n return staleThreshold * 1000 * backoff * (1 + jitter)\n }\n\n reconnectIfStale() {\n if (this.connectionIsStale()) {\n logger.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${secondsSince(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`)\n this.reconnectAttempts++\n if (this.disconnectedRecently()) {\n logger.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${secondsSince(this.disconnectedAt)} s`)\n } else {\n logger.log(\"ConnectionMonitor reopening\")\n this.connection.reopen()\n }\n }\n }\n\n get refreshedAt() {\n return this.pingedAt ? this.pingedAt : this.startedAt\n }\n\n connectionIsStale() {\n return secondsSince(this.refreshedAt) > this.constructor.staleThreshold\n }\n\n disconnectedRecently() {\n return this.disconnectedAt && (secondsSince(this.disconnectedAt) < this.constructor.staleThreshold)\n }\n\n visibilityDidChange() {\n if (document.visibilityState === \"visible\") {\n setTimeout(() => {\n if (this.connectionIsStale() || !this.connection.isOpen()) {\n logger.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`)\n this.connection.reopen()\n }\n }\n , 200)\n }\n }\n\n}\n\nConnectionMonitor.staleThreshold = 6 // Server::Connections::BEAT_INTERVAL * 2 (missed two pings)\nConnectionMonitor.reconnectionBackoffRate = 0.15\n\nexport default ConnectionMonitor\n", "export default {\n \"message_types\": {\n \"welcome\": \"welcome\",\n \"disconnect\": \"disconnect\",\n \"ping\": \"ping\",\n \"confirmation\": \"confirm_subscription\",\n \"rejection\": \"reject_subscription\"\n },\n \"disconnect_reasons\": {\n \"unauthorized\": \"unauthorized\",\n \"invalid_request\": \"invalid_request\",\n \"server_restart\": \"server_restart\",\n \"remote\": \"remote\"\n },\n \"default_mount_path\": \"/cable\",\n \"protocols\": [\n \"actioncable-v1-json\",\n \"actioncable-unsupported\"\n ]\n}\n", "import adapters from \"./adapters\"\nimport ConnectionMonitor from \"./connection_monitor\"\nimport INTERNAL from \"./internal\"\nimport logger from \"./logger\"\n\n// Encapsulate the cable connection held by the consumer. This is an internal class not intended for direct user manipulation.\n\nconst {message_types, protocols} = INTERNAL\nconst supportedProtocols = protocols.slice(0, protocols.length - 1)\n\nconst indexOf = [].indexOf\n\nclass Connection {\n constructor(consumer) {\n this.open = this.open.bind(this)\n this.consumer = consumer\n this.subscriptions = this.consumer.subscriptions\n this.monitor = new ConnectionMonitor(this)\n this.disconnected = true\n }\n\n send(data) {\n if (this.isOpen()) {\n this.webSocket.send(JSON.stringify(data))\n return true\n } else {\n return false\n }\n }\n\n open() {\n if (this.isActive()) {\n logger.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`)\n return false\n } else {\n const socketProtocols = [...protocols, ...this.consumer.subprotocols || []]\n logger.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${socketProtocols}`)\n if (this.webSocket) { this.uninstallEventHandlers() }\n this.webSocket = new adapters.WebSocket(this.consumer.url, socketProtocols)\n this.installEventHandlers()\n this.monitor.start()\n return true\n }\n }\n\n close({allowReconnect} = {allowReconnect: true}) {\n if (!allowReconnect) { this.monitor.stop() }\n // Avoid closing websockets in a \"connecting\" state due to Safari 15.1+ bug. See: https://github.com/rails/rails/issues/43835#issuecomment-1002288478\n if (this.isOpen()) {\n return this.webSocket.close()\n }\n }\n\n reopen() {\n logger.log(`Reopening WebSocket, current state is ${this.getState()}`)\n if (this.isActive()) {\n try {\n return this.close()\n } catch (error) {\n logger.log(\"Failed to reopen WebSocket\", error)\n }\n finally {\n logger.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`)\n setTimeout(this.open, this.constructor.reopenDelay)\n }\n } else {\n return this.open()\n }\n }\n\n getProtocol() {\n if (this.webSocket) {\n return this.webSocket.protocol\n }\n }\n\n isOpen() {\n return this.isState(\"open\")\n }\n\n isActive() {\n return this.isState(\"open\", \"connecting\")\n }\n\n triedToReconnect() {\n return this.monitor.reconnectAttempts > 0\n }\n\n // Private\n\n isProtocolSupported() {\n return indexOf.call(supportedProtocols, this.getProtocol()) >= 0\n }\n\n isState(...states) {\n return indexOf.call(states, this.getState()) >= 0\n }\n\n getState() {\n if (this.webSocket) {\n for (let state in adapters.WebSocket) {\n if (adapters.WebSocket[state] === this.webSocket.readyState) {\n return state.toLowerCase()\n }\n }\n }\n return null\n }\n\n installEventHandlers() {\n for (let eventName in this.events) {\n const handler = this.events[eventName].bind(this)\n this.webSocket[`on${eventName}`] = handler\n }\n }\n\n uninstallEventHandlers() {\n for (let eventName in this.events) {\n this.webSocket[`on${eventName}`] = function() {}\n }\n }\n\n}\n\nConnection.reopenDelay = 500\n\nConnection.prototype.events = {\n message(event) {\n if (!this.isProtocolSupported()) { return }\n const {identifier, message, reason, reconnect, type} = JSON.parse(event.data)\n this.monitor.recordMessage()\n switch (type) {\n case message_types.welcome:\n if (this.triedToReconnect()) {\n this.reconnectAttempted = true\n }\n this.monitor.recordConnect()\n return this.subscriptions.reload()\n case message_types.disconnect:\n logger.log(`Disconnecting. Reason: ${reason}`)\n return this.close({allowReconnect: reconnect})\n case message_types.ping:\n return null\n case message_types.confirmation:\n this.subscriptions.confirmSubscription(identifier)\n if (this.reconnectAttempted) {\n this.reconnectAttempted = false\n return this.subscriptions.notify(identifier, \"connected\", {reconnected: true})\n } else {\n return this.subscriptions.notify(identifier, \"connected\", {reconnected: false})\n }\n case message_types.rejection:\n return this.subscriptions.reject(identifier)\n default:\n return this.subscriptions.notify(identifier, \"received\", message)\n }\n },\n\n open() {\n logger.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`)\n this.disconnected = false\n if (!this.isProtocolSupported()) {\n logger.log(\"Protocol is unsupported. Stopping monitor and disconnecting.\")\n return this.close({allowReconnect: false})\n }\n },\n\n close(event) {\n logger.log(\"WebSocket onclose event\")\n if (this.disconnected) { return }\n this.disconnected = true\n this.monitor.recordDisconnect()\n return this.subscriptions.notifyAll(\"disconnected\", {willAttemptReconnect: this.monitor.isRunning()})\n },\n\n error() {\n logger.log(\"WebSocket onerror event\")\n }\n}\n\nexport default Connection\n", "// A new subscription is created through the ActionCable.Subscriptions instance available on the consumer.\n// It provides a number of callbacks and a method for calling remote procedure calls on the corresponding\n// Channel instance on the server side.\n//\n// An example demonstrates the basic functionality:\n//\n// App.appearance = App.cable.subscriptions.create(\"AppearanceChannel\", {\n// connected() {\n// // Called once the subscription has been successfully completed\n// },\n//\n// disconnected({ willAttemptReconnect: boolean }) {\n// // Called when the client has disconnected with the server.\n// // The object will have an `willAttemptReconnect` property which\n// // says whether the client has the intention of attempting\n// // to reconnect.\n// },\n//\n// appear() {\n// this.perform('appear', {appearing_on: this.appearingOn()})\n// },\n//\n// away() {\n// this.perform('away')\n// },\n//\n// appearingOn() {\n// $('main').data('appearing-on')\n// }\n// })\n//\n// The methods #appear and #away forward their intent to the remote AppearanceChannel instance on the server\n// by calling the `perform` method with the first parameter being the action (which maps to AppearanceChannel#appear/away).\n// The second parameter is a hash that'll get JSON encoded and made available on the server in the data parameter.\n//\n// This is how the server component would look:\n//\n// class AppearanceChannel < ApplicationActionCable::Channel\n// def subscribed\n// current_user.appear\n// end\n//\n// def unsubscribed\n// current_user.disappear\n// end\n//\n// def appear(data)\n// current_user.appear on: data['appearing_on']\n// end\n//\n// def away\n// current_user.away\n// end\n// end\n//\n// The \"AppearanceChannel\" name is automatically mapped between the client-side subscription creation and the server-side Ruby class name.\n// The AppearanceChannel#appear/away public methods are exposed automatically to client-side invocation through the perform method.\n\nconst extend = function(object, properties) {\n if (properties != null) {\n for (let key in properties) {\n const value = properties[key]\n object[key] = value\n }\n }\n return object\n}\n\nexport default class Subscription {\n constructor(consumer, params = {}, mixin) {\n this.consumer = consumer\n this.identifier = JSON.stringify(params)\n extend(this, mixin)\n }\n\n // Perform a channel action with the optional data passed as an attribute\n perform(action, data = {}) {\n data.action = action\n return this.send(data)\n }\n\n send(data) {\n return this.consumer.send({command: \"message\", identifier: this.identifier, data: JSON.stringify(data)})\n }\n\n unsubscribe() {\n return this.consumer.subscriptions.remove(this)\n }\n}\n", "import logger from \"./logger\"\n\n// Responsible for ensuring channel subscribe command is confirmed, retrying until confirmation is received.\n// Internal class, not intended for direct user manipulation.\n\nclass SubscriptionGuarantor {\n constructor(subscriptions) {\n this.subscriptions = subscriptions\n this.pendingSubscriptions = []\n }\n\n guarantee(subscription) {\n if(this.pendingSubscriptions.indexOf(subscription) == -1){ \n logger.log(`SubscriptionGuarantor guaranteeing ${subscription.identifier}`)\n this.pendingSubscriptions.push(subscription) \n }\n else {\n logger.log(`SubscriptionGuarantor already guaranteeing ${subscription.identifier}`)\n }\n this.startGuaranteeing()\n }\n\n forget(subscription) {\n logger.log(`SubscriptionGuarantor forgetting ${subscription.identifier}`)\n this.pendingSubscriptions = (this.pendingSubscriptions.filter((s) => s !== subscription))\n }\n\n startGuaranteeing() {\n this.stopGuaranteeing()\n this.retrySubscribing()\n }\n \n stopGuaranteeing() {\n clearTimeout(this.retryTimeout)\n }\n\n retrySubscribing() {\n this.retryTimeout = setTimeout(() => {\n if (this.subscriptions && typeof(this.subscriptions.subscribe) === \"function\") {\n this.pendingSubscriptions.map((subscription) => {\n logger.log(`SubscriptionGuarantor resubscribing ${subscription.identifier}`)\n this.subscriptions.subscribe(subscription)\n })\n }\n }\n , 500)\n }\n}\n\nexport default SubscriptionGuarantor", "import logger from \"./logger\"\nimport Subscription from \"./subscription\"\nimport SubscriptionGuarantor from \"./subscription_guarantor\"\n\n// Collection class for creating (and internally managing) channel subscriptions.\n// The only method intended to be triggered by the user is ActionCable.Subscriptions#create,\n// and it should be called through the consumer like so:\n//\n// App = {}\n// App.cable = ActionCable.createConsumer(\"ws://example.com/accounts/1\")\n// App.appearance = App.cable.subscriptions.create(\"AppearanceChannel\")\n//\n// For more details on how you'd configure an actual channel subscription, see ActionCable.Subscription.\n\nexport default class Subscriptions {\n constructor(consumer) {\n this.consumer = consumer\n this.guarantor = new SubscriptionGuarantor(this)\n this.subscriptions = []\n }\n\n create(channelName, mixin) {\n const channel = channelName\n const params = typeof channel === \"object\" ? channel : {channel}\n const subscription = new Subscription(this.consumer, params, mixin)\n return this.add(subscription)\n }\n\n // Private\n\n add(subscription) {\n this.subscriptions.push(subscription)\n this.consumer.ensureActiveConnection()\n this.notify(subscription, \"initialized\")\n this.subscribe(subscription)\n return subscription\n }\n\n remove(subscription) {\n this.forget(subscription)\n if (!this.findAll(subscription.identifier).length) {\n this.sendCommand(subscription, \"unsubscribe\")\n }\n return subscription\n }\n\n reject(identifier) {\n return this.findAll(identifier).map((subscription) => {\n this.forget(subscription)\n this.notify(subscription, \"rejected\")\n return subscription\n })\n }\n\n forget(subscription) {\n this.guarantor.forget(subscription)\n this.subscriptions = (this.subscriptions.filter((s) => s !== subscription))\n return subscription\n }\n\n findAll(identifier) {\n return this.subscriptions.filter((s) => s.identifier === identifier)\n }\n\n reload() {\n return this.subscriptions.map((subscription) =>\n this.subscribe(subscription))\n }\n\n notifyAll(callbackName, ...args) {\n return this.subscriptions.map((subscription) =>\n this.notify(subscription, callbackName, ...args))\n }\n\n notify(subscription, callbackName, ...args) {\n let subscriptions\n if (typeof subscription === \"string\") {\n subscriptions = this.findAll(subscription)\n } else {\n subscriptions = [subscription]\n }\n\n return subscriptions.map((subscription) =>\n (typeof subscription[callbackName] === \"function\" ? subscription[callbackName](...args) : undefined))\n }\n\n subscribe(subscription) {\n if (this.sendCommand(subscription, \"subscribe\")) {\n this.guarantor.guarantee(subscription)\n }\n }\n\n confirmSubscription(identifier) {\n logger.log(`Subscription confirmed ${identifier}`)\n this.findAll(identifier).map((subscription) =>\n this.guarantor.forget(subscription))\n }\n\n sendCommand(subscription, command) {\n const {identifier} = subscription\n return this.consumer.send({command, identifier})\n }\n}\n", "import Connection from \"./connection\"\nimport Subscriptions from \"./subscriptions\"\n\n// The ActionCable.Consumer establishes the connection to a server-side Ruby Connection object. Once established,\n// the ActionCable.ConnectionMonitor will ensure that its properly maintained through heartbeats and checking for stale updates.\n// The Consumer instance is also the gateway to establishing subscriptions to desired channels through the #createSubscription\n// method.\n//\n// The following example shows how this can be set up:\n//\n// App = {}\n// App.cable = ActionCable.createConsumer(\"ws://example.com/accounts/1\")\n// App.appearance = App.cable.subscriptions.create(\"AppearanceChannel\")\n//\n// For more details on how you'd configure an actual channel subscription, see ActionCable.Subscription.\n//\n// When a consumer is created, it automatically connects with the server.\n//\n// To disconnect from the server, call\n//\n// App.cable.disconnect()\n//\n// and to restart the connection:\n//\n// App.cable.connect()\n//\n// Any channel subscriptions which existed prior to disconnecting will\n// automatically resubscribe.\n\nexport default class Consumer {\n constructor(url) {\n this._url = url\n this.subscriptions = new Subscriptions(this)\n this.connection = new Connection(this)\n this.subprotocols = []\n }\n\n get url() {\n return createWebSocketURL(this._url)\n }\n\n send(data) {\n return this.connection.send(data)\n }\n\n connect() {\n return this.connection.open()\n }\n\n disconnect() {\n return this.connection.close({allowReconnect: false})\n }\n\n ensureActiveConnection() {\n if (!this.connection.isActive()) {\n return this.connection.open()\n }\n }\n\n addSubProtocol(subprotocol) {\n this.subprotocols = [...this.subprotocols, subprotocol]\n }\n}\n\nexport function createWebSocketURL(url) {\n if (typeof url === \"function\") {\n url = url()\n }\n\n if (url && !/^wss?:/i.test(url)) {\n const a = document.createElement(\"a\")\n a.href = url\n // Fix populating Location properties in IE. Otherwise, protocol will be blank.\n a.href = a.href // eslint-disable-line\n a.protocol = a.protocol.replace(\"http\", \"ws\")\n return a.href\n } else {\n return url\n }\n}\n", "import adapters from \"./adapters\"\nimport Connection from \"./connection\"\nimport ConnectionMonitor from \"./connection_monitor\"\nimport Consumer, { createWebSocketURL } from \"./consumer\"\nimport INTERNAL from \"./internal\"\nimport logger from \"./logger\"\nimport Subscription from \"./subscription\"\nimport SubscriptionGuarantor from \"./subscription_guarantor\"\nimport Subscriptions from \"./subscriptions\"\n\nexport {\n Connection,\n ConnectionMonitor,\n Consumer,\n INTERNAL,\n Subscription,\n Subscriptions,\n SubscriptionGuarantor,\n adapters,\n createWebSocketURL,\n logger,\n}\n\nexport function createConsumer(url = getConfig(\"url\") || INTERNAL.default_mount_path) {\n return new Consumer(url)\n}\n\nexport function getConfig(name) {\n const element = document.head.querySelector(`meta[name='action-cable-${name}']`)\n if (element) {\n return element.getAttribute(\"content\")\n }\n}\n", "/**\n * Copyright (c) 2014-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\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; };\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) });\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = GeneratorFunctionPrototype;\n defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: true });\n defineProperty(\n GeneratorFunctionPrototype,\n \"constructor\",\n { value: GeneratorFunction, configurable: true }\n );\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\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\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n defineProperty(this, \"_invoke\", { value: enqueue });\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n });\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\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\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var methodName = context.method;\n var method = delegate.iterator[methodName];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method, or a missing .next mehtod, always terminate the\n // yield* loop.\n context.delegate = null;\n\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (methodName === \"throw\" && delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n if (methodName !== \"return\") {\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a '\" + methodName + \"' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n define(Gp, iteratorSymbol, function() {\n return this;\n });\n\n define(Gp, \"toString\", function() {\n return \"[object Generator]\";\n });\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(val) {\n var object = Object(val);\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(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 &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(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 (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, in modern engines\n // we can explicitly access globalThis. In older engines we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n", "'use strict';\n\nmodule.exports = (prefix, cnt) => (\n `${prefix}-${cnt}-${Math.random().toString(16).slice(3, 8)}`\n);\n", "'use strict';\n\nconst getId = require('./utils/getId');\n\nlet jobCounter = 0;\n\nmodule.exports = ({\n id: _id,\n action,\n payload = {},\n}) => {\n let id = _id;\n if (typeof id === 'undefined') {\n id = getId('Job', jobCounter);\n jobCounter += 1;\n }\n\n return {\n id,\n action,\n payload,\n };\n};\n", "'use strict';\n\nlet logging = false;\n\nexports.logging = logging;\n\nexports.setLogging = (_logging) => {\n logging = _logging;\n};\n\nexports.log = (...args) => (logging ? console.log.apply(this, args) : null);\n", "'use strict';\n\nconst createJob = require('./createJob');\nconst { log } = require('./utils/log');\nconst getId = require('./utils/getId');\n\nlet schedulerCounter = 0;\n\nmodule.exports = () => {\n const id = getId('Scheduler', schedulerCounter);\n const workers = {};\n const runningWorkers = {};\n let jobQueue = [];\n\n schedulerCounter += 1;\n\n const getQueueLen = () => jobQueue.length;\n const getNumWorkers = () => Object.keys(workers).length;\n\n const dequeue = () => {\n if (jobQueue.length !== 0) {\n const wIds = Object.keys(workers);\n for (let i = 0; i < wIds.length; i += 1) {\n if (typeof runningWorkers[wIds[i]] === 'undefined') {\n jobQueue[0](workers[wIds[i]]);\n break;\n }\n }\n }\n };\n\n const queue = (action, payload) => (\n new Promise((resolve, reject) => {\n const job = createJob({ action, payload });\n jobQueue.push(async (w) => {\n jobQueue.shift();\n runningWorkers[w.id] = job;\n try {\n resolve(await w[action].apply(this, [...payload, job.id]));\n } catch (err) {\n reject(err);\n } finally {\n delete runningWorkers[w.id];\n dequeue();\n }\n });\n log(`[${id}]: Add ${job.id} to JobQueue`);\n log(`[${id}]: JobQueue length=${jobQueue.length}`);\n dequeue();\n })\n );\n\n const addWorker = (w) => {\n workers[w.id] = w;\n log(`[${id}]: Add ${w.id}`);\n log(`[${id}]: Number of workers=${getNumWorkers()}`);\n dequeue();\n return w.id;\n };\n\n const addJob = async (action, ...payload) => {\n if (getNumWorkers() === 0) {\n throw Error(`[${id}]: You need to have at least one worker before adding jobs`);\n }\n return queue(action, payload);\n };\n\n const terminate = async () => {\n Object.keys(workers).forEach(async (wid) => {\n await workers[wid].terminate();\n });\n jobQueue = [];\n };\n\n return {\n addWorker,\n addJob,\n terminate,\n getQueueLen,\n getNumWorkers,\n };\n};\n", "'use strict';\n\nmodule.exports = (key) => {\n const env = {};\n\n if (typeof WorkerGlobalScope !== 'undefined') {\n env.type = 'webworker';\n } else if (typeof document === 'object') {\n env.type = 'browser';\n } else if (typeof process === 'object' && typeof require === 'function') {\n env.type = 'node';\n }\n\n if (typeof key === 'undefined') {\n return env;\n }\n\n return env[key];\n};\n", "'use strict';\n\nconst isBrowser = require('./getEnvironment')('type') === 'browser';\n\nconst resolveURL = isBrowser ? s => (new URL(s, window.location.href)).href : s => s; // eslint-disable-line\n\nmodule.exports = (options) => {\n const opts = { ...options };\n ['corePath', 'workerPath', 'langPath'].forEach((key) => {\n if (options[key]) {\n opts[key] = resolveURL(opts[key]);\n }\n });\n return opts;\n};\n", "'use strict';\n\n/*\n * OEM = OCR Engine Mode, and there are 4 possible modes.\n *\n * By default tesseract.js uses LSTM_ONLY mode.\n *\n */\nmodule.exports = {\n TESSERACT_ONLY: 0,\n LSTM_ONLY: 1,\n TESSERACT_LSTM_COMBINED: 2,\n DEFAULT: 3,\n};\n", "{\n \"name\": \"tesseract.js\",\n \"version\": \"7.0.0\",\n \"description\": \"Pure Javascript Multilingual OCR\",\n \"main\": \"src/index.js\",\n \"type\": \"commonjs\",\n \"types\": \"src/index.d.ts\",\n \"unpkg\": \"dist/tesseract.min.js\",\n \"jsdelivr\": \"dist/tesseract.min.js\",\n \"scripts\": {\n \"start\": \"node scripts/server.js\",\n \"build\": \"rimraf dist && webpack --config scripts/webpack.config.prod.js && rollup -c scripts/rollup.esm.mjs\",\n \"profile:tesseract\": \"webpack-bundle-analyzer dist/tesseract-stats.json\",\n \"profile:worker\": \"webpack-bundle-analyzer dist/worker-stats.json\",\n \"prepublishOnly\": \"npm run build\",\n \"wait\": \"rimraf dist && wait-on http://localhost:3000/dist/tesseract.min.js\",\n \"test\": \"npm-run-all -p -r start test:all\",\n \"test:all\": \"npm-run-all wait test:browser test:node:all\",\n \"test:browser\": \"karma start karma.conf.js\",\n \"test:node\": \"nyc mocha --exit --bail --require ./scripts/test-helper.mjs\",\n \"test:node:all\": \"npm run test:node -- ./tests/*.test.mjs\",\n \"lint\": \"eslint src\",\n \"lint:fix\": \"eslint --fix src\",\n \"postinstall\": \"opencollective-postinstall || true\"\n },\n \"browser\": {\n \"./src/worker/node/index.js\": \"./src/worker/browser/index.js\"\n },\n \"author\": \"\",\n \"contributors\": [\n \"jeromewu\"\n ],\n \"license\": \"Apache-2.0\",\n \"devDependencies\": {\n \"@babel/core\": \"^7.21.4\",\n \"@babel/eslint-parser\": \"^7.21.3\",\n \"@babel/preset-env\": \"^7.21.4\",\n \"@rollup/plugin-commonjs\": \"^24.1.0\",\n \"acorn\": \"^8.8.2\",\n \"babel-loader\": \"^9.1.2\",\n \"buffer\": \"^6.0.3\",\n \"cors\": \"^2.8.5\",\n \"eslint\": \"^7.32.0\",\n \"eslint-config-airbnb-base\": \"^14.2.1\",\n \"eslint-plugin-import\": \"^2.27.5\",\n \"expect.js\": \"^0.3.1\",\n \"express\": \"^4.18.2\",\n \"mocha\": \"^10.2.0\",\n \"npm-run-all\": \"^4.1.5\",\n \"karma\": \"^6.4.2\",\n \"karma-chrome-launcher\": \"^3.2.0\",\n \"karma-firefox-launcher\": \"^2.1.2\",\n \"karma-mocha\": \"^2.0.1\",\n \"karma-webpack\": \"^5.0.0\",\n \"nyc\": \"^15.1.0\",\n \"rimraf\": \"^5.0.0\",\n \"rollup\": \"^3.20.7\",\n \"wait-on\": \"^7.0.1\",\n \"webpack\": \"^5.79.0\",\n \"webpack-bundle-analyzer\": \"^4.8.0\",\n \"webpack-cli\": \"^5.0.1\",\n \"webpack-dev-middleware\": \"^6.0.2\",\n \"rollup-plugin-sourcemaps\": \"^0.6.3\"\n },\n \"dependencies\": {\n \"bmp-js\": \"^0.1.0\",\n \"idb-keyval\": \"^6.2.0\",\n \"is-url\": \"^1.2.4\",\n \"node-fetch\": \"^2.6.9\",\n \"opencollective-postinstall\": \"^2.0.3\",\n \"regenerator-runtime\": \"^0.13.3\",\n \"tesseract.js-core\": \"^7.0.0\",\n \"wasm-feature-detect\": \"^1.8.0\",\n \"zlibjs\": \"^0.3.1\"\n },\n \"overrides\": {\n \"@rollup/pluginutils\": \"^5.0.2\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/naptha/tesseract.js.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/naptha/tesseract.js/issues\"\n },\n \"homepage\": \"https://github.com/naptha/tesseract.js\",\n \"collective\": {\n \"type\": \"opencollective\",\n \"url\": \"https://opencollective.com/tesseractjs\"\n }\n}\n", "'use strict';\n\nmodule.exports = {\n /*\n * Use BlobURL for worker script by default\n * TODO: remove this option\n *\n */\n workerBlobURL: true,\n logger: () => {},\n};\n", "'use strict';\n\nconst version = require('../../../package.json').version;\nconst defaultOptions = require('../../constants/defaultOptions');\n\n/*\n * Default options for browser worker\n */\nmodule.exports = {\n ...defaultOptions,\n workerPath: `https://cdn.jsdelivr.net/npm/tesseract.js@v${version}/dist/worker.min.js`,\n};\n", "'use strict';\n\n/**\n * spawnWorker\n *\n * @name spawnWorker\n * @function create a new Worker in browser\n * @access public\n */\nmodule.exports = ({ workerPath, workerBlobURL }) => {\n let worker;\n if (Blob && URL && workerBlobURL) {\n const blob = new Blob([`importScripts(\"${workerPath}\");`], {\n type: 'application/javascript',\n });\n worker = new Worker(URL.createObjectURL(blob));\n } else {\n worker = new Worker(workerPath);\n }\n\n return worker;\n};\n", "'use strict';\n\n/**\n * terminateWorker\n *\n * @name terminateWorker\n * @function terminate worker\n * @access public\n */\nmodule.exports = (worker) => {\n worker.terminate();\n};\n", "'use strict';\n\nmodule.exports = (worker, handler) => {\n worker.onmessage = ({ data }) => { // eslint-disable-line\n handler(data);\n };\n};\n", "'use strict';\n\n/**\n * send\n *\n * @name send\n * @function send packet to worker and create a job\n * @access public\n */\nmodule.exports = async (worker, packet) => {\n worker.postMessage(packet);\n};\n", "'use strict';\n\n/**\n * readFromBlobOrFile\n *\n * @name readFromBlobOrFile\n * @function\n * @access private\n */\nconst readFromBlobOrFile = (blob) => (\n new Promise((resolve, reject) => {\n const fileReader = new FileReader();\n fileReader.onload = () => {\n resolve(fileReader.result);\n };\n fileReader.onerror = ({ target: { error: { code } } }) => {\n reject(Error(`File could not be read! Code=${code}`));\n };\n fileReader.readAsArrayBuffer(blob);\n })\n);\n\n/**\n * loadImage\n *\n * @name loadImage\n * @function load image from different source\n * @access private\n */\nconst loadImage = async (image) => {\n let data = image;\n if (typeof image === 'undefined') {\n return 'undefined';\n }\n\n if (typeof image === 'string') {\n // Base64 Image\n if (/data:image\\/([a-zA-Z]*);base64,([^\"]*)/.test(image)) {\n data = atob(image.split(',')[1])\n .split('')\n .map((c) => c.charCodeAt(0));\n } else {\n const resp = await fetch(image);\n data = await resp.arrayBuffer();\n }\n } else if (typeof HTMLElement !== 'undefined' && image instanceof HTMLElement) {\n if (image.tagName === 'IMG') {\n data = await loadImage(image.src);\n }\n if (image.tagName === 'VIDEO') {\n data = await loadImage(image.poster);\n }\n if (image.tagName === 'CANVAS') {\n await new Promise((resolve) => {\n image.toBlob(async (blob) => {\n data = await readFromBlobOrFile(blob);\n resolve();\n });\n });\n }\n } else if (typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas) {\n const blob = await image.convertToBlob();\n data = await readFromBlobOrFile(blob);\n } else if (image instanceof File || image instanceof Blob) {\n data = await readFromBlobOrFile(image);\n }\n\n return new Uint8Array(data);\n};\n\nmodule.exports = loadImage;\n", "'use strict';\n\n/**\n *\n * Tesseract Worker adapter for browser\n *\n * @fileoverview Tesseract Worker adapter for browser\n * @author Kevin Kwok \n * @author Guillermo Webster \n * @author Jerome Wu \n */\nconst defaultOptions = require('./defaultOptions');\nconst spawnWorker = require('./spawnWorker');\nconst terminateWorker = require('./terminateWorker');\nconst onMessage = require('./onMessage');\nconst send = require('./send');\nconst loadImage = require('./loadImage');\n\nmodule.exports = {\n defaultOptions,\n spawnWorker,\n terminateWorker,\n onMessage,\n send,\n loadImage,\n};\n", "'use strict';\n\nconst resolvePaths = require('./utils/resolvePaths');\nconst createJob = require('./createJob');\nconst { log } = require('./utils/log');\nconst getId = require('./utils/getId');\nconst OEM = require('./constants/OEM');\nconst {\n defaultOptions,\n spawnWorker,\n terminateWorker,\n onMessage,\n loadImage,\n send,\n} = require('./worker/node');\n\nlet workerCounter = 0;\n\nmodule.exports = async (langs = 'eng', oem = OEM.LSTM_ONLY, _options = {}, config = {}) => {\n const id = getId('Worker', workerCounter);\n const {\n logger,\n errorHandler,\n ...options\n } = resolvePaths({\n ...defaultOptions,\n ..._options,\n });\n const promises = {};\n\n // Current langs, oem, and config file.\n // Used if the user ever re-initializes the worker using `worker.reinitialize`.\n const currentLangs = typeof langs === 'string' ? langs.split('+') : langs;\n let currentOem = oem;\n let currentConfig = config;\n const lstmOnlyCore = [OEM.DEFAULT, OEM.LSTM_ONLY].includes(oem) && !options.legacyCore;\n\n let workerResReject;\n let workerResResolve;\n const workerRes = new Promise((resolve, reject) => {\n workerResResolve = resolve;\n workerResReject = reject;\n });\n const workerError = (event) => { workerResReject(event.message); };\n\n let worker = spawnWorker(options);\n worker.onerror = workerError;\n\n workerCounter += 1;\n\n const startJob = ({ id: jobId, action, payload }) => (\n new Promise((resolve, reject) => {\n log(`[${id}]: Start ${jobId}, action=${action}`);\n // Using both `action` and `jobId` in case user provides non-unique `jobId`.\n const promiseId = `${action}-${jobId}`;\n promises[promiseId] = { resolve, reject };\n send(worker, {\n workerId: id,\n jobId,\n action,\n payload,\n });\n })\n );\n\n const load = () => (\n console.warn('`load` is depreciated and should be removed from code (workers now come pre-loaded)')\n );\n\n const loadInternal = (jobId) => (\n startJob(createJob({\n id: jobId, action: 'load', payload: { options: { lstmOnly: lstmOnlyCore, corePath: options.corePath, logging: options.logging } },\n }))\n );\n\n const writeText = (path, text, jobId) => (\n startJob(createJob({\n id: jobId,\n action: 'FS',\n payload: { method: 'writeFile', args: [path, text] },\n }))\n );\n\n const readText = (path, jobId) => (\n startJob(createJob({\n id: jobId,\n action: 'FS',\n payload: { method: 'readFile', args: [path, { encoding: 'utf8' }] },\n }))\n );\n\n const removeFile = (path, jobId) => (\n startJob(createJob({\n id: jobId,\n action: 'FS',\n payload: { method: 'unlink', args: [path] },\n }))\n );\n\n const FS = (method, args, jobId) => (\n startJob(createJob({\n id: jobId,\n action: 'FS',\n payload: { method, args },\n }))\n );\n\n const loadLanguageInternal = (_langs, jobId) => startJob(createJob({\n id: jobId,\n action: 'loadLanguage',\n payload: {\n langs: _langs,\n options: {\n langPath: options.langPath,\n dataPath: options.dataPath,\n cachePath: options.cachePath,\n cacheMethod: options.cacheMethod,\n gzip: options.gzip,\n lstmOnly: [OEM.DEFAULT, OEM.LSTM_ONLY].includes(currentOem)\n && !options.legacyLang,\n },\n },\n }));\n\n const initializeInternal = (_langs, _oem, _config, jobId) => (\n startJob(createJob({\n id: jobId,\n action: 'initialize',\n payload: { langs: _langs, oem: _oem, config: _config },\n }))\n );\n\n const reinitialize = (langs = 'eng', oem, config, jobId) => { // eslint-disable-line\n\n if (lstmOnlyCore && [OEM.TESSERACT_ONLY, OEM.TESSERACT_LSTM_COMBINED].includes(oem)) throw Error('Legacy model requested but code missing.');\n\n const _oem = oem || currentOem;\n currentOem = _oem;\n\n const _config = config || currentConfig;\n currentConfig = _config;\n\n // Only load langs that are not already loaded.\n // This logic fails if the user downloaded the LSTM-only English data for a language\n // and then uses `worker.reinitialize` to switch to the Legacy engine.\n // However, the correct data will still be downloaded after initialization fails\n // and this can be avoided entirely if the user loads the correct data ahead of time.\n const langsArr = typeof langs === 'string' ? langs.split('+') : langs;\n const _langs = langsArr.filter((x) => !currentLangs.includes(x));\n currentLangs.push(..._langs);\n\n if (_langs.length > 0) {\n return loadLanguageInternal(_langs, jobId)\n .then(() => initializeInternal(langs, _oem, _config, jobId));\n }\n\n return initializeInternal(langs, _oem, _config, jobId);\n };\n\n const setParameters = (params = {}, jobId) => (\n startJob(createJob({\n id: jobId,\n action: 'setParameters',\n payload: { params },\n }))\n );\n\n const recognize = async (image, opts = {}, output = {\n text: true,\n }, jobId) => (\n startJob(createJob({\n id: jobId,\n action: 'recognize',\n payload: { image: await loadImage(image), options: opts, output },\n }))\n );\n\n const detect = async (image, jobId) => {\n if (lstmOnlyCore) throw Error('`worker.detect` requires Legacy model, which was not loaded.');\n\n return startJob(createJob({\n id: jobId,\n action: 'detect',\n payload: { image: await loadImage(image) },\n }));\n };\n\n const terminate = async () => {\n if (worker !== null) {\n /*\n await startJob(createJob({\n id: jobId,\n action: 'terminate',\n }));\n */\n terminateWorker(worker);\n worker = null;\n }\n return Promise.resolve();\n };\n\n onMessage(worker, ({\n workerId, jobId, status, action, data,\n }) => {\n const promiseId = `${action}-${jobId}`;\n if (status === 'resolve') {\n log(`[${workerId}]: Complete ${jobId}`);\n promises[promiseId].resolve({ jobId, data });\n delete promises[promiseId];\n } else if (status === 'reject') {\n promises[promiseId].reject(data);\n delete promises[promiseId];\n if (action === 'load') workerResReject(data);\n if (errorHandler) {\n errorHandler(data);\n } else {\n throw Error(data);\n }\n } else if (status === 'progress') {\n logger({ ...data, userJobId: jobId });\n }\n });\n\n const resolveObj = {\n id,\n worker,\n load,\n writeText,\n readText,\n removeFile,\n FS,\n reinitialize,\n setParameters,\n recognize,\n detect,\n terminate,\n };\n\n loadInternal()\n .then(() => loadLanguageInternal(langs))\n .then(() => initializeInternal(langs, oem, config))\n .then(() => workerResResolve(resolveObj))\n .catch(() => {});\n\n return workerRes;\n};\n", "'use strict';\n\nconst createWorker = require('./createWorker');\n\nconst recognize = async (image, langs, options) => {\n const worker = await createWorker(langs, 1, options);\n return worker.recognize(image)\n .finally(async () => {\n await worker.terminate();\n });\n};\n\nconst detect = async (image, options) => {\n const worker = await createWorker('osd', 0, options);\n return worker.detect(image)\n .finally(async () => {\n await worker.terminate();\n });\n};\n\nmodule.exports = {\n recognize,\n detect,\n};\n", "'use strict';\n\n/*\n * languages with existing tesseract traineddata\n * https://tesseract-ocr.github.io/tessdoc/Data-Files#data-files-for-version-400-november-29-2016\n */\n\n/**\n * @typedef {object} Languages\n * @property {string} AFR Afrikaans\n * @property {string} AMH Amharic\n * @property {string} ARA Arabic\n * @property {string} ASM Assamese\n * @property {string} AZE Azerbaijani\n * @property {string} AZE_CYRL Azerbaijani - Cyrillic\n * @property {string} BEL Belarusian\n * @property {string} BEN Bengali\n * @property {string} BOD Tibetan\n * @property {string} BOS Bosnian\n * @property {string} BUL Bulgarian\n * @property {string} CAT Catalan; Valencian\n * @property {string} CEB Cebuano\n * @property {string} CES Czech\n * @property {string} CHI_SIM Chinese - Simplified\n * @property {string} CHI_TRA Chinese - Traditional\n * @property {string} CHR Cherokee\n * @property {string} CYM Welsh\n * @property {string} DAN Danish\n * @property {string} DEU German\n * @property {string} DZO Dzongkha\n * @property {string} ELL Greek, Modern (1453-)\n * @property {string} ENG English\n * @property {string} ENM English, Middle (1100-1500)\n * @property {string} EPO Esperanto\n * @property {string} EST Estonian\n * @property {string} EUS Basque\n * @property {string} FAS Persian\n * @property {string} FIN Finnish\n * @property {string} FRA French\n * @property {string} FRK German Fraktur\n * @property {string} FRM French, Middle (ca. 1400-1600)\n * @property {string} GLE Irish\n * @property {string} GLG Galician\n * @property {string} GRC Greek, Ancient (-1453)\n * @property {string} GUJ Gujarati\n * @property {string} HAT Haitian; Haitian Creole\n * @property {string} HEB Hebrew\n * @property {string} HIN Hindi\n * @property {string} HRV Croatian\n * @property {string} HUN Hungarian\n * @property {string} IKU Inuktitut\n * @property {string} IND Indonesian\n * @property {string} ISL Icelandic\n * @property {string} ITA Italian\n * @property {string} ITA_OLD Italian - Old\n * @property {string} JAV Javanese\n * @property {string} JPN Japanese\n * @property {string} KAN Kannada\n * @property {string} KAT Georgian\n * @property {string} KAT_OLD Georgian - Old\n * @property {string} KAZ Kazakh\n * @property {string} KHM Central Khmer\n * @property {string} KIR Kirghiz; Kyrgyz\n * @property {string} KOR Korean\n * @property {string} KUR Kurdish\n * @property {string} LAO Lao\n * @property {string} LAT Latin\n * @property {string} LAV Latvian\n * @property {string} LIT Lithuanian\n * @property {string} MAL Malayalam\n * @property {string} MAR Marathi\n * @property {string} MKD Macedonian\n * @property {string} MLT Maltese\n * @property {string} MSA Malay\n * @property {string} MYA Burmese\n * @property {string} NEP Nepali\n * @property {string} NLD Dutch; Flemish\n * @property {string} NOR Norwegian\n * @property {string} ORI Oriya\n * @property {string} PAN Panjabi; Punjabi\n * @property {string} POL Polish\n * @property {string} POR Portuguese\n * @property {string} PUS Pushto; Pashto\n * @property {string} RON Romanian; Moldavian; Moldovan\n * @property {string} RUS Russian\n * @property {string} SAN Sanskrit\n * @property {string} SIN Sinhala; Sinhalese\n * @property {string} SLK Slovak\n * @property {string} SLV Slovenian\n * @property {string} SPA Spanish; Castilian\n * @property {string} SPA_OLD Spanish; Castilian - Old\n * @property {string} SQI Albanian\n * @property {string} SRP Serbian\n * @property {string} SRP_LATN Serbian - Latin\n * @property {string} SWA Swahili\n * @property {string} SWE Swedish\n * @property {string} SYR Syriac\n * @property {string} TAM Tamil\n * @property {string} TEL Telugu\n * @property {string} TGK Tajik\n * @property {string} TGL Tagalog\n * @property {string} THA Thai\n * @property {string} TIR Tigrinya\n * @property {string} TUR Turkish\n * @property {string} UIG Uighur; Uyghur\n * @property {string} UKR Ukrainian\n * @property {string} URD Urdu\n * @property {string} UZB Uzbek\n * @property {string} UZB_CYRL Uzbek - Cyrillic\n * @property {string} VIE Vietnamese\n * @property {string} YID Yiddish\n */\n\n/**\n * @type {Languages}\n */\nmodule.exports = {\n AFR: 'afr',\n AMH: 'amh',\n ARA: 'ara',\n ASM: 'asm',\n AZE: 'aze',\n AZE_CYRL: 'aze_cyrl',\n BEL: 'bel',\n BEN: 'ben',\n BOD: 'bod',\n BOS: 'bos',\n BUL: 'bul',\n CAT: 'cat',\n CEB: 'ceb',\n CES: 'ces',\n CHI_SIM: 'chi_sim',\n CHI_TRA: 'chi_tra',\n CHR: 'chr',\n CYM: 'cym',\n DAN: 'dan',\n DEU: 'deu',\n DZO: 'dzo',\n ELL: 'ell',\n ENG: 'eng',\n ENM: 'enm',\n EPO: 'epo',\n EST: 'est',\n EUS: 'eus',\n FAS: 'fas',\n FIN: 'fin',\n FRA: 'fra',\n FRK: 'frk',\n FRM: 'frm',\n GLE: 'gle',\n GLG: 'glg',\n GRC: 'grc',\n GUJ: 'guj',\n HAT: 'hat',\n HEB: 'heb',\n HIN: 'hin',\n HRV: 'hrv',\n HUN: 'hun',\n IKU: 'iku',\n IND: 'ind',\n ISL: 'isl',\n ITA: 'ita',\n ITA_OLD: 'ita_old',\n JAV: 'jav',\n JPN: 'jpn',\n KAN: 'kan',\n KAT: 'kat',\n KAT_OLD: 'kat_old',\n KAZ: 'kaz',\n KHM: 'khm',\n KIR: 'kir',\n KOR: 'kor',\n KUR: 'kur',\n LAO: 'lao',\n LAT: 'lat',\n LAV: 'lav',\n LIT: 'lit',\n MAL: 'mal',\n MAR: 'mar',\n MKD: 'mkd',\n MLT: 'mlt',\n MSA: 'msa',\n MYA: 'mya',\n NEP: 'nep',\n NLD: 'nld',\n NOR: 'nor',\n ORI: 'ori',\n PAN: 'pan',\n POL: 'pol',\n POR: 'por',\n PUS: 'pus',\n RON: 'ron',\n RUS: 'rus',\n SAN: 'san',\n SIN: 'sin',\n SLK: 'slk',\n SLV: 'slv',\n SPA: 'spa',\n SPA_OLD: 'spa_old',\n SQI: 'sqi',\n SRP: 'srp',\n SRP_LATN: 'srp_latn',\n SWA: 'swa',\n SWE: 'swe',\n SYR: 'syr',\n TAM: 'tam',\n TEL: 'tel',\n TGK: 'tgk',\n TGL: 'tgl',\n THA: 'tha',\n TIR: 'tir',\n TUR: 'tur',\n UIG: 'uig',\n UKR: 'ukr',\n URD: 'urd',\n UZB: 'uzb',\n UZB_CYRL: 'uzb_cyrl',\n VIE: 'vie',\n YID: 'yid',\n};\n", "'use strict';\n\n/*\n * PSM = Page Segmentation Mode\n */\nmodule.exports = {\n OSD_ONLY: '0',\n AUTO_OSD: '1',\n AUTO_ONLY: '2',\n AUTO: '3',\n SINGLE_COLUMN: '4',\n SINGLE_BLOCK_VERT_TEXT: '5',\n SINGLE_BLOCK: '6',\n SINGLE_LINE: '7',\n SINGLE_WORD: '8',\n CIRCLE_WORD: '9',\n SINGLE_CHAR: '10',\n SPARSE_TEXT: '11',\n SPARSE_TEXT_OSD: '12',\n RAW_LINE: '13',\n};\n", "'use strict';\n\n/**\n *\n * Entry point for tesseract.js, should be the entry when bundling.\n *\n * @fileoverview entry point for tesseract.js\n * @author Kevin Kwok \n * @author Guillermo Webster \n * @author Jerome Wu \n */\nrequire('regenerator-runtime/runtime');\nconst createScheduler = require('./createScheduler');\nconst createWorker = require('./createWorker');\nconst Tesseract = require('./Tesseract');\nconst languages = require('./constants/languages');\nconst OEM = require('./constants/OEM');\nconst PSM = require('./constants/PSM');\nconst { setLogging } = require('./utils/log');\n\nmodule.exports = {\n languages,\n OEM,\n PSM,\n createScheduler,\n createWorker,\n setLogging,\n ...Tesseract,\n};\n", "/*\r\nBreaks a Javascript string into individual user-perceived \"characters\" \r\ncalled extended grapheme clusters by implementing the Unicode UAX-29 standard, version 10.0.0\r\n\r\nUsage:\r\nvar splitter = new GraphemeSplitter();\r\n//returns an array of strings, one string for each grapheme cluster\r\nvar graphemes = splitter.splitGraphemes(string); \r\n\r\n*/\r\nfunction GraphemeSplitter(){\r\n\tvar CR = 0,\r\n\t\tLF = 1,\r\n\t\tControl = 2,\r\n\t\tExtend = 3,\r\n\t\tRegional_Indicator = 4,\r\n\t\tSpacingMark = 5,\r\n\t\tL = 6,\r\n\t\tV = 7,\r\n\t\tT = 8,\r\n\t\tLV = 9,\r\n\t\tLVT = 10,\r\n\t\tOther = 11,\r\n\t\tPrepend = 12,\r\n\t\tE_Base = 13,\r\n\t\tE_Modifier = 14,\r\n\t\tZWJ = 15,\r\n\t\tGlue_After_Zwj = 16,\r\n\t\tE_Base_GAZ = 17;\r\n\t\t\r\n\t// BreakTypes\r\n\tvar NotBreak = 0,\r\n\t\tBreakStart = 1,\r\n\t\tBreak = 2,\r\n\t\tBreakLastRegional = 3,\r\n\t\tBreakPenultimateRegional = 4;\r\n\t\t\r\n\tfunction isSurrogate(str, pos) {\r\n\t\treturn 0xd800 <= str.charCodeAt(pos) && str.charCodeAt(pos) <= 0xdbff && \r\n\t\t\t\t0xdc00 <= str.charCodeAt(pos + 1) && str.charCodeAt(pos + 1) <= 0xdfff;\r\n\t}\r\n\t\t\r\n\t// Private function, gets a Unicode code point from a JavaScript UTF-16 string\r\n\t// handling surrogate pairs appropriately\r\n\tfunction codePointAt(str, idx){\r\n\t\tif(idx === undefined){\r\n\t\t\tidx = 0;\r\n\t\t}\r\n\t\tvar code = str.charCodeAt(idx);\r\n\r\n\t\t// if a high surrogate\r\n\t\tif (0xD800 <= code && code <= 0xDBFF && \r\n\t\t\tidx < str.length - 1){\r\n\t\t\tvar hi = code;\r\n\t\t\tvar low = str.charCodeAt(idx + 1);\r\n\t\t\tif (0xDC00 <= low && low <= 0xDFFF){\r\n\t\t\t\treturn ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;\r\n\t\t\t}\r\n\t\t\treturn hi;\r\n\t\t}\r\n\t\t\r\n\t\t// if a low surrogate\r\n\t\tif (0xDC00 <= code && code <= 0xDFFF &&\r\n\t\t\tidx >= 1){\r\n\t\t\tvar hi = str.charCodeAt(idx - 1);\r\n\t\t\tvar low = code;\r\n\t\t\tif (0xD800 <= hi && hi <= 0xDBFF){\r\n\t\t\t\treturn ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;\r\n\t\t\t}\r\n\t\t\treturn low;\r\n\t\t}\r\n\t\t\r\n\t\t//just return the char if an unmatched surrogate half or a \r\n\t\t//single-char codepoint\r\n\t\treturn code;\r\n\t}\r\n\t\r\n\t// Private function, returns whether a break is allowed between the \r\n\t// two given grapheme breaking classes\r\n\tfunction shouldBreak(start, mid, end){\r\n\t\tvar all = [start].concat(mid).concat([end]);\r\n\t\tvar previous = all[all.length - 2]\r\n\t\tvar next = end\r\n\t\t\r\n\t\t// Lookahead termintor for:\r\n\t\t// GB10. (E_Base | EBG) Extend* ?\tE_Modifier\r\n\t\tvar eModifierIndex = all.lastIndexOf(E_Modifier)\r\n\t\tif(eModifierIndex > 1 &&\r\n\t\t\tall.slice(1, eModifierIndex).every(function(c){return c == Extend}) &&\r\n\t\t\t[Extend, E_Base, E_Base_GAZ].indexOf(start) == -1){\r\n\t\t\treturn Break\r\n\t\t}\r\n\r\n\t\t// Lookahead termintor for:\r\n\t\t// GB12. ^ (RI RI)* RI\t?\tRI\r\n\t\t// GB13. [^RI] (RI RI)* RI\t?\tRI\r\n\t\tvar rIIndex = all.lastIndexOf(Regional_Indicator)\r\n\t\tif(rIIndex > 0 &&\r\n\t\t\tall.slice(1, rIIndex).every(function(c){return c == Regional_Indicator}) &&\r\n\t\t\t[Prepend, Regional_Indicator].indexOf(previous) == -1) { \r\n\t\t\tif(all.filter(function(c){return c == Regional_Indicator}).length % 2 == 1) {\r\n\t\t\t\treturn BreakLastRegional\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\treturn BreakPenultimateRegional\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t// GB3. CR X LF\r\n\t\tif(previous == CR && next == LF){\r\n\t\t\treturn NotBreak;\r\n\t\t}\r\n\t\t// GB4. (Control|CR|LF) \u00F7\r\n\t\telse if(previous == Control || previous == CR || previous == LF){\r\n\t\t\tif(next == E_Modifier && mid.every(function(c){return c == Extend})){\r\n\t\t\t\treturn Break\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\treturn BreakStart\r\n\t\t\t}\r\n\t\t}\r\n\t\t// GB5. \u00F7 (Control|CR|LF)\r\n\t\telse if(next == Control || next == CR || next == LF){\r\n\t\t\treturn BreakStart;\r\n\t\t}\r\n\t\t// GB6. L X (L|V|LV|LVT)\r\n\t\telse if(previous == L && \r\n\t\t\t(next == L || next == V || next == LV || next == LVT)){\r\n\t\t\treturn NotBreak;\r\n\t\t}\r\n\t\t// GB7. (LV|V) X (V|T)\r\n\t\telse if((previous == LV || previous == V) && \r\n\t\t\t(next == V || next == T)){\r\n\t\t\treturn NotBreak;\r\n\t\t}\r\n\t\t// GB8. (LVT|T) X (T)\r\n\t\telse if((previous == LVT || previous == T) && \r\n\t\t\tnext == T){\r\n\t\t\treturn NotBreak;\r\n\t\t}\r\n\t\t// GB9. X (Extend|ZWJ)\r\n\t\telse if (next == Extend || next == ZWJ){\r\n\t\t\treturn NotBreak;\r\n\t\t}\r\n\t\t// GB9a. X SpacingMark\r\n\t\telse if(next == SpacingMark){\r\n\t\t\treturn NotBreak;\r\n\t\t}\r\n\t\t// GB9b. Prepend X\r\n\t\telse if (previous == Prepend){\r\n\t\t\treturn NotBreak;\r\n\t\t}\r\n\t\t\r\n\t\t// GB10. (E_Base | EBG) Extend* ?\tE_Modifier\r\n\t\tvar previousNonExtendIndex = all.indexOf(Extend) != -1 ? all.lastIndexOf(Extend) - 1 : all.length - 2;\r\n\t\tif([E_Base, E_Base_GAZ].indexOf(all[previousNonExtendIndex]) != -1 &&\r\n\t\t\tall.slice(previousNonExtendIndex + 1, -1).every(function(c){return c == Extend}) &&\r\n\t\t\tnext == E_Modifier){\r\n\t\t\treturn NotBreak;\r\n\t\t}\r\n\t\t\r\n\t\t// GB11. ZWJ ? (Glue_After_Zwj | EBG)\r\n\t\tif(previous == ZWJ && [Glue_After_Zwj, E_Base_GAZ].indexOf(next) != -1) {\r\n\t\t\treturn NotBreak;\r\n\t\t}\r\n\r\n\t\t// GB12. ^ (RI RI)* RI ? RI\r\n\t\t// GB13. [^RI] (RI RI)* RI ? RI\r\n\t\tif(mid.indexOf(Regional_Indicator) != -1) { \r\n\t\t\treturn Break;\r\n\t\t}\r\n\t\tif(previous == Regional_Indicator && next == Regional_Indicator) {\r\n\t\t\treturn NotBreak;\r\n\t\t}\r\n\r\n\t\t// GB999. Any ? Any\r\n\t\treturn BreakStart;\r\n\t}\r\n\t\r\n\t// Returns the next grapheme break in the string after the given index\r\n\tthis.nextBreak = function(string, index){\r\n\t\tif(index === undefined){\r\n\t\t\tindex = 0;\r\n\t\t}\r\n\t\tif(index < 0){\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tif(index >= string.length - 1){\r\n\t\t\treturn string.length;\r\n\t\t}\r\n\t\tvar prev = getGraphemeBreakProperty(codePointAt(string, index));\r\n\t\tvar mid = []\r\n\t\tfor (var i = index + 1; i < string.length; i++) {\r\n\t\t\t// check for already processed low surrogates\r\n\t\t\tif(isSurrogate(string, i - 1)){\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\r\n\t\t\tvar next = getGraphemeBreakProperty(codePointAt(string, i));\r\n\t\t\tif(shouldBreak(prev, mid, next)){\r\n\t\t\t\treturn i;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tmid.push(next);\r\n\t\t}\r\n\t\treturn string.length;\r\n\t};\r\n\t\r\n\t// Breaks the given string into an array of grapheme cluster strings\r\n\tthis.splitGraphemes = function(str){\r\n\t\tvar res = [];\r\n\t\tvar index = 0;\r\n\t\tvar brk;\r\n\t\twhile((brk = this.nextBreak(str, index)) < str.length){\r\n\t\t\tres.push(str.slice(index, brk));\r\n\t\t\tindex = brk;\r\n\t\t}\r\n\t\tif(index < str.length){\r\n\t\t\tres.push(str.slice(index));\r\n\t\t}\r\n\t\treturn res;\r\n\t};\r\n\r\n\t// Returns the iterator of grapheme clusters there are in the given string\r\n\tthis.iterateGraphemes = function(str) {\r\n\t\tvar index = 0;\r\n\t\tvar res = {\r\n\t\t\tnext: (function() {\r\n\t\t\t\tvar value;\r\n\t\t\t\tvar brk;\r\n\t\t\t\tif ((brk = this.nextBreak(str, index)) < str.length) {\r\n\t\t\t\t\tvalue = str.slice(index, brk);\r\n\t\t\t\t\tindex = brk;\r\n\t\t\t\t\treturn { value: value, done: false };\r\n\t\t\t\t}\r\n\t\t\t\tif (index < str.length) {\r\n\t\t\t\t\tvalue = str.slice(index);\r\n\t\t\t\t\tindex = str.length;\r\n\t\t\t\t\treturn { value: value, done: false };\r\n\t\t\t\t}\r\n\t\t\t\treturn { value: undefined, done: true };\r\n\t\t\t}).bind(this)\r\n\t\t};\r\n\t\t// ES2015 @@iterator method (iterable) for spread syntax and for...of statement\r\n\t\tif (typeof Symbol !== 'undefined' && Symbol.iterator) {\r\n\t\t\tres[Symbol.iterator] = function() {return res};\r\n\t\t}\r\n\t\treturn res;\r\n\t};\r\n\r\n\t// Returns the number of grapheme clusters there are in the given string\r\n\tthis.countGraphemes = function(str){\r\n\t\tvar count = 0;\r\n\t\tvar index = 0;\r\n\t\tvar brk;\r\n\t\twhile((brk = this.nextBreak(str, index)) < str.length){\r\n\t\t\tindex = brk;\r\n\t\t\tcount++;\r\n\t\t}\r\n\t\tif(index < str.length){\r\n\t\t\tcount++;\r\n\t\t}\r\n\t\treturn count;\r\n\t};\r\n\t\r\n\t//given a Unicode code point, determines this symbol's grapheme break property\r\n\tfunction getGraphemeBreakProperty(code){\r\n\t\t\r\n\t\t//grapheme break property for Unicode 10.0.0, \r\n\t\t//taken from http://www.unicode.org/Public/10.0.0/ucd/auxiliary/GraphemeBreakProperty.txt\r\n\t\t//and adapted to JavaScript rules\r\n\t\t\r\n\t\tif(\t\t\r\n\t\t(0x0600 <= code && code <= 0x0605) || // Cf [6] ARABIC NUMBER SIGN..ARABIC NUMBER MARK ABOVE\r\n\t\t0x06DD == code || // Cf ARABIC END OF AYAH\r\n\t\t0x070F == code || // Cf SYRIAC ABBREVIATION MARK\r\n\t\t0x08E2 == code || // Cf ARABIC DISPUTED END OF AYAH\r\n\t\t0x0D4E == code || // Lo MALAYALAM LETTER DOT REPH\r\n\t\t0x110BD == code || // Cf KAITHI NUMBER SIGN\r\n\t\t(0x111C2 <= code && code <= 0x111C3) || // Lo [2] SHARADA SIGN JIHVAMULIYA..SHARADA SIGN UPADHMANIYA\r\n\t\t0x11A3A == code || // Lo ZANABAZAR SQUARE CLUSTER-INITIAL LETTER RA\r\n\t\t(0x11A86 <= code && code <= 0x11A89) || // Lo [4] SOYOMBO CLUSTER-INITIAL LETTER RA..SOYOMBO CLUSTER-INITIAL LETTER SA\r\n\t\t0x11D46 == code // Lo MASARAM GONDI REPHA\r\n\t\t){\r\n\t\t\treturn Prepend;\r\n\t\t}\r\n\t\tif(\r\n\t\t0x000D == code // Cc \r\n\t\t){\r\n\t\t\treturn CR;\r\n\t\t}\r\n\t\t\r\n\t\tif(\r\n\t\t0x000A == code // Cc \r\n\t\t){\r\n\t\t\treturn LF;\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\tif(\r\n\t\t(0x0000 <= code && code <= 0x0009) || // Cc [10] ..\r\n\t\t(0x000B <= code && code <= 0x000C) || // Cc [2] ..\r\n\t\t(0x000E <= code && code <= 0x001F) || // Cc [18] ..\r\n\t\t(0x007F <= code && code <= 0x009F) || // Cc [33] ..\r\n\t\t0x00AD == code || // Cf SOFT HYPHEN\r\n\t\t0x061C == code || // Cf ARABIC LETTER MARK\r\n\t\r\n\t\t0x180E == code || // Cf MONGOLIAN VOWEL SEPARATOR\r\n\t\t0x200B == code || // Cf ZERO WIDTH SPACE\r\n\t\t(0x200E <= code && code <= 0x200F) || // Cf [2] LEFT-TO-RIGHT MARK..RIGHT-TO-LEFT MARK\r\n\t\t0x2028 == code || // Zl LINE SEPARATOR\r\n\t\t0x2029 == code || // Zp PARAGRAPH SEPARATOR\r\n\t\t(0x202A <= code && code <= 0x202E) || // Cf [5] LEFT-TO-RIGHT EMBEDDING..RIGHT-TO-LEFT OVERRIDE\r\n\t\t(0x2060 <= code && code <= 0x2064) || // Cf [5] WORD JOINER..INVISIBLE PLUS\r\n\t\t0x2065 == code || // Cn \r\n\t\t(0x2066 <= code && code <= 0x206F) || // Cf [10] LEFT-TO-RIGHT ISOLATE..NOMINAL DIGIT SHAPES\r\n\t\t(0xD800 <= code && code <= 0xDFFF) || // Cs [2048] ..\r\n\t\t0xFEFF == code || // Cf ZERO WIDTH NO-BREAK SPACE\r\n\t\t(0xFFF0 <= code && code <= 0xFFF8) || // Cn [9] ..\r\n\t\t(0xFFF9 <= code && code <= 0xFFFB) || // Cf [3] INTERLINEAR ANNOTATION ANCHOR..INTERLINEAR ANNOTATION TERMINATOR\r\n\t\t(0x1BCA0 <= code && code <= 0x1BCA3) || // Cf [4] SHORTHAND FORMAT LETTER OVERLAP..SHORTHAND FORMAT UP STEP\r\n\t\t(0x1D173 <= code && code <= 0x1D17A) || // Cf [8] MUSICAL SYMBOL BEGIN BEAM..MUSICAL SYMBOL END PHRASE\r\n\t\t0xE0000 == code || // Cn \r\n\t\t0xE0001 == code || // Cf LANGUAGE TAG\r\n\t\t(0xE0002 <= code && code <= 0xE001F) || // Cn [30] ..\r\n\t\t(0xE0080 <= code && code <= 0xE00FF) || // Cn [128] ..\r\n\t\t(0xE01F0 <= code && code <= 0xE0FFF) // Cn [3600] ..\r\n\t\t){\r\n\t\t\treturn Control;\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\tif(\r\n\t\t(0x0300 <= code && code <= 0x036F) || // Mn [112] COMBINING GRAVE ACCENT..COMBINING LATIN SMALL LETTER X\r\n\t\t(0x0483 <= code && code <= 0x0487) || // Mn [5] COMBINING CYRILLIC TITLO..COMBINING CYRILLIC POKRYTIE\r\n\t\t(0x0488 <= code && code <= 0x0489) || // Me [2] COMBINING CYRILLIC HUNDRED THOUSANDS SIGN..COMBINING CYRILLIC MILLIONS SIGN\r\n\t\t(0x0591 <= code && code <= 0x05BD) || // Mn [45] HEBREW ACCENT ETNAHTA..HEBREW POINT METEG\r\n\t\t0x05BF == code || // Mn HEBREW POINT RAFE\r\n\t\t(0x05C1 <= code && code <= 0x05C2) || // Mn [2] HEBREW POINT SHIN DOT..HEBREW POINT SIN DOT\r\n\t\t(0x05C4 <= code && code <= 0x05C5) || // Mn [2] HEBREW MARK UPPER DOT..HEBREW MARK LOWER DOT\r\n\t\t0x05C7 == code || // Mn HEBREW POINT QAMATS QATAN\r\n\t\t(0x0610 <= code && code <= 0x061A) || // Mn [11] ARABIC SIGN SALLALLAHOU ALAYHE WASSALLAM..ARABIC SMALL KASRA\r\n\t\t(0x064B <= code && code <= 0x065F) || // Mn [21] ARABIC FATHATAN..ARABIC WAVY HAMZA BELOW\r\n\t\t0x0670 == code || // Mn ARABIC LETTER SUPERSCRIPT ALEF\r\n\t\t(0x06D6 <= code && code <= 0x06DC) || // Mn [7] ARABIC SMALL HIGH LIGATURE SAD WITH LAM WITH ALEF MAKSURA..ARABIC SMALL HIGH SEEN\r\n\t\t(0x06DF <= code && code <= 0x06E4) || // Mn [6] ARABIC SMALL HIGH ROUNDED ZERO..ARABIC SMALL HIGH MADDA\r\n\t\t(0x06E7 <= code && code <= 0x06E8) || // Mn [2] ARABIC SMALL HIGH YEH..ARABIC SMALL HIGH NOON\r\n\t\t(0x06EA <= code && code <= 0x06ED) || // Mn [4] ARABIC EMPTY CENTRE LOW STOP..ARABIC SMALL LOW MEEM\r\n\t\t0x0711 == code || // Mn SYRIAC LETTER SUPERSCRIPT ALAPH\r\n\t\t(0x0730 <= code && code <= 0x074A) || // Mn [27] SYRIAC PTHAHA ABOVE..SYRIAC BARREKH\r\n\t\t(0x07A6 <= code && code <= 0x07B0) || // Mn [11] THAANA ABAFILI..THAANA SUKUN\r\n\t\t(0x07EB <= code && code <= 0x07F3) || // Mn [9] NKO COMBINING SHORT HIGH TONE..NKO COMBINING DOUBLE DOT ABOVE\r\n\t\t(0x0816 <= code && code <= 0x0819) || // Mn [4] SAMARITAN MARK IN..SAMARITAN MARK DAGESH\r\n\t\t(0x081B <= code && code <= 0x0823) || // Mn [9] SAMARITAN MARK EPENTHETIC YUT..SAMARITAN VOWEL SIGN A\r\n\t\t(0x0825 <= code && code <= 0x0827) || // Mn [3] SAMARITAN VOWEL SIGN SHORT A..SAMARITAN VOWEL SIGN U\r\n\t\t(0x0829 <= code && code <= 0x082D) || // Mn [5] SAMARITAN VOWEL SIGN LONG I..SAMARITAN MARK NEQUDAA\r\n\t\t(0x0859 <= code && code <= 0x085B) || // Mn [3] MANDAIC AFFRICATION MARK..MANDAIC GEMINATION MARK\r\n\t\t(0x08D4 <= code && code <= 0x08E1) || // Mn [14] ARABIC SMALL HIGH WORD AR-RUB..ARABIC SMALL HIGH SIGN SAFHA\r\n\t\t(0x08E3 <= code && code <= 0x0902) || // Mn [32] ARABIC TURNED DAMMA BELOW..DEVANAGARI SIGN ANUSVARA\r\n\t\t0x093A == code || // Mn DEVANAGARI VOWEL SIGN OE\r\n\t\t0x093C == code || // Mn DEVANAGARI SIGN NUKTA\r\n\t\t(0x0941 <= code && code <= 0x0948) || // Mn [8] DEVANAGARI VOWEL SIGN U..DEVANAGARI VOWEL SIGN AI\r\n\t\t0x094D == code || // Mn DEVANAGARI SIGN VIRAMA\r\n\t\t(0x0951 <= code && code <= 0x0957) || // Mn [7] DEVANAGARI STRESS SIGN UDATTA..DEVANAGARI VOWEL SIGN UUE\r\n\t\t(0x0962 <= code && code <= 0x0963) || // Mn [2] DEVANAGARI VOWEL SIGN VOCALIC L..DEVANAGARI VOWEL SIGN VOCALIC LL\r\n\t\t0x0981 == code || // Mn BENGALI SIGN CANDRABINDU\r\n\t\t0x09BC == code || // Mn BENGALI SIGN NUKTA\r\n\t\t0x09BE == code || // Mc BENGALI VOWEL SIGN AA\r\n\t\t(0x09C1 <= code && code <= 0x09C4) || // Mn [4] BENGALI VOWEL SIGN U..BENGALI VOWEL SIGN VOCALIC RR\r\n\t\t0x09CD == code || // Mn BENGALI SIGN VIRAMA\r\n\t\t0x09D7 == code || // Mc BENGALI AU LENGTH MARK\r\n\t\t(0x09E2 <= code && code <= 0x09E3) || // Mn [2] BENGALI VOWEL SIGN VOCALIC L..BENGALI VOWEL SIGN VOCALIC LL\r\n\t\t(0x0A01 <= code && code <= 0x0A02) || // Mn [2] GURMUKHI SIGN ADAK BINDI..GURMUKHI SIGN BINDI\r\n\t\t0x0A3C == code || // Mn GURMUKHI SIGN NUKTA\r\n\t\t(0x0A41 <= code && code <= 0x0A42) || // Mn [2] GURMUKHI VOWEL SIGN U..GURMUKHI VOWEL SIGN UU\r\n\t\t(0x0A47 <= code && code <= 0x0A48) || // Mn [2] GURMUKHI VOWEL SIGN EE..GURMUKHI VOWEL SIGN AI\r\n\t\t(0x0A4B <= code && code <= 0x0A4D) || // Mn [3] GURMUKHI VOWEL SIGN OO..GURMUKHI SIGN VIRAMA\r\n\t\t0x0A51 == code || // Mn GURMUKHI SIGN UDAAT\r\n\t\t(0x0A70 <= code && code <= 0x0A71) || // Mn [2] GURMUKHI TIPPI..GURMUKHI ADDAK\r\n\t\t0x0A75 == code || // Mn GURMUKHI SIGN YAKASH\r\n\t\t(0x0A81 <= code && code <= 0x0A82) || // Mn [2] GUJARATI SIGN CANDRABINDU..GUJARATI SIGN ANUSVARA\r\n\t\t0x0ABC == code || // Mn GUJARATI SIGN NUKTA\r\n\t\t(0x0AC1 <= code && code <= 0x0AC5) || // Mn [5] GUJARATI VOWEL SIGN U..GUJARATI VOWEL SIGN CANDRA E\r\n\t\t(0x0AC7 <= code && code <= 0x0AC8) || // Mn [2] GUJARATI VOWEL SIGN E..GUJARATI VOWEL SIGN AI\r\n\t\t0x0ACD == code || // Mn GUJARATI SIGN VIRAMA\r\n\t\t(0x0AE2 <= code && code <= 0x0AE3) || // Mn [2] GUJARATI VOWEL SIGN VOCALIC L..GUJARATI VOWEL SIGN VOCALIC LL\r\n\t\t(0x0AFA <= code && code <= 0x0AFF) || // Mn [6] GUJARATI SIGN SUKUN..GUJARATI SIGN TWO-CIRCLE NUKTA ABOVE\r\n\t\t0x0B01 == code || // Mn ORIYA SIGN CANDRABINDU\r\n\t\t0x0B3C == code || // Mn ORIYA SIGN NUKTA\r\n\t\t0x0B3E == code || // Mc ORIYA VOWEL SIGN AA\r\n\t\t0x0B3F == code || // Mn ORIYA VOWEL SIGN I\r\n\t\t(0x0B41 <= code && code <= 0x0B44) || // Mn [4] ORIYA VOWEL SIGN U..ORIYA VOWEL SIGN VOCALIC RR\r\n\t\t0x0B4D == code || // Mn ORIYA SIGN VIRAMA\r\n\t\t0x0B56 == code || // Mn ORIYA AI LENGTH MARK\r\n\t\t0x0B57 == code || // Mc ORIYA AU LENGTH MARK\r\n\t\t(0x0B62 <= code && code <= 0x0B63) || // Mn [2] ORIYA VOWEL SIGN VOCALIC L..ORIYA VOWEL SIGN VOCALIC LL\r\n\t\t0x0B82 == code || // Mn TAMIL SIGN ANUSVARA\r\n\t\t0x0BBE == code || // Mc TAMIL VOWEL SIGN AA\r\n\t\t0x0BC0 == code || // Mn TAMIL VOWEL SIGN II\r\n\t\t0x0BCD == code || // Mn TAMIL SIGN VIRAMA\r\n\t\t0x0BD7 == code || // Mc TAMIL AU LENGTH MARK\r\n\t\t0x0C00 == code || // Mn TELUGU SIGN COMBINING CANDRABINDU ABOVE\r\n\t\t(0x0C3E <= code && code <= 0x0C40) || // Mn [3] TELUGU VOWEL SIGN AA..TELUGU VOWEL SIGN II\r\n\t\t(0x0C46 <= code && code <= 0x0C48) || // Mn [3] TELUGU VOWEL SIGN E..TELUGU VOWEL SIGN AI\r\n\t\t(0x0C4A <= code && code <= 0x0C4D) || // Mn [4] TELUGU VOWEL SIGN O..TELUGU SIGN VIRAMA\r\n\t\t(0x0C55 <= code && code <= 0x0C56) || // Mn [2] TELUGU LENGTH MARK..TELUGU AI LENGTH MARK\r\n\t\t(0x0C62 <= code && code <= 0x0C63) || // Mn [2] TELUGU VOWEL SIGN VOCALIC L..TELUGU VOWEL SIGN VOCALIC LL\r\n\t\t0x0C81 == code || // Mn KANNADA SIGN CANDRABINDU\r\n\t\t0x0CBC == code || // Mn KANNADA SIGN NUKTA\r\n\t\t0x0CBF == code || // Mn KANNADA VOWEL SIGN I\r\n\t\t0x0CC2 == code || // Mc KANNADA VOWEL SIGN UU\r\n\t\t0x0CC6 == code || // Mn KANNADA VOWEL SIGN E\r\n\t\t(0x0CCC <= code && code <= 0x0CCD) || // Mn [2] KANNADA VOWEL SIGN AU..KANNADA SIGN VIRAMA\r\n\t\t(0x0CD5 <= code && code <= 0x0CD6) || // Mc [2] KANNADA LENGTH MARK..KANNADA AI LENGTH MARK\r\n\t\t(0x0CE2 <= code && code <= 0x0CE3) || // Mn [2] KANNADA VOWEL SIGN VOCALIC L..KANNADA VOWEL SIGN VOCALIC LL\r\n\t\t(0x0D00 <= code && code <= 0x0D01) || // Mn [2] MALAYALAM SIGN COMBINING ANUSVARA ABOVE..MALAYALAM SIGN CANDRABINDU\r\n\t\t(0x0D3B <= code && code <= 0x0D3C) || // Mn [2] MALAYALAM SIGN VERTICAL BAR VIRAMA..MALAYALAM SIGN CIRCULAR VIRAMA\r\n\t\t0x0D3E == code || // Mc MALAYALAM VOWEL SIGN AA\r\n\t\t(0x0D41 <= code && code <= 0x0D44) || // Mn [4] MALAYALAM VOWEL SIGN U..MALAYALAM VOWEL SIGN VOCALIC RR\r\n\t\t0x0D4D == code || // Mn MALAYALAM SIGN VIRAMA\r\n\t\t0x0D57 == code || // Mc MALAYALAM AU LENGTH MARK\r\n\t\t(0x0D62 <= code && code <= 0x0D63) || // Mn [2] MALAYALAM VOWEL SIGN VOCALIC L..MALAYALAM VOWEL SIGN VOCALIC LL\r\n\t\t0x0DCA == code || // Mn SINHALA SIGN AL-LAKUNA\r\n\t\t0x0DCF == code || // Mc SINHALA VOWEL SIGN AELA-PILLA\r\n\t\t(0x0DD2 <= code && code <= 0x0DD4) || // Mn [3] SINHALA VOWEL SIGN KETTI IS-PILLA..SINHALA VOWEL SIGN KETTI PAA-PILLA\r\n\t\t0x0DD6 == code || // Mn SINHALA VOWEL SIGN DIGA PAA-PILLA\r\n\t\t0x0DDF == code || // Mc SINHALA VOWEL SIGN GAYANUKITTA\r\n\t\t0x0E31 == code || // Mn THAI CHARACTER MAI HAN-AKAT\r\n\t\t(0x0E34 <= code && code <= 0x0E3A) || // Mn [7] THAI CHARACTER SARA I..THAI CHARACTER PHINTHU\r\n\t\t(0x0E47 <= code && code <= 0x0E4E) || // Mn [8] THAI CHARACTER MAITAIKHU..THAI CHARACTER YAMAKKAN\r\n\t\t0x0EB1 == code || // Mn LAO VOWEL SIGN MAI KAN\r\n\t\t(0x0EB4 <= code && code <= 0x0EB9) || // Mn [6] LAO VOWEL SIGN I..LAO VOWEL SIGN UU\r\n\t\t(0x0EBB <= code && code <= 0x0EBC) || // Mn [2] LAO VOWEL SIGN MAI KON..LAO SEMIVOWEL SIGN LO\r\n\t\t(0x0EC8 <= code && code <= 0x0ECD) || // Mn [6] LAO TONE MAI EK..LAO NIGGAHITA\r\n\t\t(0x0F18 <= code && code <= 0x0F19) || // Mn [2] TIBETAN ASTROLOGICAL SIGN -KHYUD PA..TIBETAN ASTROLOGICAL SIGN SDONG TSHUGS\r\n\t\t0x0F35 == code || // Mn TIBETAN MARK NGAS BZUNG NYI ZLA\r\n\t\t0x0F37 == code || // Mn TIBETAN MARK NGAS BZUNG SGOR RTAGS\r\n\t\t0x0F39 == code || // Mn TIBETAN MARK TSA -PHRU\r\n\t\t(0x0F71 <= code && code <= 0x0F7E) || // Mn [14] TIBETAN VOWEL SIGN AA..TIBETAN SIGN RJES SU NGA RO\r\n\t\t(0x0F80 <= code && code <= 0x0F84) || // Mn [5] TIBETAN VOWEL SIGN REVERSED I..TIBETAN MARK HALANTA\r\n\t\t(0x0F86 <= code && code <= 0x0F87) || // Mn [2] TIBETAN SIGN LCI RTAGS..TIBETAN SIGN YANG RTAGS\r\n\t\t(0x0F8D <= code && code <= 0x0F97) || // Mn [11] TIBETAN SUBJOINED SIGN LCE TSA CAN..TIBETAN SUBJOINED LETTER JA\r\n\t\t(0x0F99 <= code && code <= 0x0FBC) || // Mn [36] TIBETAN SUBJOINED LETTER NYA..TIBETAN SUBJOINED LETTER FIXED-FORM RA\r\n\t\t0x0FC6 == code || // Mn TIBETAN SYMBOL PADMA GDAN\r\n\t\t(0x102D <= code && code <= 0x1030) || // Mn [4] MYANMAR VOWEL SIGN I..MYANMAR VOWEL SIGN UU\r\n\t\t(0x1032 <= code && code <= 0x1037) || // Mn [6] MYANMAR VOWEL SIGN AI..MYANMAR SIGN DOT BELOW\r\n\t\t(0x1039 <= code && code <= 0x103A) || // Mn [2] MYANMAR SIGN VIRAMA..MYANMAR SIGN ASAT\r\n\t\t(0x103D <= code && code <= 0x103E) || // Mn [2] MYANMAR CONSONANT SIGN MEDIAL WA..MYANMAR CONSONANT SIGN MEDIAL HA\r\n\t\t(0x1058 <= code && code <= 0x1059) || // Mn [2] MYANMAR VOWEL SIGN VOCALIC L..MYANMAR VOWEL SIGN VOCALIC LL\r\n\t\t(0x105E <= code && code <= 0x1060) || // Mn [3] MYANMAR CONSONANT SIGN MON MEDIAL NA..MYANMAR CONSONANT SIGN MON MEDIAL LA\r\n\t\t(0x1071 <= code && code <= 0x1074) || // Mn [4] MYANMAR VOWEL SIGN GEBA KAREN I..MYANMAR VOWEL SIGN KAYAH EE\r\n\t\t0x1082 == code || // Mn MYANMAR CONSONANT SIGN SHAN MEDIAL WA\r\n\t\t(0x1085 <= code && code <= 0x1086) || // Mn [2] MYANMAR VOWEL SIGN SHAN E ABOVE..MYANMAR VOWEL SIGN SHAN FINAL Y\r\n\t\t0x108D == code || // Mn MYANMAR SIGN SHAN COUNCIL EMPHATIC TONE\r\n\t\t0x109D == code || // Mn MYANMAR VOWEL SIGN AITON AI\r\n\t\t(0x135D <= code && code <= 0x135F) || // Mn [3] ETHIOPIC COMBINING GEMINATION AND VOWEL LENGTH MARK..ETHIOPIC COMBINING GEMINATION MARK\r\n\t\t(0x1712 <= code && code <= 0x1714) || // Mn [3] TAGALOG VOWEL SIGN I..TAGALOG SIGN VIRAMA\r\n\t\t(0x1732 <= code && code <= 0x1734) || // Mn [3] HANUNOO VOWEL SIGN I..HANUNOO SIGN PAMUDPOD\r\n\t\t(0x1752 <= code && code <= 0x1753) || // Mn [2] BUHID VOWEL SIGN I..BUHID VOWEL SIGN U\r\n\t\t(0x1772 <= code && code <= 0x1773) || // Mn [2] TAGBANWA VOWEL SIGN I..TAGBANWA VOWEL SIGN U\r\n\t\t(0x17B4 <= code && code <= 0x17B5) || // Mn [2] KHMER VOWEL INHERENT AQ..KHMER VOWEL INHERENT AA\r\n\t\t(0x17B7 <= code && code <= 0x17BD) || // Mn [7] KHMER VOWEL SIGN I..KHMER VOWEL SIGN UA\r\n\t\t0x17C6 == code || // Mn KHMER SIGN NIKAHIT\r\n\t\t(0x17C9 <= code && code <= 0x17D3) || // Mn [11] KHMER SIGN MUUSIKATOAN..KHMER SIGN BATHAMASAT\r\n\t\t0x17DD == code || // Mn KHMER SIGN ATTHACAN\r\n\t\t(0x180B <= code && code <= 0x180D) || // Mn [3] MONGOLIAN FREE VARIATION SELECTOR ONE..MONGOLIAN FREE VARIATION SELECTOR THREE\r\n\t\t(0x1885 <= code && code <= 0x1886) || // Mn [2] MONGOLIAN LETTER ALI GALI BALUDA..MONGOLIAN LETTER ALI GALI THREE BALUDA\r\n\t\t0x18A9 == code || // Mn MONGOLIAN LETTER ALI GALI DAGALGA\r\n\t\t(0x1920 <= code && code <= 0x1922) || // Mn [3] LIMBU VOWEL SIGN A..LIMBU VOWEL SIGN U\r\n\t\t(0x1927 <= code && code <= 0x1928) || // Mn [2] LIMBU VOWEL SIGN E..LIMBU VOWEL SIGN O\r\n\t\t0x1932 == code || // Mn LIMBU SMALL LETTER ANUSVARA\r\n\t\t(0x1939 <= code && code <= 0x193B) || // Mn [3] LIMBU SIGN MUKPHRENG..LIMBU SIGN SA-I\r\n\t\t(0x1A17 <= code && code <= 0x1A18) || // Mn [2] BUGINESE VOWEL SIGN I..BUGINESE VOWEL SIGN U\r\n\t\t0x1A1B == code || // Mn BUGINESE VOWEL SIGN AE\r\n\t\t0x1A56 == code || // Mn TAI THAM CONSONANT SIGN MEDIAL LA\r\n\t\t(0x1A58 <= code && code <= 0x1A5E) || // Mn [7] TAI THAM SIGN MAI KANG LAI..TAI THAM CONSONANT SIGN SA\r\n\t\t0x1A60 == code || // Mn TAI THAM SIGN SAKOT\r\n\t\t0x1A62 == code || // Mn TAI THAM VOWEL SIGN MAI SAT\r\n\t\t(0x1A65 <= code && code <= 0x1A6C) || // Mn [8] TAI THAM VOWEL SIGN I..TAI THAM VOWEL SIGN OA BELOW\r\n\t\t(0x1A73 <= code && code <= 0x1A7C) || // Mn [10] TAI THAM VOWEL SIGN OA ABOVE..TAI THAM SIGN KHUEN-LUE KARAN\r\n\t\t0x1A7F == code || // Mn TAI THAM COMBINING CRYPTOGRAMMIC DOT\r\n\t\t(0x1AB0 <= code && code <= 0x1ABD) || // Mn [14] COMBINING DOUBLED CIRCUMFLEX ACCENT..COMBINING PARENTHESES BELOW\r\n\t\t0x1ABE == code || // Me COMBINING PARENTHESES OVERLAY\r\n\t\t(0x1B00 <= code && code <= 0x1B03) || // Mn [4] BALINESE SIGN ULU RICEM..BALINESE SIGN SURANG\r\n\t\t0x1B34 == code || // Mn BALINESE SIGN REREKAN\r\n\t\t(0x1B36 <= code && code <= 0x1B3A) || // Mn [5] BALINESE VOWEL SIGN ULU..BALINESE VOWEL SIGN RA REPA\r\n\t\t0x1B3C == code || // Mn BALINESE VOWEL SIGN LA LENGA\r\n\t\t0x1B42 == code || // Mn BALINESE VOWEL SIGN PEPET\r\n\t\t(0x1B6B <= code && code <= 0x1B73) || // Mn [9] BALINESE MUSICAL SYMBOL COMBINING TEGEH..BALINESE MUSICAL SYMBOL COMBINING GONG\r\n\t\t(0x1B80 <= code && code <= 0x1B81) || // Mn [2] SUNDANESE SIGN PANYECEK..SUNDANESE SIGN PANGLAYAR\r\n\t\t(0x1BA2 <= code && code <= 0x1BA5) || // Mn [4] SUNDANESE CONSONANT SIGN PANYAKRA..SUNDANESE VOWEL SIGN PANYUKU\r\n\t\t(0x1BA8 <= code && code <= 0x1BA9) || // Mn [2] SUNDANESE VOWEL SIGN PAMEPET..SUNDANESE VOWEL SIGN PANEULEUNG\r\n\t\t(0x1BAB <= code && code <= 0x1BAD) || // Mn [3] SUNDANESE SIGN VIRAMA..SUNDANESE CONSONANT SIGN PASANGAN WA\r\n\t\t0x1BE6 == code || // Mn BATAK SIGN TOMPI\r\n\t\t(0x1BE8 <= code && code <= 0x1BE9) || // Mn [2] BATAK VOWEL SIGN PAKPAK E..BATAK VOWEL SIGN EE\r\n\t\t0x1BED == code || // Mn BATAK VOWEL SIGN KARO O\r\n\t\t(0x1BEF <= code && code <= 0x1BF1) || // Mn [3] BATAK VOWEL SIGN U FOR SIMALUNGUN SA..BATAK CONSONANT SIGN H\r\n\t\t(0x1C2C <= code && code <= 0x1C33) || // Mn [8] LEPCHA VOWEL SIGN E..LEPCHA CONSONANT SIGN T\r\n\t\t(0x1C36 <= code && code <= 0x1C37) || // Mn [2] LEPCHA SIGN RAN..LEPCHA SIGN NUKTA\r\n\t\t(0x1CD0 <= code && code <= 0x1CD2) || // Mn [3] VEDIC TONE KARSHANA..VEDIC TONE PRENKHA\r\n\t\t(0x1CD4 <= code && code <= 0x1CE0) || // Mn [13] VEDIC SIGN YAJURVEDIC MIDLINE SVARITA..VEDIC TONE RIGVEDIC KASHMIRI INDEPENDENT SVARITA\r\n\t\t(0x1CE2 <= code && code <= 0x1CE8) || // Mn [7] VEDIC SIGN VISARGA SVARITA..VEDIC SIGN VISARGA ANUDATTA WITH TAIL\r\n\t\t0x1CED == code || // Mn VEDIC SIGN TIRYAK\r\n\t\t0x1CF4 == code || // Mn VEDIC TONE CANDRA ABOVE\r\n\t\t(0x1CF8 <= code && code <= 0x1CF9) || // Mn [2] VEDIC TONE RING ABOVE..VEDIC TONE DOUBLE RING ABOVE\r\n\t\t(0x1DC0 <= code && code <= 0x1DF9) || // Mn [58] COMBINING DOTTED GRAVE ACCENT..COMBINING WIDE INVERTED BRIDGE BELOW\r\n\t\t(0x1DFB <= code && code <= 0x1DFF) || // Mn [5] COMBINING DELETION MARK..COMBINING RIGHT ARROWHEAD AND DOWN ARROWHEAD BELOW\r\n\t\t0x200C == code || // Cf ZERO WIDTH NON-JOINER\r\n\t\t(0x20D0 <= code && code <= 0x20DC) || // Mn [13] COMBINING LEFT HARPOON ABOVE..COMBINING FOUR DOTS ABOVE\r\n\t\t(0x20DD <= code && code <= 0x20E0) || // Me [4] COMBINING ENCLOSING CIRCLE..COMBINING ENCLOSING CIRCLE BACKSLASH\r\n\t\t0x20E1 == code || // Mn COMBINING LEFT RIGHT ARROW ABOVE\r\n\t\t(0x20E2 <= code && code <= 0x20E4) || // Me [3] COMBINING ENCLOSING SCREEN..COMBINING ENCLOSING UPWARD POINTING TRIANGLE\r\n\t\t(0x20E5 <= code && code <= 0x20F0) || // Mn [12] COMBINING REVERSE SOLIDUS OVERLAY..COMBINING ASTERISK ABOVE\r\n\t\t(0x2CEF <= code && code <= 0x2CF1) || // Mn [3] COPTIC COMBINING NI ABOVE..COPTIC COMBINING SPIRITUS LENIS\r\n\t\t0x2D7F == code || // Mn TIFINAGH CONSONANT JOINER\r\n\t\t(0x2DE0 <= code && code <= 0x2DFF) || // Mn [32] COMBINING CYRILLIC LETTER BE..COMBINING CYRILLIC LETTER IOTIFIED BIG YUS\r\n\t\t(0x302A <= code && code <= 0x302D) || // Mn [4] IDEOGRAPHIC LEVEL TONE MARK..IDEOGRAPHIC ENTERING TONE MARK\r\n\t\t(0x302E <= code && code <= 0x302F) || // Mc [2] HANGUL SINGLE DOT TONE MARK..HANGUL DOUBLE DOT TONE MARK\r\n\t\t(0x3099 <= code && code <= 0x309A) || // Mn [2] COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK..COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK\r\n\t\t0xA66F == code || // Mn COMBINING CYRILLIC VZMET\r\n\t\t(0xA670 <= code && code <= 0xA672) || // Me [3] COMBINING CYRILLIC TEN MILLIONS SIGN..COMBINING CYRILLIC THOUSAND MILLIONS SIGN\r\n\t\t(0xA674 <= code && code <= 0xA67D) || // Mn [10] COMBINING CYRILLIC LETTER UKRAINIAN IE..COMBINING CYRILLIC PAYEROK\r\n\t\t(0xA69E <= code && code <= 0xA69F) || // Mn [2] COMBINING CYRILLIC LETTER EF..COMBINING CYRILLIC LETTER IOTIFIED E\r\n\t\t(0xA6F0 <= code && code <= 0xA6F1) || // Mn [2] BAMUM COMBINING MARK KOQNDON..BAMUM COMBINING MARK TUKWENTIS\r\n\t\t0xA802 == code || // Mn SYLOTI NAGRI SIGN DVISVARA\r\n\t\t0xA806 == code || // Mn SYLOTI NAGRI SIGN HASANTA\r\n\t\t0xA80B == code || // Mn SYLOTI NAGRI SIGN ANUSVARA\r\n\t\t(0xA825 <= code && code <= 0xA826) || // Mn [2] SYLOTI NAGRI VOWEL SIGN U..SYLOTI NAGRI VOWEL SIGN E\r\n\t\t(0xA8C4 <= code && code <= 0xA8C5) || // Mn [2] SAURASHTRA SIGN VIRAMA..SAURASHTRA SIGN CANDRABINDU\r\n\t\t(0xA8E0 <= code && code <= 0xA8F1) || // Mn [18] COMBINING DEVANAGARI DIGIT ZERO..COMBINING DEVANAGARI SIGN AVAGRAHA\r\n\t\t(0xA926 <= code && code <= 0xA92D) || // Mn [8] KAYAH LI VOWEL UE..KAYAH LI TONE CALYA PLOPHU\r\n\t\t(0xA947 <= code && code <= 0xA951) || // Mn [11] REJANG VOWEL SIGN I..REJANG CONSONANT SIGN R\r\n\t\t(0xA980 <= code && code <= 0xA982) || // Mn [3] JAVANESE SIGN PANYANGGA..JAVANESE SIGN LAYAR\r\n\t\t0xA9B3 == code || // Mn JAVANESE SIGN CECAK TELU\r\n\t\t(0xA9B6 <= code && code <= 0xA9B9) || // Mn [4] JAVANESE VOWEL SIGN WULU..JAVANESE VOWEL SIGN SUKU MENDUT\r\n\t\t0xA9BC == code || // Mn JAVANESE VOWEL SIGN PEPET\r\n\t\t0xA9E5 == code || // Mn MYANMAR SIGN SHAN SAW\r\n\t\t(0xAA29 <= code && code <= 0xAA2E) || // Mn [6] CHAM VOWEL SIGN AA..CHAM VOWEL SIGN OE\r\n\t\t(0xAA31 <= code && code <= 0xAA32) || // Mn [2] CHAM VOWEL SIGN AU..CHAM VOWEL SIGN UE\r\n\t\t(0xAA35 <= code && code <= 0xAA36) || // Mn [2] CHAM CONSONANT SIGN LA..CHAM CONSONANT SIGN WA\r\n\t\t0xAA43 == code || // Mn CHAM CONSONANT SIGN FINAL NG\r\n\t\t0xAA4C == code || // Mn CHAM CONSONANT SIGN FINAL M\r\n\t\t0xAA7C == code || // Mn MYANMAR SIGN TAI LAING TONE-2\r\n\t\t0xAAB0 == code || // Mn TAI VIET MAI KANG\r\n\t\t(0xAAB2 <= code && code <= 0xAAB4) || // Mn [3] TAI VIET VOWEL I..TAI VIET VOWEL U\r\n\t\t(0xAAB7 <= code && code <= 0xAAB8) || // Mn [2] TAI VIET MAI KHIT..TAI VIET VOWEL IA\r\n\t\t(0xAABE <= code && code <= 0xAABF) || // Mn [2] TAI VIET VOWEL AM..TAI VIET TONE MAI EK\r\n\t\t0xAAC1 == code || // Mn TAI VIET TONE MAI THO\r\n\t\t(0xAAEC <= code && code <= 0xAAED) || // Mn [2] MEETEI MAYEK VOWEL SIGN UU..MEETEI MAYEK VOWEL SIGN AAI\r\n\t\t0xAAF6 == code || // Mn MEETEI MAYEK VIRAMA\r\n\t\t0xABE5 == code || // Mn MEETEI MAYEK VOWEL SIGN ANAP\r\n\t\t0xABE8 == code || // Mn MEETEI MAYEK VOWEL SIGN UNAP\r\n\t\t0xABED == code || // Mn MEETEI MAYEK APUN IYEK\r\n\t\t0xFB1E == code || // Mn HEBREW POINT JUDEO-SPANISH VARIKA\r\n\t\t(0xFE00 <= code && code <= 0xFE0F) || // Mn [16] VARIATION SELECTOR-1..VARIATION SELECTOR-16\r\n\t\t(0xFE20 <= code && code <= 0xFE2F) || // Mn [16] COMBINING LIGATURE LEFT HALF..COMBINING CYRILLIC TITLO RIGHT HALF\r\n\t\t(0xFF9E <= code && code <= 0xFF9F) || // Lm [2] HALFWIDTH KATAKANA VOICED SOUND MARK..HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK\r\n\t\t0x101FD == code || // Mn PHAISTOS DISC SIGN COMBINING OBLIQUE STROKE\r\n\t\t0x102E0 == code || // Mn COPTIC EPACT THOUSANDS MARK\r\n\t\t(0x10376 <= code && code <= 0x1037A) || // Mn [5] COMBINING OLD PERMIC LETTER AN..COMBINING OLD PERMIC LETTER SII\r\n\t\t(0x10A01 <= code && code <= 0x10A03) || // Mn [3] KHAROSHTHI VOWEL SIGN I..KHAROSHTHI VOWEL SIGN VOCALIC R\r\n\t\t(0x10A05 <= code && code <= 0x10A06) || // Mn [2] KHAROSHTHI VOWEL SIGN E..KHAROSHTHI VOWEL SIGN O\r\n\t\t(0x10A0C <= code && code <= 0x10A0F) || // Mn [4] KHAROSHTHI VOWEL LENGTH MARK..KHAROSHTHI SIGN VISARGA\r\n\t\t(0x10A38 <= code && code <= 0x10A3A) || // Mn [3] KHAROSHTHI SIGN BAR ABOVE..KHAROSHTHI SIGN DOT BELOW\r\n\t\t0x10A3F == code || // Mn KHAROSHTHI VIRAMA\r\n\t\t(0x10AE5 <= code && code <= 0x10AE6) || // Mn [2] MANICHAEAN ABBREVIATION MARK ABOVE..MANICHAEAN ABBREVIATION MARK BELOW\r\n\t\t0x11001 == code || // Mn BRAHMI SIGN ANUSVARA\r\n\t\t(0x11038 <= code && code <= 0x11046) || // Mn [15] BRAHMI VOWEL SIGN AA..BRAHMI VIRAMA\r\n\t\t(0x1107F <= code && code <= 0x11081) || // Mn [3] BRAHMI NUMBER JOINER..KAITHI SIGN ANUSVARA\r\n\t\t(0x110B3 <= code && code <= 0x110B6) || // Mn [4] KAITHI VOWEL SIGN U..KAITHI VOWEL SIGN AI\r\n\t\t(0x110B9 <= code && code <= 0x110BA) || // Mn [2] KAITHI SIGN VIRAMA..KAITHI SIGN NUKTA\r\n\t\t(0x11100 <= code && code <= 0x11102) || // Mn [3] CHAKMA SIGN CANDRABINDU..CHAKMA SIGN VISARGA\r\n\t\t(0x11127 <= code && code <= 0x1112B) || // Mn [5] CHAKMA VOWEL SIGN A..CHAKMA VOWEL SIGN UU\r\n\t\t(0x1112D <= code && code <= 0x11134) || // Mn [8] CHAKMA VOWEL SIGN AI..CHAKMA MAAYYAA\r\n\t\t0x11173 == code || // Mn MAHAJANI SIGN NUKTA\r\n\t\t(0x11180 <= code && code <= 0x11181) || // Mn [2] SHARADA SIGN CANDRABINDU..SHARADA SIGN ANUSVARA\r\n\t\t(0x111B6 <= code && code <= 0x111BE) || // Mn [9] SHARADA VOWEL SIGN U..SHARADA VOWEL SIGN O\r\n\t\t(0x111CA <= code && code <= 0x111CC) || // Mn [3] SHARADA SIGN NUKTA..SHARADA EXTRA SHORT VOWEL MARK\r\n\t\t(0x1122F <= code && code <= 0x11231) || // Mn [3] KHOJKI VOWEL SIGN U..KHOJKI VOWEL SIGN AI\r\n\t\t0x11234 == code || // Mn KHOJKI SIGN ANUSVARA\r\n\t\t(0x11236 <= code && code <= 0x11237) || // Mn [2] KHOJKI SIGN NUKTA..KHOJKI SIGN SHADDA\r\n\t\t0x1123E == code || // Mn KHOJKI SIGN SUKUN\r\n\t\t0x112DF == code || // Mn KHUDAWADI SIGN ANUSVARA\r\n\t\t(0x112E3 <= code && code <= 0x112EA) || // Mn [8] KHUDAWADI VOWEL SIGN U..KHUDAWADI SIGN VIRAMA\r\n\t\t(0x11300 <= code && code <= 0x11301) || // Mn [2] GRANTHA SIGN COMBINING ANUSVARA ABOVE..GRANTHA SIGN CANDRABINDU\r\n\t\t0x1133C == code || // Mn GRANTHA SIGN NUKTA\r\n\t\t0x1133E == code || // Mc GRANTHA VOWEL SIGN AA\r\n\t\t0x11340 == code || // Mn GRANTHA VOWEL SIGN II\r\n\t\t0x11357 == code || // Mc GRANTHA AU LENGTH MARK\r\n\t\t(0x11366 <= code && code <= 0x1136C) || // Mn [7] COMBINING GRANTHA DIGIT ZERO..COMBINING GRANTHA DIGIT SIX\r\n\t\t(0x11370 <= code && code <= 0x11374) || // Mn [5] COMBINING GRANTHA LETTER A..COMBINING GRANTHA LETTER PA\r\n\t\t(0x11438 <= code && code <= 0x1143F) || // Mn [8] NEWA VOWEL SIGN U..NEWA VOWEL SIGN AI\r\n\t\t(0x11442 <= code && code <= 0x11444) || // Mn [3] NEWA SIGN VIRAMA..NEWA SIGN ANUSVARA\r\n\t\t0x11446 == code || // Mn NEWA SIGN NUKTA\r\n\t\t0x114B0 == code || // Mc TIRHUTA VOWEL SIGN AA\r\n\t\t(0x114B3 <= code && code <= 0x114B8) || // Mn [6] TIRHUTA VOWEL SIGN U..TIRHUTA VOWEL SIGN VOCALIC LL\r\n\t\t0x114BA == code || // Mn TIRHUTA VOWEL SIGN SHORT E\r\n\t\t0x114BD == code || // Mc TIRHUTA VOWEL SIGN SHORT O\r\n\t\t(0x114BF <= code && code <= 0x114C0) || // Mn [2] TIRHUTA SIGN CANDRABINDU..TIRHUTA SIGN ANUSVARA\r\n\t\t(0x114C2 <= code && code <= 0x114C3) || // Mn [2] TIRHUTA SIGN VIRAMA..TIRHUTA SIGN NUKTA\r\n\t\t0x115AF == code || // Mc SIDDHAM VOWEL SIGN AA\r\n\t\t(0x115B2 <= code && code <= 0x115B5) || // Mn [4] SIDDHAM VOWEL SIGN U..SIDDHAM VOWEL SIGN VOCALIC RR\r\n\t\t(0x115BC <= code && code <= 0x115BD) || // Mn [2] SIDDHAM SIGN CANDRABINDU..SIDDHAM SIGN ANUSVARA\r\n\t\t(0x115BF <= code && code <= 0x115C0) || // Mn [2] SIDDHAM SIGN VIRAMA..SIDDHAM SIGN NUKTA\r\n\t\t(0x115DC <= code && code <= 0x115DD) || // Mn [2] SIDDHAM VOWEL SIGN ALTERNATE U..SIDDHAM VOWEL SIGN ALTERNATE UU\r\n\t\t(0x11633 <= code && code <= 0x1163A) || // Mn [8] MODI VOWEL SIGN U..MODI VOWEL SIGN AI\r\n\t\t0x1163D == code || // Mn MODI SIGN ANUSVARA\r\n\t\t(0x1163F <= code && code <= 0x11640) || // Mn [2] MODI SIGN VIRAMA..MODI SIGN ARDHACANDRA\r\n\t\t0x116AB == code || // Mn TAKRI SIGN ANUSVARA\r\n\t\t0x116AD == code || // Mn TAKRI VOWEL SIGN AA\r\n\t\t(0x116B0 <= code && code <= 0x116B5) || // Mn [6] TAKRI VOWEL SIGN U..TAKRI VOWEL SIGN AU\r\n\t\t0x116B7 == code || // Mn TAKRI SIGN NUKTA\r\n\t\t(0x1171D <= code && code <= 0x1171F) || // Mn [3] AHOM CONSONANT SIGN MEDIAL LA..AHOM CONSONANT SIGN MEDIAL LIGATING RA\r\n\t\t(0x11722 <= code && code <= 0x11725) || // Mn [4] AHOM VOWEL SIGN I..AHOM VOWEL SIGN UU\r\n\t\t(0x11727 <= code && code <= 0x1172B) || // Mn [5] AHOM VOWEL SIGN AW..AHOM SIGN KILLER\r\n\t\t(0x11A01 <= code && code <= 0x11A06) || // Mn [6] ZANABAZAR SQUARE VOWEL SIGN I..ZANABAZAR SQUARE VOWEL SIGN O\r\n\t\t(0x11A09 <= code && code <= 0x11A0A) || // Mn [2] ZANABAZAR SQUARE VOWEL SIGN REVERSED I..ZANABAZAR SQUARE VOWEL LENGTH MARK\r\n\t\t(0x11A33 <= code && code <= 0x11A38) || // Mn [6] ZANABAZAR SQUARE FINAL CONSONANT MARK..ZANABAZAR SQUARE SIGN ANUSVARA\r\n\t\t(0x11A3B <= code && code <= 0x11A3E) || // Mn [4] ZANABAZAR SQUARE CLUSTER-FINAL LETTER YA..ZANABAZAR SQUARE CLUSTER-FINAL LETTER VA\r\n\t\t0x11A47 == code || // Mn ZANABAZAR SQUARE SUBJOINER\r\n\t\t(0x11A51 <= code && code <= 0x11A56) || // Mn [6] SOYOMBO VOWEL SIGN I..SOYOMBO VOWEL SIGN OE\r\n\t\t(0x11A59 <= code && code <= 0x11A5B) || // Mn [3] SOYOMBO VOWEL SIGN VOCALIC R..SOYOMBO VOWEL LENGTH MARK\r\n\t\t(0x11A8A <= code && code <= 0x11A96) || // Mn [13] SOYOMBO FINAL CONSONANT SIGN G..SOYOMBO SIGN ANUSVARA\r\n\t\t(0x11A98 <= code && code <= 0x11A99) || // Mn [2] SOYOMBO GEMINATION MARK..SOYOMBO SUBJOINER\r\n\t\t(0x11C30 <= code && code <= 0x11C36) || // Mn [7] BHAIKSUKI VOWEL SIGN I..BHAIKSUKI VOWEL SIGN VOCALIC L\r\n\t\t(0x11C38 <= code && code <= 0x11C3D) || // Mn [6] BHAIKSUKI VOWEL SIGN E..BHAIKSUKI SIGN ANUSVARA\r\n\t\t0x11C3F == code || // Mn BHAIKSUKI SIGN VIRAMA\r\n\t\t(0x11C92 <= code && code <= 0x11CA7) || // Mn [22] MARCHEN SUBJOINED LETTER KA..MARCHEN SUBJOINED LETTER ZA\r\n\t\t(0x11CAA <= code && code <= 0x11CB0) || // Mn [7] MARCHEN SUBJOINED LETTER RA..MARCHEN VOWEL SIGN AA\r\n\t\t(0x11CB2 <= code && code <= 0x11CB3) || // Mn [2] MARCHEN VOWEL SIGN U..MARCHEN VOWEL SIGN E\r\n\t\t(0x11CB5 <= code && code <= 0x11CB6) || // Mn [2] MARCHEN SIGN ANUSVARA..MARCHEN SIGN CANDRABINDU\r\n\t\t(0x11D31 <= code && code <= 0x11D36) || // Mn [6] MASARAM GONDI VOWEL SIGN AA..MASARAM GONDI VOWEL SIGN VOCALIC R\r\n\t\t0x11D3A == code || // Mn MASARAM GONDI VOWEL SIGN E\r\n\t\t(0x11D3C <= code && code <= 0x11D3D) || // Mn [2] MASARAM GONDI VOWEL SIGN AI..MASARAM GONDI VOWEL SIGN O\r\n\t\t(0x11D3F <= code && code <= 0x11D45) || // Mn [7] MASARAM GONDI VOWEL SIGN AU..MASARAM GONDI VIRAMA\r\n\t\t0x11D47 == code || // Mn MASARAM GONDI RA-KARA\r\n\t\t(0x16AF0 <= code && code <= 0x16AF4) || // Mn [5] BASSA VAH COMBINING HIGH TONE..BASSA VAH COMBINING HIGH-LOW TONE\r\n\t\t(0x16B30 <= code && code <= 0x16B36) || // Mn [7] PAHAWH HMONG MARK CIM TUB..PAHAWH HMONG MARK CIM TAUM\r\n\t\t(0x16F8F <= code && code <= 0x16F92) || // Mn [4] MIAO TONE RIGHT..MIAO TONE BELOW\r\n\t\t(0x1BC9D <= code && code <= 0x1BC9E) || // Mn [2] DUPLOYAN THICK LETTER SELECTOR..DUPLOYAN DOUBLE MARK\r\n\t\t0x1D165 == code || // Mc MUSICAL SYMBOL COMBINING STEM\r\n\t\t(0x1D167 <= code && code <= 0x1D169) || // Mn [3] MUSICAL SYMBOL COMBINING TREMOLO-1..MUSICAL SYMBOL COMBINING TREMOLO-3\r\n\t\t(0x1D16E <= code && code <= 0x1D172) || // Mc [5] MUSICAL SYMBOL COMBINING FLAG-1..MUSICAL SYMBOL COMBINING FLAG-5\r\n\t\t(0x1D17B <= code && code <= 0x1D182) || // Mn [8] MUSICAL SYMBOL COMBINING ACCENT..MUSICAL SYMBOL COMBINING LOURE\r\n\t\t(0x1D185 <= code && code <= 0x1D18B) || // Mn [7] MUSICAL SYMBOL COMBINING DOIT..MUSICAL SYMBOL COMBINING TRIPLE TONGUE\r\n\t\t(0x1D1AA <= code && code <= 0x1D1AD) || // Mn [4] MUSICAL SYMBOL COMBINING DOWN BOW..MUSICAL SYMBOL COMBINING SNAP PIZZICATO\r\n\t\t(0x1D242 <= code && code <= 0x1D244) || // Mn [3] COMBINING GREEK MUSICAL TRISEME..COMBINING GREEK MUSICAL PENTASEME\r\n\t\t(0x1DA00 <= code && code <= 0x1DA36) || // Mn [55] SIGNWRITING HEAD RIM..SIGNWRITING AIR SUCKING IN\r\n\t\t(0x1DA3B <= code && code <= 0x1DA6C) || // Mn [50] SIGNWRITING MOUTH CLOSED NEUTRAL..SIGNWRITING EXCITEMENT\r\n\t\t0x1DA75 == code || // Mn SIGNWRITING UPPER BODY TILTING FROM HIP JOINTS\r\n\t\t0x1DA84 == code || // Mn SIGNWRITING LOCATION HEAD NECK\r\n\t\t(0x1DA9B <= code && code <= 0x1DA9F) || // Mn [5] SIGNWRITING FILL MODIFIER-2..SIGNWRITING FILL MODIFIER-6\r\n\t\t(0x1DAA1 <= code && code <= 0x1DAAF) || // Mn [15] SIGNWRITING ROTATION MODIFIER-2..SIGNWRITING ROTATION MODIFIER-16\r\n\t\t(0x1E000 <= code && code <= 0x1E006) || // Mn [7] COMBINING GLAGOLITIC LETTER AZU..COMBINING GLAGOLITIC LETTER ZHIVETE\r\n\t\t(0x1E008 <= code && code <= 0x1E018) || // Mn [17] COMBINING GLAGOLITIC LETTER ZEMLJA..COMBINING GLAGOLITIC LETTER HERU\r\n\t\t(0x1E01B <= code && code <= 0x1E021) || // Mn [7] COMBINING GLAGOLITIC LETTER SHTA..COMBINING GLAGOLITIC LETTER YATI\r\n\t\t(0x1E023 <= code && code <= 0x1E024) || // Mn [2] COMBINING GLAGOLITIC LETTER YU..COMBINING GLAGOLITIC LETTER SMALL YUS\r\n\t\t(0x1E026 <= code && code <= 0x1E02A) || // Mn [5] COMBINING GLAGOLITIC LETTER YO..COMBINING GLAGOLITIC LETTER FITA\r\n\t\t(0x1E8D0 <= code && code <= 0x1E8D6) || // Mn [7] MENDE KIKAKUI COMBINING NUMBER TEENS..MENDE KIKAKUI COMBINING NUMBER MILLIONS\r\n\t\t(0x1E944 <= code && code <= 0x1E94A) || // Mn [7] ADLAM ALIF LENGTHENER..ADLAM NUKTA\r\n\t\t(0xE0020 <= code && code <= 0xE007F) || // Cf [96] TAG SPACE..CANCEL TAG\r\n\t\t(0xE0100 <= code && code <= 0xE01EF) // Mn [240] VARIATION SELECTOR-17..VARIATION SELECTOR-256\r\n\t\t){\r\n\t\t\treturn Extend;\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\tif(\r\n\t\t(0x1F1E6 <= code && code <= 0x1F1FF) // So [26] REGIONAL INDICATOR SYMBOL LETTER A..REGIONAL INDICATOR SYMBOL LETTER Z\r\n\t\t){\r\n\t\t\treturn Regional_Indicator;\r\n\t\t}\r\n\t\t\r\n\t\tif(\r\n\t\t0x0903 == code || // Mc DEVANAGARI SIGN VISARGA\r\n\t\t0x093B == code || // Mc DEVANAGARI VOWEL SIGN OOE\r\n\t\t(0x093E <= code && code <= 0x0940) || // Mc [3] DEVANAGARI VOWEL SIGN AA..DEVANAGARI VOWEL SIGN II\r\n\t\t(0x0949 <= code && code <= 0x094C) || // Mc [4] DEVANAGARI VOWEL SIGN CANDRA O..DEVANAGARI VOWEL SIGN AU\r\n\t\t(0x094E <= code && code <= 0x094F) || // Mc [2] DEVANAGARI VOWEL SIGN PRISHTHAMATRA E..DEVANAGARI VOWEL SIGN AW\r\n\t\t(0x0982 <= code && code <= 0x0983) || // Mc [2] BENGALI SIGN ANUSVARA..BENGALI SIGN VISARGA\r\n\t\t(0x09BF <= code && code <= 0x09C0) || // Mc [2] BENGALI VOWEL SIGN I..BENGALI VOWEL SIGN II\r\n\t\t(0x09C7 <= code && code <= 0x09C8) || // Mc [2] BENGALI VOWEL SIGN E..BENGALI VOWEL SIGN AI\r\n\t\t(0x09CB <= code && code <= 0x09CC) || // Mc [2] BENGALI VOWEL SIGN O..BENGALI VOWEL SIGN AU\r\n\t\t0x0A03 == code || // Mc GURMUKHI SIGN VISARGA\r\n\t\t(0x0A3E <= code && code <= 0x0A40) || // Mc [3] GURMUKHI VOWEL SIGN AA..GURMUKHI VOWEL SIGN II\r\n\t\t0x0A83 == code || // Mc GUJARATI SIGN VISARGA\r\n\t\t(0x0ABE <= code && code <= 0x0AC0) || // Mc [3] GUJARATI VOWEL SIGN AA..GUJARATI VOWEL SIGN II\r\n\t\t0x0AC9 == code || // Mc GUJARATI VOWEL SIGN CANDRA O\r\n\t\t(0x0ACB <= code && code <= 0x0ACC) || // Mc [2] GUJARATI VOWEL SIGN O..GUJARATI VOWEL SIGN AU\r\n\t\t(0x0B02 <= code && code <= 0x0B03) || // Mc [2] ORIYA SIGN ANUSVARA..ORIYA SIGN VISARGA\r\n\t\t0x0B40 == code || // Mc ORIYA VOWEL SIGN II\r\n\t\t(0x0B47 <= code && code <= 0x0B48) || // Mc [2] ORIYA VOWEL SIGN E..ORIYA VOWEL SIGN AI\r\n\t\t(0x0B4B <= code && code <= 0x0B4C) || // Mc [2] ORIYA VOWEL SIGN O..ORIYA VOWEL SIGN AU\r\n\t\t0x0BBF == code || // Mc TAMIL VOWEL SIGN I\r\n\t\t(0x0BC1 <= code && code <= 0x0BC2) || // Mc [2] TAMIL VOWEL SIGN U..TAMIL VOWEL SIGN UU\r\n\t\t(0x0BC6 <= code && code <= 0x0BC8) || // Mc [3] TAMIL VOWEL SIGN E..TAMIL VOWEL SIGN AI\r\n\t\t(0x0BCA <= code && code <= 0x0BCC) || // Mc [3] TAMIL VOWEL SIGN O..TAMIL VOWEL SIGN AU\r\n\t\t(0x0C01 <= code && code <= 0x0C03) || // Mc [3] TELUGU SIGN CANDRABINDU..TELUGU SIGN VISARGA\r\n\t\t(0x0C41 <= code && code <= 0x0C44) || // Mc [4] TELUGU VOWEL SIGN U..TELUGU VOWEL SIGN VOCALIC RR\r\n\t\t(0x0C82 <= code && code <= 0x0C83) || // Mc [2] KANNADA SIGN ANUSVARA..KANNADA SIGN VISARGA\r\n\t\t0x0CBE == code || // Mc KANNADA VOWEL SIGN AA\r\n\t\t(0x0CC0 <= code && code <= 0x0CC1) || // Mc [2] KANNADA VOWEL SIGN II..KANNADA VOWEL SIGN U\r\n\t\t(0x0CC3 <= code && code <= 0x0CC4) || // Mc [2] KANNADA VOWEL SIGN VOCALIC R..KANNADA VOWEL SIGN VOCALIC RR\r\n\t\t(0x0CC7 <= code && code <= 0x0CC8) || // Mc [2] KANNADA VOWEL SIGN EE..KANNADA VOWEL SIGN AI\r\n\t\t(0x0CCA <= code && code <= 0x0CCB) || // Mc [2] KANNADA VOWEL SIGN O..KANNADA VOWEL SIGN OO\r\n\t\t(0x0D02 <= code && code <= 0x0D03) || // Mc [2] MALAYALAM SIGN ANUSVARA..MALAYALAM SIGN VISARGA\r\n\t\t(0x0D3F <= code && code <= 0x0D40) || // Mc [2] MALAYALAM VOWEL SIGN I..MALAYALAM VOWEL SIGN II\r\n\t\t(0x0D46 <= code && code <= 0x0D48) || // Mc [3] MALAYALAM VOWEL SIGN E..MALAYALAM VOWEL SIGN AI\r\n\t\t(0x0D4A <= code && code <= 0x0D4C) || // Mc [3] MALAYALAM VOWEL SIGN O..MALAYALAM VOWEL SIGN AU\r\n\t\t(0x0D82 <= code && code <= 0x0D83) || // Mc [2] SINHALA SIGN ANUSVARAYA..SINHALA SIGN VISARGAYA\r\n\t\t(0x0DD0 <= code && code <= 0x0DD1) || // Mc [2] SINHALA VOWEL SIGN KETTI AEDA-PILLA..SINHALA VOWEL SIGN DIGA AEDA-PILLA\r\n\t\t(0x0DD8 <= code && code <= 0x0DDE) || // Mc [7] SINHALA VOWEL SIGN GAETTA-PILLA..SINHALA VOWEL SIGN KOMBUVA HAA GAYANUKITTA\r\n\t\t(0x0DF2 <= code && code <= 0x0DF3) || // Mc [2] SINHALA VOWEL SIGN DIGA GAETTA-PILLA..SINHALA VOWEL SIGN DIGA GAYANUKITTA\r\n\t\t0x0E33 == code || // Lo THAI CHARACTER SARA AM\r\n\t\t0x0EB3 == code || // Lo LAO VOWEL SIGN AM\r\n\t\t(0x0F3E <= code && code <= 0x0F3F) || // Mc [2] TIBETAN SIGN YAR TSHES..TIBETAN SIGN MAR TSHES\r\n\t\t0x0F7F == code || // Mc TIBETAN SIGN RNAM BCAD\r\n\t\t0x1031 == code || // Mc MYANMAR VOWEL SIGN E\r\n\t\t(0x103B <= code && code <= 0x103C) || // Mc [2] MYANMAR CONSONANT SIGN MEDIAL YA..MYANMAR CONSONANT SIGN MEDIAL RA\r\n\t\t(0x1056 <= code && code <= 0x1057) || // Mc [2] MYANMAR VOWEL SIGN VOCALIC R..MYANMAR VOWEL SIGN VOCALIC RR\r\n\t\t0x1084 == code || // Mc MYANMAR VOWEL SIGN SHAN E\r\n\t\t0x17B6 == code || // Mc KHMER VOWEL SIGN AA\r\n\t\t(0x17BE <= code && code <= 0x17C5) || // Mc [8] KHMER VOWEL SIGN OE..KHMER VOWEL SIGN AU\r\n\t\t(0x17C7 <= code && code <= 0x17C8) || // Mc [2] KHMER SIGN REAHMUK..KHMER SIGN YUUKALEAPINTU\r\n\t\t(0x1923 <= code && code <= 0x1926) || // Mc [4] LIMBU VOWEL SIGN EE..LIMBU VOWEL SIGN AU\r\n\t\t(0x1929 <= code && code <= 0x192B) || // Mc [3] LIMBU SUBJOINED LETTER YA..LIMBU SUBJOINED LETTER WA\r\n\t\t(0x1930 <= code && code <= 0x1931) || // Mc [2] LIMBU SMALL LETTER KA..LIMBU SMALL LETTER NGA\r\n\t\t(0x1933 <= code && code <= 0x1938) || // Mc [6] LIMBU SMALL LETTER TA..LIMBU SMALL LETTER LA\r\n\t\t(0x1A19 <= code && code <= 0x1A1A) || // Mc [2] BUGINESE VOWEL SIGN E..BUGINESE VOWEL SIGN O\r\n\t\t0x1A55 == code || // Mc TAI THAM CONSONANT SIGN MEDIAL RA\r\n\t\t0x1A57 == code || // Mc TAI THAM CONSONANT SIGN LA TANG LAI\r\n\t\t(0x1A6D <= code && code <= 0x1A72) || // Mc [6] TAI THAM VOWEL SIGN OY..TAI THAM VOWEL SIGN THAM AI\r\n\t\t0x1B04 == code || // Mc BALINESE SIGN BISAH\r\n\t\t0x1B35 == code || // Mc BALINESE VOWEL SIGN TEDUNG\r\n\t\t0x1B3B == code || // Mc BALINESE VOWEL SIGN RA REPA TEDUNG\r\n\t\t(0x1B3D <= code && code <= 0x1B41) || // Mc [5] BALINESE VOWEL SIGN LA LENGA TEDUNG..BALINESE VOWEL SIGN TALING REPA TEDUNG\r\n\t\t(0x1B43 <= code && code <= 0x1B44) || // Mc [2] BALINESE VOWEL SIGN PEPET TEDUNG..BALINESE ADEG ADEG\r\n\t\t0x1B82 == code || // Mc SUNDANESE SIGN PANGWISAD\r\n\t\t0x1BA1 == code || // Mc SUNDANESE CONSONANT SIGN PAMINGKAL\r\n\t\t(0x1BA6 <= code && code <= 0x1BA7) || // Mc [2] SUNDANESE VOWEL SIGN PANAELAENG..SUNDANESE VOWEL SIGN PANOLONG\r\n\t\t0x1BAA == code || // Mc SUNDANESE SIGN PAMAAEH\r\n\t\t0x1BE7 == code || // Mc BATAK VOWEL SIGN E\r\n\t\t(0x1BEA <= code && code <= 0x1BEC) || // Mc [3] BATAK VOWEL SIGN I..BATAK VOWEL SIGN O\r\n\t\t0x1BEE == code || // Mc BATAK VOWEL SIGN U\r\n\t\t(0x1BF2 <= code && code <= 0x1BF3) || // Mc [2] BATAK PANGOLAT..BATAK PANONGONAN\r\n\t\t(0x1C24 <= code && code <= 0x1C2B) || // Mc [8] LEPCHA SUBJOINED LETTER YA..LEPCHA VOWEL SIGN UU\r\n\t\t(0x1C34 <= code && code <= 0x1C35) || // Mc [2] LEPCHA CONSONANT SIGN NYIN-DO..LEPCHA CONSONANT SIGN KANG\r\n\t\t0x1CE1 == code || // Mc VEDIC TONE ATHARVAVEDIC INDEPENDENT SVARITA\r\n\t\t(0x1CF2 <= code && code <= 0x1CF3) || // Mc [2] VEDIC SIGN ARDHAVISARGA..VEDIC SIGN ROTATED ARDHAVISARGA\r\n\t\t0x1CF7 == code || // Mc VEDIC SIGN ATIKRAMA\r\n\t\t(0xA823 <= code && code <= 0xA824) || // Mc [2] SYLOTI NAGRI VOWEL SIGN A..SYLOTI NAGRI VOWEL SIGN I\r\n\t\t0xA827 == code || // Mc SYLOTI NAGRI VOWEL SIGN OO\r\n\t\t(0xA880 <= code && code <= 0xA881) || // Mc [2] SAURASHTRA SIGN ANUSVARA..SAURASHTRA SIGN VISARGA\r\n\t\t(0xA8B4 <= code && code <= 0xA8C3) || // Mc [16] SAURASHTRA CONSONANT SIGN HAARU..SAURASHTRA VOWEL SIGN AU\r\n\t\t(0xA952 <= code && code <= 0xA953) || // Mc [2] REJANG CONSONANT SIGN H..REJANG VIRAMA\r\n\t\t0xA983 == code || // Mc JAVANESE SIGN WIGNYAN\r\n\t\t(0xA9B4 <= code && code <= 0xA9B5) || // Mc [2] JAVANESE VOWEL SIGN TARUNG..JAVANESE VOWEL SIGN TOLONG\r\n\t\t(0xA9BA <= code && code <= 0xA9BB) || // Mc [2] JAVANESE VOWEL SIGN TALING..JAVANESE VOWEL SIGN DIRGA MURE\r\n\t\t(0xA9BD <= code && code <= 0xA9C0) || // Mc [4] JAVANESE CONSONANT SIGN KERET..JAVANESE PANGKON\r\n\t\t(0xAA2F <= code && code <= 0xAA30) || // Mc [2] CHAM VOWEL SIGN O..CHAM VOWEL SIGN AI\r\n\t\t(0xAA33 <= code && code <= 0xAA34) || // Mc [2] CHAM CONSONANT SIGN YA..CHAM CONSONANT SIGN RA\r\n\t\t0xAA4D == code || // Mc CHAM CONSONANT SIGN FINAL H\r\n\t\t0xAAEB == code || // Mc MEETEI MAYEK VOWEL SIGN II\r\n\t\t(0xAAEE <= code && code <= 0xAAEF) || // Mc [2] MEETEI MAYEK VOWEL SIGN AU..MEETEI MAYEK VOWEL SIGN AAU\r\n\t\t0xAAF5 == code || // Mc MEETEI MAYEK VOWEL SIGN VISARGA\r\n\t\t(0xABE3 <= code && code <= 0xABE4) || // Mc [2] MEETEI MAYEK VOWEL SIGN ONAP..MEETEI MAYEK VOWEL SIGN INAP\r\n\t\t(0xABE6 <= code && code <= 0xABE7) || // Mc [2] MEETEI MAYEK VOWEL SIGN YENAP..MEETEI MAYEK VOWEL SIGN SOUNAP\r\n\t\t(0xABE9 <= code && code <= 0xABEA) || // Mc [2] MEETEI MAYEK VOWEL SIGN CHEINAP..MEETEI MAYEK VOWEL SIGN NUNG\r\n\t\t0xABEC == code || // Mc MEETEI MAYEK LUM IYEK\r\n\t\t0x11000 == code || // Mc BRAHMI SIGN CANDRABINDU\r\n\t\t0x11002 == code || // Mc BRAHMI SIGN VISARGA\r\n\t\t0x11082 == code || // Mc KAITHI SIGN VISARGA\r\n\t\t(0x110B0 <= code && code <= 0x110B2) || // Mc [3] KAITHI VOWEL SIGN AA..KAITHI VOWEL SIGN II\r\n\t\t(0x110B7 <= code && code <= 0x110B8) || // Mc [2] KAITHI VOWEL SIGN O..KAITHI VOWEL SIGN AU\r\n\t\t0x1112C == code || // Mc CHAKMA VOWEL SIGN E\r\n\t\t0x11182 == code || // Mc SHARADA SIGN VISARGA\r\n\t\t(0x111B3 <= code && code <= 0x111B5) || // Mc [3] SHARADA VOWEL SIGN AA..SHARADA VOWEL SIGN II\r\n\t\t(0x111BF <= code && code <= 0x111C0) || // Mc [2] SHARADA VOWEL SIGN AU..SHARADA SIGN VIRAMA\r\n\t\t(0x1122C <= code && code <= 0x1122E) || // Mc [3] KHOJKI VOWEL SIGN AA..KHOJKI VOWEL SIGN II\r\n\t\t(0x11232 <= code && code <= 0x11233) || // Mc [2] KHOJKI VOWEL SIGN O..KHOJKI VOWEL SIGN AU\r\n\t\t0x11235 == code || // Mc KHOJKI SIGN VIRAMA\r\n\t\t(0x112E0 <= code && code <= 0x112E2) || // Mc [3] KHUDAWADI VOWEL SIGN AA..KHUDAWADI VOWEL SIGN II\r\n\t\t(0x11302 <= code && code <= 0x11303) || // Mc [2] GRANTHA SIGN ANUSVARA..GRANTHA SIGN VISARGA\r\n\t\t0x1133F == code || // Mc GRANTHA VOWEL SIGN I\r\n\t\t(0x11341 <= code && code <= 0x11344) || // Mc [4] GRANTHA VOWEL SIGN U..GRANTHA VOWEL SIGN VOCALIC RR\r\n\t\t(0x11347 <= code && code <= 0x11348) || // Mc [2] GRANTHA VOWEL SIGN EE..GRANTHA VOWEL SIGN AI\r\n\t\t(0x1134B <= code && code <= 0x1134D) || // Mc [3] GRANTHA VOWEL SIGN OO..GRANTHA SIGN VIRAMA\r\n\t\t(0x11362 <= code && code <= 0x11363) || // Mc [2] GRANTHA VOWEL SIGN VOCALIC L..GRANTHA VOWEL SIGN VOCALIC LL\r\n\t\t(0x11435 <= code && code <= 0x11437) || // Mc [3] NEWA VOWEL SIGN AA..NEWA VOWEL SIGN II\r\n\t\t(0x11440 <= code && code <= 0x11441) || // Mc [2] NEWA VOWEL SIGN O..NEWA VOWEL SIGN AU\r\n\t\t0x11445 == code || // Mc NEWA SIGN VISARGA\r\n\t\t(0x114B1 <= code && code <= 0x114B2) || // Mc [2] TIRHUTA VOWEL SIGN I..TIRHUTA VOWEL SIGN II\r\n\t\t0x114B9 == code || // Mc TIRHUTA VOWEL SIGN E\r\n\t\t(0x114BB <= code && code <= 0x114BC) || // Mc [2] TIRHUTA VOWEL SIGN AI..TIRHUTA VOWEL SIGN O\r\n\t\t0x114BE == code || // Mc TIRHUTA VOWEL SIGN AU\r\n\t\t0x114C1 == code || // Mc TIRHUTA SIGN VISARGA\r\n\t\t(0x115B0 <= code && code <= 0x115B1) || // Mc [2] SIDDHAM VOWEL SIGN I..SIDDHAM VOWEL SIGN II\r\n\t\t(0x115B8 <= code && code <= 0x115BB) || // Mc [4] SIDDHAM VOWEL SIGN E..SIDDHAM VOWEL SIGN AU\r\n\t\t0x115BE == code || // Mc SIDDHAM SIGN VISARGA\r\n\t\t(0x11630 <= code && code <= 0x11632) || // Mc [3] MODI VOWEL SIGN AA..MODI VOWEL SIGN II\r\n\t\t(0x1163B <= code && code <= 0x1163C) || // Mc [2] MODI VOWEL SIGN O..MODI VOWEL SIGN AU\r\n\t\t0x1163E == code || // Mc MODI SIGN VISARGA\r\n\t\t0x116AC == code || // Mc TAKRI SIGN VISARGA\r\n\t\t(0x116AE <= code && code <= 0x116AF) || // Mc [2] TAKRI VOWEL SIGN I..TAKRI VOWEL SIGN II\r\n\t\t0x116B6 == code || // Mc TAKRI SIGN VIRAMA\r\n\t\t(0x11720 <= code && code <= 0x11721) || // Mc [2] AHOM VOWEL SIGN A..AHOM VOWEL SIGN AA\r\n\t\t0x11726 == code || // Mc AHOM VOWEL SIGN E\r\n\t\t(0x11A07 <= code && code <= 0x11A08) || // Mc [2] ZANABAZAR SQUARE VOWEL SIGN AI..ZANABAZAR SQUARE VOWEL SIGN AU\r\n\t\t0x11A39 == code || // Mc ZANABAZAR SQUARE SIGN VISARGA\r\n\t\t(0x11A57 <= code && code <= 0x11A58) || // Mc [2] SOYOMBO VOWEL SIGN AI..SOYOMBO VOWEL SIGN AU\r\n\t\t0x11A97 == code || // Mc SOYOMBO SIGN VISARGA\r\n\t\t0x11C2F == code || // Mc BHAIKSUKI VOWEL SIGN AA\r\n\t\t0x11C3E == code || // Mc BHAIKSUKI SIGN VISARGA\r\n\t\t0x11CA9 == code || // Mc MARCHEN SUBJOINED LETTER YA\r\n\t\t0x11CB1 == code || // Mc MARCHEN VOWEL SIGN I\r\n\t\t0x11CB4 == code || // Mc MARCHEN VOWEL SIGN O\r\n\t\t(0x16F51 <= code && code <= 0x16F7E) || // Mc [46] MIAO SIGN ASPIRATION..MIAO VOWEL SIGN NG\r\n\t\t0x1D166 == code || // Mc MUSICAL SYMBOL COMBINING SPRECHGESANG STEM\r\n\t\t0x1D16D == code // Mc MUSICAL SYMBOL COMBINING AUGMENTATION DOT\r\n\t\t){\r\n\t\t\treturn SpacingMark;\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\tif(\r\n\t\t(0x1100 <= code && code <= 0x115F) || // Lo [96] HANGUL CHOSEONG KIYEOK..HANGUL CHOSEONG FILLER\r\n\t\t(0xA960 <= code && code <= 0xA97C) // Lo [29] HANGUL CHOSEONG TIKEUT-MIEUM..HANGUL CHOSEONG SSANGYEORINHIEUH\r\n\t\t){\r\n\t\t\treturn L;\r\n\t\t}\r\n\t\t\r\n\t\tif(\r\n\t\t(0x1160 <= code && code <= 0x11A7) || // Lo [72] HANGUL JUNGSEONG FILLER..HANGUL JUNGSEONG O-YAE\r\n\t\t(0xD7B0 <= code && code <= 0xD7C6) // Lo [23] HANGUL JUNGSEONG O-YEO..HANGUL JUNGSEONG ARAEA-E\r\n\t\t){\r\n\t\t\treturn V;\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\tif(\r\n\t\t(0x11A8 <= code && code <= 0x11FF) || // Lo [88] HANGUL JONGSEONG KIYEOK..HANGUL JONGSEONG SSANGNIEUN\r\n\t\t(0xD7CB <= code && code <= 0xD7FB) // Lo [49] HANGUL JONGSEONG NIEUN-RIEUL..HANGUL JONGSEONG PHIEUPH-THIEUTH\r\n\t\t){\r\n\t\t\treturn T;\r\n\t\t}\r\n\t\t\r\n\t\tif(\r\n\t\t0xAC00 == code || // Lo HANGUL SYLLABLE GA\r\n\t\t0xAC1C == code || // Lo HANGUL SYLLABLE GAE\r\n\t\t0xAC38 == code || // Lo HANGUL SYLLABLE GYA\r\n\t\t0xAC54 == code || // Lo HANGUL SYLLABLE GYAE\r\n\t\t0xAC70 == code || // Lo HANGUL SYLLABLE GEO\r\n\t\t0xAC8C == code || // Lo HANGUL SYLLABLE GE\r\n\t\t0xACA8 == code || // Lo HANGUL SYLLABLE GYEO\r\n\t\t0xACC4 == code || // Lo HANGUL SYLLABLE GYE\r\n\t\t0xACE0 == code || // Lo HANGUL SYLLABLE GO\r\n\t\t0xACFC == code || // Lo HANGUL SYLLABLE GWA\r\n\t\t0xAD18 == code || // Lo HANGUL SYLLABLE GWAE\r\n\t\t0xAD34 == code || // Lo HANGUL SYLLABLE GOE\r\n\t\t0xAD50 == code || // Lo HANGUL SYLLABLE GYO\r\n\t\t0xAD6C == code || // Lo HANGUL SYLLABLE GU\r\n\t\t0xAD88 == code || // Lo HANGUL SYLLABLE GWEO\r\n\t\t0xADA4 == code || // Lo HANGUL SYLLABLE GWE\r\n\t\t0xADC0 == code || // Lo HANGUL SYLLABLE GWI\r\n\t\t0xADDC == code || // Lo HANGUL SYLLABLE GYU\r\n\t\t0xADF8 == code || // Lo HANGUL SYLLABLE GEU\r\n\t\t0xAE14 == code || // Lo HANGUL SYLLABLE GYI\r\n\t\t0xAE30 == code || // Lo HANGUL SYLLABLE GI\r\n\t\t0xAE4C == code || // Lo HANGUL SYLLABLE GGA\r\n\t\t0xAE68 == code || // Lo HANGUL SYLLABLE GGAE\r\n\t\t0xAE84 == code || // Lo HANGUL SYLLABLE GGYA\r\n\t\t0xAEA0 == code || // Lo HANGUL SYLLABLE GGYAE\r\n\t\t0xAEBC == code || // Lo HANGUL SYLLABLE GGEO\r\n\t\t0xAED8 == code || // Lo HANGUL SYLLABLE GGE\r\n\t\t0xAEF4 == code || // Lo HANGUL SYLLABLE GGYEO\r\n\t\t0xAF10 == code || // Lo HANGUL SYLLABLE GGYE\r\n\t\t0xAF2C == code || // Lo HANGUL SYLLABLE GGO\r\n\t\t0xAF48 == code || // Lo HANGUL SYLLABLE GGWA\r\n\t\t0xAF64 == code || // Lo HANGUL SYLLABLE GGWAE\r\n\t\t0xAF80 == code || // Lo HANGUL SYLLABLE GGOE\r\n\t\t0xAF9C == code || // Lo HANGUL SYLLABLE GGYO\r\n\t\t0xAFB8 == code || // Lo HANGUL SYLLABLE GGU\r\n\t\t0xAFD4 == code || // Lo HANGUL SYLLABLE GGWEO\r\n\t\t0xAFF0 == code || // Lo HANGUL SYLLABLE GGWE\r\n\t\t0xB00C == code || // Lo HANGUL SYLLABLE GGWI\r\n\t\t0xB028 == code || // Lo HANGUL SYLLABLE GGYU\r\n\t\t0xB044 == code || // Lo HANGUL SYLLABLE GGEU\r\n\t\t0xB060 == code || // Lo HANGUL SYLLABLE GGYI\r\n\t\t0xB07C == code || // Lo HANGUL SYLLABLE GGI\r\n\t\t0xB098 == code || // Lo HANGUL SYLLABLE NA\r\n\t\t0xB0B4 == code || // Lo HANGUL SYLLABLE NAE\r\n\t\t0xB0D0 == code || // Lo HANGUL SYLLABLE NYA\r\n\t\t0xB0EC == code || // Lo HANGUL SYLLABLE NYAE\r\n\t\t0xB108 == code || // Lo HANGUL SYLLABLE NEO\r\n\t\t0xB124 == code || // Lo HANGUL SYLLABLE NE\r\n\t\t0xB140 == code || // Lo HANGUL SYLLABLE NYEO\r\n\t\t0xB15C == code || // Lo HANGUL SYLLABLE NYE\r\n\t\t0xB178 == code || // Lo HANGUL SYLLABLE NO\r\n\t\t0xB194 == code || // Lo HANGUL SYLLABLE NWA\r\n\t\t0xB1B0 == code || // Lo HANGUL SYLLABLE NWAE\r\n\t\t0xB1CC == code || // Lo HANGUL SYLLABLE NOE\r\n\t\t0xB1E8 == code || // Lo HANGUL SYLLABLE NYO\r\n\t\t0xB204 == code || // Lo HANGUL SYLLABLE NU\r\n\t\t0xB220 == code || // Lo HANGUL SYLLABLE NWEO\r\n\t\t0xB23C == code || // Lo HANGUL SYLLABLE NWE\r\n\t\t0xB258 == code || // Lo HANGUL SYLLABLE NWI\r\n\t\t0xB274 == code || // Lo HANGUL SYLLABLE NYU\r\n\t\t0xB290 == code || // Lo HANGUL SYLLABLE NEU\r\n\t\t0xB2AC == code || // Lo HANGUL SYLLABLE NYI\r\n\t\t0xB2C8 == code || // Lo HANGUL SYLLABLE NI\r\n\t\t0xB2E4 == code || // Lo HANGUL SYLLABLE DA\r\n\t\t0xB300 == code || // Lo HANGUL SYLLABLE DAE\r\n\t\t0xB31C == code || // Lo HANGUL SYLLABLE DYA\r\n\t\t0xB338 == code || // Lo HANGUL SYLLABLE DYAE\r\n\t\t0xB354 == code || // Lo HANGUL SYLLABLE DEO\r\n\t\t0xB370 == code || // Lo HANGUL SYLLABLE DE\r\n\t\t0xB38C == code || // Lo HANGUL SYLLABLE DYEO\r\n\t\t0xB3A8 == code || // Lo HANGUL SYLLABLE DYE\r\n\t\t0xB3C4 == code || // Lo HANGUL SYLLABLE DO\r\n\t\t0xB3E0 == code || // Lo HANGUL SYLLABLE DWA\r\n\t\t0xB3FC == code || // Lo HANGUL SYLLABLE DWAE\r\n\t\t0xB418 == code || // Lo HANGUL SYLLABLE DOE\r\n\t\t0xB434 == code || // Lo HANGUL SYLLABLE DYO\r\n\t\t0xB450 == code || // Lo HANGUL SYLLABLE DU\r\n\t\t0xB46C == code || // Lo HANGUL SYLLABLE DWEO\r\n\t\t0xB488 == code || // Lo HANGUL SYLLABLE DWE\r\n\t\t0xB4A4 == code || // Lo HANGUL SYLLABLE DWI\r\n\t\t0xB4C0 == code || // Lo HANGUL SYLLABLE DYU\r\n\t\t0xB4DC == code || // Lo HANGUL SYLLABLE DEU\r\n\t\t0xB4F8 == code || // Lo HANGUL SYLLABLE DYI\r\n\t\t0xB514 == code || // Lo HANGUL SYLLABLE DI\r\n\t\t0xB530 == code || // Lo HANGUL SYLLABLE DDA\r\n\t\t0xB54C == code || // Lo HANGUL SYLLABLE DDAE\r\n\t\t0xB568 == code || // Lo HANGUL SYLLABLE DDYA\r\n\t\t0xB584 == code || // Lo HANGUL SYLLABLE DDYAE\r\n\t\t0xB5A0 == code || // Lo HANGUL SYLLABLE DDEO\r\n\t\t0xB5BC == code || // Lo HANGUL SYLLABLE DDE\r\n\t\t0xB5D8 == code || // Lo HANGUL SYLLABLE DDYEO\r\n\t\t0xB5F4 == code || // Lo HANGUL SYLLABLE DDYE\r\n\t\t0xB610 == code || // Lo HANGUL SYLLABLE DDO\r\n\t\t0xB62C == code || // Lo HANGUL SYLLABLE DDWA\r\n\t\t0xB648 == code || // Lo HANGUL SYLLABLE DDWAE\r\n\t\t0xB664 == code || // Lo HANGUL SYLLABLE DDOE\r\n\t\t0xB680 == code || // Lo HANGUL SYLLABLE DDYO\r\n\t\t0xB69C == code || // Lo HANGUL SYLLABLE DDU\r\n\t\t0xB6B8 == code || // Lo HANGUL SYLLABLE DDWEO\r\n\t\t0xB6D4 == code || // Lo HANGUL SYLLABLE DDWE\r\n\t\t0xB6F0 == code || // Lo HANGUL SYLLABLE DDWI\r\n\t\t0xB70C == code || // Lo HANGUL SYLLABLE DDYU\r\n\t\t0xB728 == code || // Lo HANGUL SYLLABLE DDEU\r\n\t\t0xB744 == code || // Lo HANGUL SYLLABLE DDYI\r\n\t\t0xB760 == code || // Lo HANGUL SYLLABLE DDI\r\n\t\t0xB77C == code || // Lo HANGUL SYLLABLE RA\r\n\t\t0xB798 == code || // Lo HANGUL SYLLABLE RAE\r\n\t\t0xB7B4 == code || // Lo HANGUL SYLLABLE RYA\r\n\t\t0xB7D0 == code || // Lo HANGUL SYLLABLE RYAE\r\n\t\t0xB7EC == code || // Lo HANGUL SYLLABLE REO\r\n\t\t0xB808 == code || // Lo HANGUL SYLLABLE RE\r\n\t\t0xB824 == code || // Lo HANGUL SYLLABLE RYEO\r\n\t\t0xB840 == code || // Lo HANGUL SYLLABLE RYE\r\n\t\t0xB85C == code || // Lo HANGUL SYLLABLE RO\r\n\t\t0xB878 == code || // Lo HANGUL SYLLABLE RWA\r\n\t\t0xB894 == code || // Lo HANGUL SYLLABLE RWAE\r\n\t\t0xB8B0 == code || // Lo HANGUL SYLLABLE ROE\r\n\t\t0xB8CC == code || // Lo HANGUL SYLLABLE RYO\r\n\t\t0xB8E8 == code || // Lo HANGUL SYLLABLE RU\r\n\t\t0xB904 == code || // Lo HANGUL SYLLABLE RWEO\r\n\t\t0xB920 == code || // Lo HANGUL SYLLABLE RWE\r\n\t\t0xB93C == code || // Lo HANGUL SYLLABLE RWI\r\n\t\t0xB958 == code || // Lo HANGUL SYLLABLE RYU\r\n\t\t0xB974 == code || // Lo HANGUL SYLLABLE REU\r\n\t\t0xB990 == code || // Lo HANGUL SYLLABLE RYI\r\n\t\t0xB9AC == code || // Lo HANGUL SYLLABLE RI\r\n\t\t0xB9C8 == code || // Lo HANGUL SYLLABLE MA\r\n\t\t0xB9E4 == code || // Lo HANGUL SYLLABLE MAE\r\n\t\t0xBA00 == code || // Lo HANGUL SYLLABLE MYA\r\n\t\t0xBA1C == code || // Lo HANGUL SYLLABLE MYAE\r\n\t\t0xBA38 == code || // Lo HANGUL SYLLABLE MEO\r\n\t\t0xBA54 == code || // Lo HANGUL SYLLABLE ME\r\n\t\t0xBA70 == code || // Lo HANGUL SYLLABLE MYEO\r\n\t\t0xBA8C == code || // Lo HANGUL SYLLABLE MYE\r\n\t\t0xBAA8 == code || // Lo HANGUL SYLLABLE MO\r\n\t\t0xBAC4 == code || // Lo HANGUL SYLLABLE MWA\r\n\t\t0xBAE0 == code || // Lo HANGUL SYLLABLE MWAE\r\n\t\t0xBAFC == code || // Lo HANGUL SYLLABLE MOE\r\n\t\t0xBB18 == code || // Lo HANGUL SYLLABLE MYO\r\n\t\t0xBB34 == code || // Lo HANGUL SYLLABLE MU\r\n\t\t0xBB50 == code || // Lo HANGUL SYLLABLE MWEO\r\n\t\t0xBB6C == code || // Lo HANGUL SYLLABLE MWE\r\n\t\t0xBB88 == code || // Lo HANGUL SYLLABLE MWI\r\n\t\t0xBBA4 == code || // Lo HANGUL SYLLABLE MYU\r\n\t\t0xBBC0 == code || // Lo HANGUL SYLLABLE MEU\r\n\t\t0xBBDC == code || // Lo HANGUL SYLLABLE MYI\r\n\t\t0xBBF8 == code || // Lo HANGUL SYLLABLE MI\r\n\t\t0xBC14 == code || // Lo HANGUL SYLLABLE BA\r\n\t\t0xBC30 == code || // Lo HANGUL SYLLABLE BAE\r\n\t\t0xBC4C == code || // Lo HANGUL SYLLABLE BYA\r\n\t\t0xBC68 == code || // Lo HANGUL SYLLABLE BYAE\r\n\t\t0xBC84 == code || // Lo HANGUL SYLLABLE BEO\r\n\t\t0xBCA0 == code || // Lo HANGUL SYLLABLE BE\r\n\t\t0xBCBC == code || // Lo HANGUL SYLLABLE BYEO\r\n\t\t0xBCD8 == code || // Lo HANGUL SYLLABLE BYE\r\n\t\t0xBCF4 == code || // Lo HANGUL SYLLABLE BO\r\n\t\t0xBD10 == code || // Lo HANGUL SYLLABLE BWA\r\n\t\t0xBD2C == code || // Lo HANGUL SYLLABLE BWAE\r\n\t\t0xBD48 == code || // Lo HANGUL SYLLABLE BOE\r\n\t\t0xBD64 == code || // Lo HANGUL SYLLABLE BYO\r\n\t\t0xBD80 == code || // Lo HANGUL SYLLABLE BU\r\n\t\t0xBD9C == code || // Lo HANGUL SYLLABLE BWEO\r\n\t\t0xBDB8 == code || // Lo HANGUL SYLLABLE BWE\r\n\t\t0xBDD4 == code || // Lo HANGUL SYLLABLE BWI\r\n\t\t0xBDF0 == code || // Lo HANGUL SYLLABLE BYU\r\n\t\t0xBE0C == code || // Lo HANGUL SYLLABLE BEU\r\n\t\t0xBE28 == code || // Lo HANGUL SYLLABLE BYI\r\n\t\t0xBE44 == code || // Lo HANGUL SYLLABLE BI\r\n\t\t0xBE60 == code || // Lo HANGUL SYLLABLE BBA\r\n\t\t0xBE7C == code || // Lo HANGUL SYLLABLE BBAE\r\n\t\t0xBE98 == code || // Lo HANGUL SYLLABLE BBYA\r\n\t\t0xBEB4 == code || // Lo HANGUL SYLLABLE BBYAE\r\n\t\t0xBED0 == code || // Lo HANGUL SYLLABLE BBEO\r\n\t\t0xBEEC == code || // Lo HANGUL SYLLABLE BBE\r\n\t\t0xBF08 == code || // Lo HANGUL SYLLABLE BBYEO\r\n\t\t0xBF24 == code || // Lo HANGUL SYLLABLE BBYE\r\n\t\t0xBF40 == code || // Lo HANGUL SYLLABLE BBO\r\n\t\t0xBF5C == code || // Lo HANGUL SYLLABLE BBWA\r\n\t\t0xBF78 == code || // Lo HANGUL SYLLABLE BBWAE\r\n\t\t0xBF94 == code || // Lo HANGUL SYLLABLE BBOE\r\n\t\t0xBFB0 == code || // Lo HANGUL SYLLABLE BBYO\r\n\t\t0xBFCC == code || // Lo HANGUL SYLLABLE BBU\r\n\t\t0xBFE8 == code || // Lo HANGUL SYLLABLE BBWEO\r\n\t\t0xC004 == code || // Lo HANGUL SYLLABLE BBWE\r\n\t\t0xC020 == code || // Lo HANGUL SYLLABLE BBWI\r\n\t\t0xC03C == code || // Lo HANGUL SYLLABLE BBYU\r\n\t\t0xC058 == code || // Lo HANGUL SYLLABLE BBEU\r\n\t\t0xC074 == code || // Lo HANGUL SYLLABLE BBYI\r\n\t\t0xC090 == code || // Lo HANGUL SYLLABLE BBI\r\n\t\t0xC0AC == code || // Lo HANGUL SYLLABLE SA\r\n\t\t0xC0C8 == code || // Lo HANGUL SYLLABLE SAE\r\n\t\t0xC0E4 == code || // Lo HANGUL SYLLABLE SYA\r\n\t\t0xC100 == code || // Lo HANGUL SYLLABLE SYAE\r\n\t\t0xC11C == code || // Lo HANGUL SYLLABLE SEO\r\n\t\t0xC138 == code || // Lo HANGUL SYLLABLE SE\r\n\t\t0xC154 == code || // Lo HANGUL SYLLABLE SYEO\r\n\t\t0xC170 == code || // Lo HANGUL SYLLABLE SYE\r\n\t\t0xC18C == code || // Lo HANGUL SYLLABLE SO\r\n\t\t0xC1A8 == code || // Lo HANGUL SYLLABLE SWA\r\n\t\t0xC1C4 == code || // Lo HANGUL SYLLABLE SWAE\r\n\t\t0xC1E0 == code || // Lo HANGUL SYLLABLE SOE\r\n\t\t0xC1FC == code || // Lo HANGUL SYLLABLE SYO\r\n\t\t0xC218 == code || // Lo HANGUL SYLLABLE SU\r\n\t\t0xC234 == code || // Lo HANGUL SYLLABLE SWEO\r\n\t\t0xC250 == code || // Lo HANGUL SYLLABLE SWE\r\n\t\t0xC26C == code || // Lo HANGUL SYLLABLE SWI\r\n\t\t0xC288 == code || // Lo HANGUL SYLLABLE SYU\r\n\t\t0xC2A4 == code || // Lo HANGUL SYLLABLE SEU\r\n\t\t0xC2C0 == code || // Lo HANGUL SYLLABLE SYI\r\n\t\t0xC2DC == code || // Lo HANGUL SYLLABLE SI\r\n\t\t0xC2F8 == code || // Lo HANGUL SYLLABLE SSA\r\n\t\t0xC314 == code || // Lo HANGUL SYLLABLE SSAE\r\n\t\t0xC330 == code || // Lo HANGUL SYLLABLE SSYA\r\n\t\t0xC34C == code || // Lo HANGUL SYLLABLE SSYAE\r\n\t\t0xC368 == code || // Lo HANGUL SYLLABLE SSEO\r\n\t\t0xC384 == code || // Lo HANGUL SYLLABLE SSE\r\n\t\t0xC3A0 == code || // Lo HANGUL SYLLABLE SSYEO\r\n\t\t0xC3BC == code || // Lo HANGUL SYLLABLE SSYE\r\n\t\t0xC3D8 == code || // Lo HANGUL SYLLABLE SSO\r\n\t\t0xC3F4 == code || // Lo HANGUL SYLLABLE SSWA\r\n\t\t0xC410 == code || // Lo HANGUL SYLLABLE SSWAE\r\n\t\t0xC42C == code || // Lo HANGUL SYLLABLE SSOE\r\n\t\t0xC448 == code || // Lo HANGUL SYLLABLE SSYO\r\n\t\t0xC464 == code || // Lo HANGUL SYLLABLE SSU\r\n\t\t0xC480 == code || // Lo HANGUL SYLLABLE SSWEO\r\n\t\t0xC49C == code || // Lo HANGUL SYLLABLE SSWE\r\n\t\t0xC4B8 == code || // Lo HANGUL SYLLABLE SSWI\r\n\t\t0xC4D4 == code || // Lo HANGUL SYLLABLE SSYU\r\n\t\t0xC4F0 == code || // Lo HANGUL SYLLABLE SSEU\r\n\t\t0xC50C == code || // Lo HANGUL SYLLABLE SSYI\r\n\t\t0xC528 == code || // Lo HANGUL SYLLABLE SSI\r\n\t\t0xC544 == code || // Lo HANGUL SYLLABLE A\r\n\t\t0xC560 == code || // Lo HANGUL SYLLABLE AE\r\n\t\t0xC57C == code || // Lo HANGUL SYLLABLE YA\r\n\t\t0xC598 == code || // Lo HANGUL SYLLABLE YAE\r\n\t\t0xC5B4 == code || // Lo HANGUL SYLLABLE EO\r\n\t\t0xC5D0 == code || // Lo HANGUL SYLLABLE E\r\n\t\t0xC5EC == code || // Lo HANGUL SYLLABLE YEO\r\n\t\t0xC608 == code || // Lo HANGUL SYLLABLE YE\r\n\t\t0xC624 == code || // Lo HANGUL SYLLABLE O\r\n\t\t0xC640 == code || // Lo HANGUL SYLLABLE WA\r\n\t\t0xC65C == code || // Lo HANGUL SYLLABLE WAE\r\n\t\t0xC678 == code || // Lo HANGUL SYLLABLE OE\r\n\t\t0xC694 == code || // Lo HANGUL SYLLABLE YO\r\n\t\t0xC6B0 == code || // Lo HANGUL SYLLABLE U\r\n\t\t0xC6CC == code || // Lo HANGUL SYLLABLE WEO\r\n\t\t0xC6E8 == code || // Lo HANGUL SYLLABLE WE\r\n\t\t0xC704 == code || // Lo HANGUL SYLLABLE WI\r\n\t\t0xC720 == code || // Lo HANGUL SYLLABLE YU\r\n\t\t0xC73C == code || // Lo HANGUL SYLLABLE EU\r\n\t\t0xC758 == code || // Lo HANGUL SYLLABLE YI\r\n\t\t0xC774 == code || // Lo HANGUL SYLLABLE I\r\n\t\t0xC790 == code || // Lo HANGUL SYLLABLE JA\r\n\t\t0xC7AC == code || // Lo HANGUL SYLLABLE JAE\r\n\t\t0xC7C8 == code || // Lo HANGUL SYLLABLE JYA\r\n\t\t0xC7E4 == code || // Lo HANGUL SYLLABLE JYAE\r\n\t\t0xC800 == code || // Lo HANGUL SYLLABLE JEO\r\n\t\t0xC81C == code || // Lo HANGUL SYLLABLE JE\r\n\t\t0xC838 == code || // Lo HANGUL SYLLABLE JYEO\r\n\t\t0xC854 == code || // Lo HANGUL SYLLABLE JYE\r\n\t\t0xC870 == code || // Lo HANGUL SYLLABLE JO\r\n\t\t0xC88C == code || // Lo HANGUL SYLLABLE JWA\r\n\t\t0xC8A8 == code || // Lo HANGUL SYLLABLE JWAE\r\n\t\t0xC8C4 == code || // Lo HANGUL SYLLABLE JOE\r\n\t\t0xC8E0 == code || // Lo HANGUL SYLLABLE JYO\r\n\t\t0xC8FC == code || // Lo HANGUL SYLLABLE JU\r\n\t\t0xC918 == code || // Lo HANGUL SYLLABLE JWEO\r\n\t\t0xC934 == code || // Lo HANGUL SYLLABLE JWE\r\n\t\t0xC950 == code || // Lo HANGUL SYLLABLE JWI\r\n\t\t0xC96C == code || // Lo HANGUL SYLLABLE JYU\r\n\t\t0xC988 == code || // Lo HANGUL SYLLABLE JEU\r\n\t\t0xC9A4 == code || // Lo HANGUL SYLLABLE JYI\r\n\t\t0xC9C0 == code || // Lo HANGUL SYLLABLE JI\r\n\t\t0xC9DC == code || // Lo HANGUL SYLLABLE JJA\r\n\t\t0xC9F8 == code || // Lo HANGUL SYLLABLE JJAE\r\n\t\t0xCA14 == code || // Lo HANGUL SYLLABLE JJYA\r\n\t\t0xCA30 == code || // Lo HANGUL SYLLABLE JJYAE\r\n\t\t0xCA4C == code || // Lo HANGUL SYLLABLE JJEO\r\n\t\t0xCA68 == code || // Lo HANGUL SYLLABLE JJE\r\n\t\t0xCA84 == code || // Lo HANGUL SYLLABLE JJYEO\r\n\t\t0xCAA0 == code || // Lo HANGUL SYLLABLE JJYE\r\n\t\t0xCABC == code || // Lo HANGUL SYLLABLE JJO\r\n\t\t0xCAD8 == code || // Lo HANGUL SYLLABLE JJWA\r\n\t\t0xCAF4 == code || // Lo HANGUL SYLLABLE JJWAE\r\n\t\t0xCB10 == code || // Lo HANGUL SYLLABLE JJOE\r\n\t\t0xCB2C == code || // Lo HANGUL SYLLABLE JJYO\r\n\t\t0xCB48 == code || // Lo HANGUL SYLLABLE JJU\r\n\t\t0xCB64 == code || // Lo HANGUL SYLLABLE JJWEO\r\n\t\t0xCB80 == code || // Lo HANGUL SYLLABLE JJWE\r\n\t\t0xCB9C == code || // Lo HANGUL SYLLABLE JJWI\r\n\t\t0xCBB8 == code || // Lo HANGUL SYLLABLE JJYU\r\n\t\t0xCBD4 == code || // Lo HANGUL SYLLABLE JJEU\r\n\t\t0xCBF0 == code || // Lo HANGUL SYLLABLE JJYI\r\n\t\t0xCC0C == code || // Lo HANGUL SYLLABLE JJI\r\n\t\t0xCC28 == code || // Lo HANGUL SYLLABLE CA\r\n\t\t0xCC44 == code || // Lo HANGUL SYLLABLE CAE\r\n\t\t0xCC60 == code || // Lo HANGUL SYLLABLE CYA\r\n\t\t0xCC7C == code || // Lo HANGUL SYLLABLE CYAE\r\n\t\t0xCC98 == code || // Lo HANGUL SYLLABLE CEO\r\n\t\t0xCCB4 == code || // Lo HANGUL SYLLABLE CE\r\n\t\t0xCCD0 == code || // Lo HANGUL SYLLABLE CYEO\r\n\t\t0xCCEC == code || // Lo HANGUL SYLLABLE CYE\r\n\t\t0xCD08 == code || // Lo HANGUL SYLLABLE CO\r\n\t\t0xCD24 == code || // Lo HANGUL SYLLABLE CWA\r\n\t\t0xCD40 == code || // Lo HANGUL SYLLABLE CWAE\r\n\t\t0xCD5C == code || // Lo HANGUL SYLLABLE COE\r\n\t\t0xCD78 == code || // Lo HANGUL SYLLABLE CYO\r\n\t\t0xCD94 == code || // Lo HANGUL SYLLABLE CU\r\n\t\t0xCDB0 == code || // Lo HANGUL SYLLABLE CWEO\r\n\t\t0xCDCC == code || // Lo HANGUL SYLLABLE CWE\r\n\t\t0xCDE8 == code || // Lo HANGUL SYLLABLE CWI\r\n\t\t0xCE04 == code || // Lo HANGUL SYLLABLE CYU\r\n\t\t0xCE20 == code || // Lo HANGUL SYLLABLE CEU\r\n\t\t0xCE3C == code || // Lo HANGUL SYLLABLE CYI\r\n\t\t0xCE58 == code || // Lo HANGUL SYLLABLE CI\r\n\t\t0xCE74 == code || // Lo HANGUL SYLLABLE KA\r\n\t\t0xCE90 == code || // Lo HANGUL SYLLABLE KAE\r\n\t\t0xCEAC == code || // Lo HANGUL SYLLABLE KYA\r\n\t\t0xCEC8 == code || // Lo HANGUL SYLLABLE KYAE\r\n\t\t0xCEE4 == code || // Lo HANGUL SYLLABLE KEO\r\n\t\t0xCF00 == code || // Lo HANGUL SYLLABLE KE\r\n\t\t0xCF1C == code || // Lo HANGUL SYLLABLE KYEO\r\n\t\t0xCF38 == code || // Lo HANGUL SYLLABLE KYE\r\n\t\t0xCF54 == code || // Lo HANGUL SYLLABLE KO\r\n\t\t0xCF70 == code || // Lo HANGUL SYLLABLE KWA\r\n\t\t0xCF8C == code || // Lo HANGUL SYLLABLE KWAE\r\n\t\t0xCFA8 == code || // Lo HANGUL SYLLABLE KOE\r\n\t\t0xCFC4 == code || // Lo HANGUL SYLLABLE KYO\r\n\t\t0xCFE0 == code || // Lo HANGUL SYLLABLE KU\r\n\t\t0xCFFC == code || // Lo HANGUL SYLLABLE KWEO\r\n\t\t0xD018 == code || // Lo HANGUL SYLLABLE KWE\r\n\t\t0xD034 == code || // Lo HANGUL SYLLABLE KWI\r\n\t\t0xD050 == code || // Lo HANGUL SYLLABLE KYU\r\n\t\t0xD06C == code || // Lo HANGUL SYLLABLE KEU\r\n\t\t0xD088 == code || // Lo HANGUL SYLLABLE KYI\r\n\t\t0xD0A4 == code || // Lo HANGUL SYLLABLE KI\r\n\t\t0xD0C0 == code || // Lo HANGUL SYLLABLE TA\r\n\t\t0xD0DC == code || // Lo HANGUL SYLLABLE TAE\r\n\t\t0xD0F8 == code || // Lo HANGUL SYLLABLE TYA\r\n\t\t0xD114 == code || // Lo HANGUL SYLLABLE TYAE\r\n\t\t0xD130 == code || // Lo HANGUL SYLLABLE TEO\r\n\t\t0xD14C == code || // Lo HANGUL SYLLABLE TE\r\n\t\t0xD168 == code || // Lo HANGUL SYLLABLE TYEO\r\n\t\t0xD184 == code || // Lo HANGUL SYLLABLE TYE\r\n\t\t0xD1A0 == code || // Lo HANGUL SYLLABLE TO\r\n\t\t0xD1BC == code || // Lo HANGUL SYLLABLE TWA\r\n\t\t0xD1D8 == code || // Lo HANGUL SYLLABLE TWAE\r\n\t\t0xD1F4 == code || // Lo HANGUL SYLLABLE TOE\r\n\t\t0xD210 == code || // Lo HANGUL SYLLABLE TYO\r\n\t\t0xD22C == code || // Lo HANGUL SYLLABLE TU\r\n\t\t0xD248 == code || // Lo HANGUL SYLLABLE TWEO\r\n\t\t0xD264 == code || // Lo HANGUL SYLLABLE TWE\r\n\t\t0xD280 == code || // Lo HANGUL SYLLABLE TWI\r\n\t\t0xD29C == code || // Lo HANGUL SYLLABLE TYU\r\n\t\t0xD2B8 == code || // Lo HANGUL SYLLABLE TEU\r\n\t\t0xD2D4 == code || // Lo HANGUL SYLLABLE TYI\r\n\t\t0xD2F0 == code || // Lo HANGUL SYLLABLE TI\r\n\t\t0xD30C == code || // Lo HANGUL SYLLABLE PA\r\n\t\t0xD328 == code || // Lo HANGUL SYLLABLE PAE\r\n\t\t0xD344 == code || // Lo HANGUL SYLLABLE PYA\r\n\t\t0xD360 == code || // Lo HANGUL SYLLABLE PYAE\r\n\t\t0xD37C == code || // Lo HANGUL SYLLABLE PEO\r\n\t\t0xD398 == code || // Lo HANGUL SYLLABLE PE\r\n\t\t0xD3B4 == code || // Lo HANGUL SYLLABLE PYEO\r\n\t\t0xD3D0 == code || // Lo HANGUL SYLLABLE PYE\r\n\t\t0xD3EC == code || // Lo HANGUL SYLLABLE PO\r\n\t\t0xD408 == code || // Lo HANGUL SYLLABLE PWA\r\n\t\t0xD424 == code || // Lo HANGUL SYLLABLE PWAE\r\n\t\t0xD440 == code || // Lo HANGUL SYLLABLE POE\r\n\t\t0xD45C == code || // Lo HANGUL SYLLABLE PYO\r\n\t\t0xD478 == code || // Lo HANGUL SYLLABLE PU\r\n\t\t0xD494 == code || // Lo HANGUL SYLLABLE PWEO\r\n\t\t0xD4B0 == code || // Lo HANGUL SYLLABLE PWE\r\n\t\t0xD4CC == code || // Lo HANGUL SYLLABLE PWI\r\n\t\t0xD4E8 == code || // Lo HANGUL SYLLABLE PYU\r\n\t\t0xD504 == code || // Lo HANGUL SYLLABLE PEU\r\n\t\t0xD520 == code || // Lo HANGUL SYLLABLE PYI\r\n\t\t0xD53C == code || // Lo HANGUL SYLLABLE PI\r\n\t\t0xD558 == code || // Lo HANGUL SYLLABLE HA\r\n\t\t0xD574 == code || // Lo HANGUL SYLLABLE HAE\r\n\t\t0xD590 == code || // Lo HANGUL SYLLABLE HYA\r\n\t\t0xD5AC == code || // Lo HANGUL SYLLABLE HYAE\r\n\t\t0xD5C8 == code || // Lo HANGUL SYLLABLE HEO\r\n\t\t0xD5E4 == code || // Lo HANGUL SYLLABLE HE\r\n\t\t0xD600 == code || // Lo HANGUL SYLLABLE HYEO\r\n\t\t0xD61C == code || // Lo HANGUL SYLLABLE HYE\r\n\t\t0xD638 == code || // Lo HANGUL SYLLABLE HO\r\n\t\t0xD654 == code || // Lo HANGUL SYLLABLE HWA\r\n\t\t0xD670 == code || // Lo HANGUL SYLLABLE HWAE\r\n\t\t0xD68C == code || // Lo HANGUL SYLLABLE HOE\r\n\t\t0xD6A8 == code || // Lo HANGUL SYLLABLE HYO\r\n\t\t0xD6C4 == code || // Lo HANGUL SYLLABLE HU\r\n\t\t0xD6E0 == code || // Lo HANGUL SYLLABLE HWEO\r\n\t\t0xD6FC == code || // Lo HANGUL SYLLABLE HWE\r\n\t\t0xD718 == code || // Lo HANGUL SYLLABLE HWI\r\n\t\t0xD734 == code || // Lo HANGUL SYLLABLE HYU\r\n\t\t0xD750 == code || // Lo HANGUL SYLLABLE HEU\r\n\t\t0xD76C == code || // Lo HANGUL SYLLABLE HYI\r\n\t\t0xD788 == code // Lo HANGUL SYLLABLE HI\r\n\t\t){\r\n\t\t\treturn LV;\r\n\t\t}\r\n\t\t\r\n\t\tif(\r\n\t\t(0xAC01 <= code && code <= 0xAC1B) || // Lo [27] HANGUL SYLLABLE GAG..HANGUL SYLLABLE GAH\r\n\t\t(0xAC1D <= code && code <= 0xAC37) || // Lo [27] HANGUL SYLLABLE GAEG..HANGUL SYLLABLE GAEH\r\n\t\t(0xAC39 <= code && code <= 0xAC53) || // Lo [27] HANGUL SYLLABLE GYAG..HANGUL SYLLABLE GYAH\r\n\t\t(0xAC55 <= code && code <= 0xAC6F) || // Lo [27] HANGUL SYLLABLE GYAEG..HANGUL SYLLABLE GYAEH\r\n\t\t(0xAC71 <= code && code <= 0xAC8B) || // Lo [27] HANGUL SYLLABLE GEOG..HANGUL SYLLABLE GEOH\r\n\t\t(0xAC8D <= code && code <= 0xACA7) || // Lo [27] HANGUL SYLLABLE GEG..HANGUL SYLLABLE GEH\r\n\t\t(0xACA9 <= code && code <= 0xACC3) || // Lo [27] HANGUL SYLLABLE GYEOG..HANGUL SYLLABLE GYEOH\r\n\t\t(0xACC5 <= code && code <= 0xACDF) || // Lo [27] HANGUL SYLLABLE GYEG..HANGUL SYLLABLE GYEH\r\n\t\t(0xACE1 <= code && code <= 0xACFB) || // Lo [27] HANGUL SYLLABLE GOG..HANGUL SYLLABLE GOH\r\n\t\t(0xACFD <= code && code <= 0xAD17) || // Lo [27] HANGUL SYLLABLE GWAG..HANGUL SYLLABLE GWAH\r\n\t\t(0xAD19 <= code && code <= 0xAD33) || // Lo [27] HANGUL SYLLABLE GWAEG..HANGUL SYLLABLE GWAEH\r\n\t\t(0xAD35 <= code && code <= 0xAD4F) || // Lo [27] HANGUL SYLLABLE GOEG..HANGUL SYLLABLE GOEH\r\n\t\t(0xAD51 <= code && code <= 0xAD6B) || // Lo [27] HANGUL SYLLABLE GYOG..HANGUL SYLLABLE GYOH\r\n\t\t(0xAD6D <= code && code <= 0xAD87) || // Lo [27] HANGUL SYLLABLE GUG..HANGUL SYLLABLE GUH\r\n\t\t(0xAD89 <= code && code <= 0xADA3) || // Lo [27] HANGUL SYLLABLE GWEOG..HANGUL SYLLABLE GWEOH\r\n\t\t(0xADA5 <= code && code <= 0xADBF) || // Lo [27] HANGUL SYLLABLE GWEG..HANGUL SYLLABLE GWEH\r\n\t\t(0xADC1 <= code && code <= 0xADDB) || // Lo [27] HANGUL SYLLABLE GWIG..HANGUL SYLLABLE GWIH\r\n\t\t(0xADDD <= code && code <= 0xADF7) || // Lo [27] HANGUL SYLLABLE GYUG..HANGUL SYLLABLE GYUH\r\n\t\t(0xADF9 <= code && code <= 0xAE13) || // Lo [27] HANGUL SYLLABLE GEUG..HANGUL SYLLABLE GEUH\r\n\t\t(0xAE15 <= code && code <= 0xAE2F) || // Lo [27] HANGUL SYLLABLE GYIG..HANGUL SYLLABLE GYIH\r\n\t\t(0xAE31 <= code && code <= 0xAE4B) || // Lo [27] HANGUL SYLLABLE GIG..HANGUL SYLLABLE GIH\r\n\t\t(0xAE4D <= code && code <= 0xAE67) || // Lo [27] HANGUL SYLLABLE GGAG..HANGUL SYLLABLE GGAH\r\n\t\t(0xAE69 <= code && code <= 0xAE83) || // Lo [27] HANGUL SYLLABLE GGAEG..HANGUL SYLLABLE GGAEH\r\n\t\t(0xAE85 <= code && code <= 0xAE9F) || // Lo [27] HANGUL SYLLABLE GGYAG..HANGUL SYLLABLE GGYAH\r\n\t\t(0xAEA1 <= code && code <= 0xAEBB) || // Lo [27] HANGUL SYLLABLE GGYAEG..HANGUL SYLLABLE GGYAEH\r\n\t\t(0xAEBD <= code && code <= 0xAED7) || // Lo [27] HANGUL SYLLABLE GGEOG..HANGUL SYLLABLE GGEOH\r\n\t\t(0xAED9 <= code && code <= 0xAEF3) || // Lo [27] HANGUL SYLLABLE GGEG..HANGUL SYLLABLE GGEH\r\n\t\t(0xAEF5 <= code && code <= 0xAF0F) || // Lo [27] HANGUL SYLLABLE GGYEOG..HANGUL SYLLABLE GGYEOH\r\n\t\t(0xAF11 <= code && code <= 0xAF2B) || // Lo [27] HANGUL SYLLABLE GGYEG..HANGUL SYLLABLE GGYEH\r\n\t\t(0xAF2D <= code && code <= 0xAF47) || // Lo [27] HANGUL SYLLABLE GGOG..HANGUL SYLLABLE GGOH\r\n\t\t(0xAF49 <= code && code <= 0xAF63) || // Lo [27] HANGUL SYLLABLE GGWAG..HANGUL SYLLABLE GGWAH\r\n\t\t(0xAF65 <= code && code <= 0xAF7F) || // Lo [27] HANGUL SYLLABLE GGWAEG..HANGUL SYLLABLE GGWAEH\r\n\t\t(0xAF81 <= code && code <= 0xAF9B) || // Lo [27] HANGUL SYLLABLE GGOEG..HANGUL SYLLABLE GGOEH\r\n\t\t(0xAF9D <= code && code <= 0xAFB7) || // Lo [27] HANGUL SYLLABLE GGYOG..HANGUL SYLLABLE GGYOH\r\n\t\t(0xAFB9 <= code && code <= 0xAFD3) || // Lo [27] HANGUL SYLLABLE GGUG..HANGUL SYLLABLE GGUH\r\n\t\t(0xAFD5 <= code && code <= 0xAFEF) || // Lo [27] HANGUL SYLLABLE GGWEOG..HANGUL SYLLABLE GGWEOH\r\n\t\t(0xAFF1 <= code && code <= 0xB00B) || // Lo [27] HANGUL SYLLABLE GGWEG..HANGUL SYLLABLE GGWEH\r\n\t\t(0xB00D <= code && code <= 0xB027) || // Lo [27] HANGUL SYLLABLE GGWIG..HANGUL SYLLABLE GGWIH\r\n\t\t(0xB029 <= code && code <= 0xB043) || // Lo [27] HANGUL SYLLABLE GGYUG..HANGUL SYLLABLE GGYUH\r\n\t\t(0xB045 <= code && code <= 0xB05F) || // Lo [27] HANGUL SYLLABLE GGEUG..HANGUL SYLLABLE GGEUH\r\n\t\t(0xB061 <= code && code <= 0xB07B) || // Lo [27] HANGUL SYLLABLE GGYIG..HANGUL SYLLABLE GGYIH\r\n\t\t(0xB07D <= code && code <= 0xB097) || // Lo [27] HANGUL SYLLABLE GGIG..HANGUL SYLLABLE GGIH\r\n\t\t(0xB099 <= code && code <= 0xB0B3) || // Lo [27] HANGUL SYLLABLE NAG..HANGUL SYLLABLE NAH\r\n\t\t(0xB0B5 <= code && code <= 0xB0CF) || // Lo [27] HANGUL SYLLABLE NAEG..HANGUL SYLLABLE NAEH\r\n\t\t(0xB0D1 <= code && code <= 0xB0EB) || // Lo [27] HANGUL SYLLABLE NYAG..HANGUL SYLLABLE NYAH\r\n\t\t(0xB0ED <= code && code <= 0xB107) || // Lo [27] HANGUL SYLLABLE NYAEG..HANGUL SYLLABLE NYAEH\r\n\t\t(0xB109 <= code && code <= 0xB123) || // Lo [27] HANGUL SYLLABLE NEOG..HANGUL SYLLABLE NEOH\r\n\t\t(0xB125 <= code && code <= 0xB13F) || // Lo [27] HANGUL SYLLABLE NEG..HANGUL SYLLABLE NEH\r\n\t\t(0xB141 <= code && code <= 0xB15B) || // Lo [27] HANGUL SYLLABLE NYEOG..HANGUL SYLLABLE NYEOH\r\n\t\t(0xB15D <= code && code <= 0xB177) || // Lo [27] HANGUL SYLLABLE NYEG..HANGUL SYLLABLE NYEH\r\n\t\t(0xB179 <= code && code <= 0xB193) || // Lo [27] HANGUL SYLLABLE NOG..HANGUL SYLLABLE NOH\r\n\t\t(0xB195 <= code && code <= 0xB1AF) || // Lo [27] HANGUL SYLLABLE NWAG..HANGUL SYLLABLE NWAH\r\n\t\t(0xB1B1 <= code && code <= 0xB1CB) || // Lo [27] HANGUL SYLLABLE NWAEG..HANGUL SYLLABLE NWAEH\r\n\t\t(0xB1CD <= code && code <= 0xB1E7) || // Lo [27] HANGUL SYLLABLE NOEG..HANGUL SYLLABLE NOEH\r\n\t\t(0xB1E9 <= code && code <= 0xB203) || // Lo [27] HANGUL SYLLABLE NYOG..HANGUL SYLLABLE NYOH\r\n\t\t(0xB205 <= code && code <= 0xB21F) || // Lo [27] HANGUL SYLLABLE NUG..HANGUL SYLLABLE NUH\r\n\t\t(0xB221 <= code && code <= 0xB23B) || // Lo [27] HANGUL SYLLABLE NWEOG..HANGUL SYLLABLE NWEOH\r\n\t\t(0xB23D <= code && code <= 0xB257) || // Lo [27] HANGUL SYLLABLE NWEG..HANGUL SYLLABLE NWEH\r\n\t\t(0xB259 <= code && code <= 0xB273) || // Lo [27] HANGUL SYLLABLE NWIG..HANGUL SYLLABLE NWIH\r\n\t\t(0xB275 <= code && code <= 0xB28F) || // Lo [27] HANGUL SYLLABLE NYUG..HANGUL SYLLABLE NYUH\r\n\t\t(0xB291 <= code && code <= 0xB2AB) || // Lo [27] HANGUL SYLLABLE NEUG..HANGUL SYLLABLE NEUH\r\n\t\t(0xB2AD <= code && code <= 0xB2C7) || // Lo [27] HANGUL SYLLABLE NYIG..HANGUL SYLLABLE NYIH\r\n\t\t(0xB2C9 <= code && code <= 0xB2E3) || // Lo [27] HANGUL SYLLABLE NIG..HANGUL SYLLABLE NIH\r\n\t\t(0xB2E5 <= code && code <= 0xB2FF) || // Lo [27] HANGUL SYLLABLE DAG..HANGUL SYLLABLE DAH\r\n\t\t(0xB301 <= code && code <= 0xB31B) || // Lo [27] HANGUL SYLLABLE DAEG..HANGUL SYLLABLE DAEH\r\n\t\t(0xB31D <= code && code <= 0xB337) || // Lo [27] HANGUL SYLLABLE DYAG..HANGUL SYLLABLE DYAH\r\n\t\t(0xB339 <= code && code <= 0xB353) || // Lo [27] HANGUL SYLLABLE DYAEG..HANGUL SYLLABLE DYAEH\r\n\t\t(0xB355 <= code && code <= 0xB36F) || // Lo [27] HANGUL SYLLABLE DEOG..HANGUL SYLLABLE DEOH\r\n\t\t(0xB371 <= code && code <= 0xB38B) || // Lo [27] HANGUL SYLLABLE DEG..HANGUL SYLLABLE DEH\r\n\t\t(0xB38D <= code && code <= 0xB3A7) || // Lo [27] HANGUL SYLLABLE DYEOG..HANGUL SYLLABLE DYEOH\r\n\t\t(0xB3A9 <= code && code <= 0xB3C3) || // Lo [27] HANGUL SYLLABLE DYEG..HANGUL SYLLABLE DYEH\r\n\t\t(0xB3C5 <= code && code <= 0xB3DF) || // Lo [27] HANGUL SYLLABLE DOG..HANGUL SYLLABLE DOH\r\n\t\t(0xB3E1 <= code && code <= 0xB3FB) || // Lo [27] HANGUL SYLLABLE DWAG..HANGUL SYLLABLE DWAH\r\n\t\t(0xB3FD <= code && code <= 0xB417) || // Lo [27] HANGUL SYLLABLE DWAEG..HANGUL SYLLABLE DWAEH\r\n\t\t(0xB419 <= code && code <= 0xB433) || // Lo [27] HANGUL SYLLABLE DOEG..HANGUL SYLLABLE DOEH\r\n\t\t(0xB435 <= code && code <= 0xB44F) || // Lo [27] HANGUL SYLLABLE DYOG..HANGUL SYLLABLE DYOH\r\n\t\t(0xB451 <= code && code <= 0xB46B) || // Lo [27] HANGUL SYLLABLE DUG..HANGUL SYLLABLE DUH\r\n\t\t(0xB46D <= code && code <= 0xB487) || // Lo [27] HANGUL SYLLABLE DWEOG..HANGUL SYLLABLE DWEOH\r\n\t\t(0xB489 <= code && code <= 0xB4A3) || // Lo [27] HANGUL SYLLABLE DWEG..HANGUL SYLLABLE DWEH\r\n\t\t(0xB4A5 <= code && code <= 0xB4BF) || // Lo [27] HANGUL SYLLABLE DWIG..HANGUL SYLLABLE DWIH\r\n\t\t(0xB4C1 <= code && code <= 0xB4DB) || // Lo [27] HANGUL SYLLABLE DYUG..HANGUL SYLLABLE DYUH\r\n\t\t(0xB4DD <= code && code <= 0xB4F7) || // Lo [27] HANGUL SYLLABLE DEUG..HANGUL SYLLABLE DEUH\r\n\t\t(0xB4F9 <= code && code <= 0xB513) || // Lo [27] HANGUL SYLLABLE DYIG..HANGUL SYLLABLE DYIH\r\n\t\t(0xB515 <= code && code <= 0xB52F) || // Lo [27] HANGUL SYLLABLE DIG..HANGUL SYLLABLE DIH\r\n\t\t(0xB531 <= code && code <= 0xB54B) || // Lo [27] HANGUL SYLLABLE DDAG..HANGUL SYLLABLE DDAH\r\n\t\t(0xB54D <= code && code <= 0xB567) || // Lo [27] HANGUL SYLLABLE DDAEG..HANGUL SYLLABLE DDAEH\r\n\t\t(0xB569 <= code && code <= 0xB583) || // Lo [27] HANGUL SYLLABLE DDYAG..HANGUL SYLLABLE DDYAH\r\n\t\t(0xB585 <= code && code <= 0xB59F) || // Lo [27] HANGUL SYLLABLE DDYAEG..HANGUL SYLLABLE DDYAEH\r\n\t\t(0xB5A1 <= code && code <= 0xB5BB) || // Lo [27] HANGUL SYLLABLE DDEOG..HANGUL SYLLABLE DDEOH\r\n\t\t(0xB5BD <= code && code <= 0xB5D7) || // Lo [27] HANGUL SYLLABLE DDEG..HANGUL SYLLABLE DDEH\r\n\t\t(0xB5D9 <= code && code <= 0xB5F3) || // Lo [27] HANGUL SYLLABLE DDYEOG..HANGUL SYLLABLE DDYEOH\r\n\t\t(0xB5F5 <= code && code <= 0xB60F) || // Lo [27] HANGUL SYLLABLE DDYEG..HANGUL SYLLABLE DDYEH\r\n\t\t(0xB611 <= code && code <= 0xB62B) || // Lo [27] HANGUL SYLLABLE DDOG..HANGUL SYLLABLE DDOH\r\n\t\t(0xB62D <= code && code <= 0xB647) || // Lo [27] HANGUL SYLLABLE DDWAG..HANGUL SYLLABLE DDWAH\r\n\t\t(0xB649 <= code && code <= 0xB663) || // Lo [27] HANGUL SYLLABLE DDWAEG..HANGUL SYLLABLE DDWAEH\r\n\t\t(0xB665 <= code && code <= 0xB67F) || // Lo [27] HANGUL SYLLABLE DDOEG..HANGUL SYLLABLE DDOEH\r\n\t\t(0xB681 <= code && code <= 0xB69B) || // Lo [27] HANGUL SYLLABLE DDYOG..HANGUL SYLLABLE DDYOH\r\n\t\t(0xB69D <= code && code <= 0xB6B7) || // Lo [27] HANGUL SYLLABLE DDUG..HANGUL SYLLABLE DDUH\r\n\t\t(0xB6B9 <= code && code <= 0xB6D3) || // Lo [27] HANGUL SYLLABLE DDWEOG..HANGUL SYLLABLE DDWEOH\r\n\t\t(0xB6D5 <= code && code <= 0xB6EF) || // Lo [27] HANGUL SYLLABLE DDWEG..HANGUL SYLLABLE DDWEH\r\n\t\t(0xB6F1 <= code && code <= 0xB70B) || // Lo [27] HANGUL SYLLABLE DDWIG..HANGUL SYLLABLE DDWIH\r\n\t\t(0xB70D <= code && code <= 0xB727) || // Lo [27] HANGUL SYLLABLE DDYUG..HANGUL SYLLABLE DDYUH\r\n\t\t(0xB729 <= code && code <= 0xB743) || // Lo [27] HANGUL SYLLABLE DDEUG..HANGUL SYLLABLE DDEUH\r\n\t\t(0xB745 <= code && code <= 0xB75F) || // Lo [27] HANGUL SYLLABLE DDYIG..HANGUL SYLLABLE DDYIH\r\n\t\t(0xB761 <= code && code <= 0xB77B) || // Lo [27] HANGUL SYLLABLE DDIG..HANGUL SYLLABLE DDIH\r\n\t\t(0xB77D <= code && code <= 0xB797) || // Lo [27] HANGUL SYLLABLE RAG..HANGUL SYLLABLE RAH\r\n\t\t(0xB799 <= code && code <= 0xB7B3) || // Lo [27] HANGUL SYLLABLE RAEG..HANGUL SYLLABLE RAEH\r\n\t\t(0xB7B5 <= code && code <= 0xB7CF) || // Lo [27] HANGUL SYLLABLE RYAG..HANGUL SYLLABLE RYAH\r\n\t\t(0xB7D1 <= code && code <= 0xB7EB) || // Lo [27] HANGUL SYLLABLE RYAEG..HANGUL SYLLABLE RYAEH\r\n\t\t(0xB7ED <= code && code <= 0xB807) || // Lo [27] HANGUL SYLLABLE REOG..HANGUL SYLLABLE REOH\r\n\t\t(0xB809 <= code && code <= 0xB823) || // Lo [27] HANGUL SYLLABLE REG..HANGUL SYLLABLE REH\r\n\t\t(0xB825 <= code && code <= 0xB83F) || // Lo [27] HANGUL SYLLABLE RYEOG..HANGUL SYLLABLE RYEOH\r\n\t\t(0xB841 <= code && code <= 0xB85B) || // Lo [27] HANGUL SYLLABLE RYEG..HANGUL SYLLABLE RYEH\r\n\t\t(0xB85D <= code && code <= 0xB877) || // Lo [27] HANGUL SYLLABLE ROG..HANGUL SYLLABLE ROH\r\n\t\t(0xB879 <= code && code <= 0xB893) || // Lo [27] HANGUL SYLLABLE RWAG..HANGUL SYLLABLE RWAH\r\n\t\t(0xB895 <= code && code <= 0xB8AF) || // Lo [27] HANGUL SYLLABLE RWAEG..HANGUL SYLLABLE RWAEH\r\n\t\t(0xB8B1 <= code && code <= 0xB8CB) || // Lo [27] HANGUL SYLLABLE ROEG..HANGUL SYLLABLE ROEH\r\n\t\t(0xB8CD <= code && code <= 0xB8E7) || // Lo [27] HANGUL SYLLABLE RYOG..HANGUL SYLLABLE RYOH\r\n\t\t(0xB8E9 <= code && code <= 0xB903) || // Lo [27] HANGUL SYLLABLE RUG..HANGUL SYLLABLE RUH\r\n\t\t(0xB905 <= code && code <= 0xB91F) || // Lo [27] HANGUL SYLLABLE RWEOG..HANGUL SYLLABLE RWEOH\r\n\t\t(0xB921 <= code && code <= 0xB93B) || // Lo [27] HANGUL SYLLABLE RWEG..HANGUL SYLLABLE RWEH\r\n\t\t(0xB93D <= code && code <= 0xB957) || // Lo [27] HANGUL SYLLABLE RWIG..HANGUL SYLLABLE RWIH\r\n\t\t(0xB959 <= code && code <= 0xB973) || // Lo [27] HANGUL SYLLABLE RYUG..HANGUL SYLLABLE RYUH\r\n\t\t(0xB975 <= code && code <= 0xB98F) || // Lo [27] HANGUL SYLLABLE REUG..HANGUL SYLLABLE REUH\r\n\t\t(0xB991 <= code && code <= 0xB9AB) || // Lo [27] HANGUL SYLLABLE RYIG..HANGUL SYLLABLE RYIH\r\n\t\t(0xB9AD <= code && code <= 0xB9C7) || // Lo [27] HANGUL SYLLABLE RIG..HANGUL SYLLABLE RIH\r\n\t\t(0xB9C9 <= code && code <= 0xB9E3) || // Lo [27] HANGUL SYLLABLE MAG..HANGUL SYLLABLE MAH\r\n\t\t(0xB9E5 <= code && code <= 0xB9FF) || // Lo [27] HANGUL SYLLABLE MAEG..HANGUL SYLLABLE MAEH\r\n\t\t(0xBA01 <= code && code <= 0xBA1B) || // Lo [27] HANGUL SYLLABLE MYAG..HANGUL SYLLABLE MYAH\r\n\t\t(0xBA1D <= code && code <= 0xBA37) || // Lo [27] HANGUL SYLLABLE MYAEG..HANGUL SYLLABLE MYAEH\r\n\t\t(0xBA39 <= code && code <= 0xBA53) || // Lo [27] HANGUL SYLLABLE MEOG..HANGUL SYLLABLE MEOH\r\n\t\t(0xBA55 <= code && code <= 0xBA6F) || // Lo [27] HANGUL SYLLABLE MEG..HANGUL SYLLABLE MEH\r\n\t\t(0xBA71 <= code && code <= 0xBA8B) || // Lo [27] HANGUL SYLLABLE MYEOG..HANGUL SYLLABLE MYEOH\r\n\t\t(0xBA8D <= code && code <= 0xBAA7) || // Lo [27] HANGUL SYLLABLE MYEG..HANGUL SYLLABLE MYEH\r\n\t\t(0xBAA9 <= code && code <= 0xBAC3) || // Lo [27] HANGUL SYLLABLE MOG..HANGUL SYLLABLE MOH\r\n\t\t(0xBAC5 <= code && code <= 0xBADF) || // Lo [27] HANGUL SYLLABLE MWAG..HANGUL SYLLABLE MWAH\r\n\t\t(0xBAE1 <= code && code <= 0xBAFB) || // Lo [27] HANGUL SYLLABLE MWAEG..HANGUL SYLLABLE MWAEH\r\n\t\t(0xBAFD <= code && code <= 0xBB17) || // Lo [27] HANGUL SYLLABLE MOEG..HANGUL SYLLABLE MOEH\r\n\t\t(0xBB19 <= code && code <= 0xBB33) || // Lo [27] HANGUL SYLLABLE MYOG..HANGUL SYLLABLE MYOH\r\n\t\t(0xBB35 <= code && code <= 0xBB4F) || // Lo [27] HANGUL SYLLABLE MUG..HANGUL SYLLABLE MUH\r\n\t\t(0xBB51 <= code && code <= 0xBB6B) || // Lo [27] HANGUL SYLLABLE MWEOG..HANGUL SYLLABLE MWEOH\r\n\t\t(0xBB6D <= code && code <= 0xBB87) || // Lo [27] HANGUL SYLLABLE MWEG..HANGUL SYLLABLE MWEH\r\n\t\t(0xBB89 <= code && code <= 0xBBA3) || // Lo [27] HANGUL SYLLABLE MWIG..HANGUL SYLLABLE MWIH\r\n\t\t(0xBBA5 <= code && code <= 0xBBBF) || // Lo [27] HANGUL SYLLABLE MYUG..HANGUL SYLLABLE MYUH\r\n\t\t(0xBBC1 <= code && code <= 0xBBDB) || // Lo [27] HANGUL SYLLABLE MEUG..HANGUL SYLLABLE MEUH\r\n\t\t(0xBBDD <= code && code <= 0xBBF7) || // Lo [27] HANGUL SYLLABLE MYIG..HANGUL SYLLABLE MYIH\r\n\t\t(0xBBF9 <= code && code <= 0xBC13) || // Lo [27] HANGUL SYLLABLE MIG..HANGUL SYLLABLE MIH\r\n\t\t(0xBC15 <= code && code <= 0xBC2F) || // Lo [27] HANGUL SYLLABLE BAG..HANGUL SYLLABLE BAH\r\n\t\t(0xBC31 <= code && code <= 0xBC4B) || // Lo [27] HANGUL SYLLABLE BAEG..HANGUL SYLLABLE BAEH\r\n\t\t(0xBC4D <= code && code <= 0xBC67) || // Lo [27] HANGUL SYLLABLE BYAG..HANGUL SYLLABLE BYAH\r\n\t\t(0xBC69 <= code && code <= 0xBC83) || // Lo [27] HANGUL SYLLABLE BYAEG..HANGUL SYLLABLE BYAEH\r\n\t\t(0xBC85 <= code && code <= 0xBC9F) || // Lo [27] HANGUL SYLLABLE BEOG..HANGUL SYLLABLE BEOH\r\n\t\t(0xBCA1 <= code && code <= 0xBCBB) || // Lo [27] HANGUL SYLLABLE BEG..HANGUL SYLLABLE BEH\r\n\t\t(0xBCBD <= code && code <= 0xBCD7) || // Lo [27] HANGUL SYLLABLE BYEOG..HANGUL SYLLABLE BYEOH\r\n\t\t(0xBCD9 <= code && code <= 0xBCF3) || // Lo [27] HANGUL SYLLABLE BYEG..HANGUL SYLLABLE BYEH\r\n\t\t(0xBCF5 <= code && code <= 0xBD0F) || // Lo [27] HANGUL SYLLABLE BOG..HANGUL SYLLABLE BOH\r\n\t\t(0xBD11 <= code && code <= 0xBD2B) || // Lo [27] HANGUL SYLLABLE BWAG..HANGUL SYLLABLE BWAH\r\n\t\t(0xBD2D <= code && code <= 0xBD47) || // Lo [27] HANGUL SYLLABLE BWAEG..HANGUL SYLLABLE BWAEH\r\n\t\t(0xBD49 <= code && code <= 0xBD63) || // Lo [27] HANGUL SYLLABLE BOEG..HANGUL SYLLABLE BOEH\r\n\t\t(0xBD65 <= code && code <= 0xBD7F) || // Lo [27] HANGUL SYLLABLE BYOG..HANGUL SYLLABLE BYOH\r\n\t\t(0xBD81 <= code && code <= 0xBD9B) || // Lo [27] HANGUL SYLLABLE BUG..HANGUL SYLLABLE BUH\r\n\t\t(0xBD9D <= code && code <= 0xBDB7) || // Lo [27] HANGUL SYLLABLE BWEOG..HANGUL SYLLABLE BWEOH\r\n\t\t(0xBDB9 <= code && code <= 0xBDD3) || // Lo [27] HANGUL SYLLABLE BWEG..HANGUL SYLLABLE BWEH\r\n\t\t(0xBDD5 <= code && code <= 0xBDEF) || // Lo [27] HANGUL SYLLABLE BWIG..HANGUL SYLLABLE BWIH\r\n\t\t(0xBDF1 <= code && code <= 0xBE0B) || // Lo [27] HANGUL SYLLABLE BYUG..HANGUL SYLLABLE BYUH\r\n\t\t(0xBE0D <= code && code <= 0xBE27) || // Lo [27] HANGUL SYLLABLE BEUG..HANGUL SYLLABLE BEUH\r\n\t\t(0xBE29 <= code && code <= 0xBE43) || // Lo [27] HANGUL SYLLABLE BYIG..HANGUL SYLLABLE BYIH\r\n\t\t(0xBE45 <= code && code <= 0xBE5F) || // Lo [27] HANGUL SYLLABLE BIG..HANGUL SYLLABLE BIH\r\n\t\t(0xBE61 <= code && code <= 0xBE7B) || // Lo [27] HANGUL SYLLABLE BBAG..HANGUL SYLLABLE BBAH\r\n\t\t(0xBE7D <= code && code <= 0xBE97) || // Lo [27] HANGUL SYLLABLE BBAEG..HANGUL SYLLABLE BBAEH\r\n\t\t(0xBE99 <= code && code <= 0xBEB3) || // Lo [27] HANGUL SYLLABLE BBYAG..HANGUL SYLLABLE BBYAH\r\n\t\t(0xBEB5 <= code && code <= 0xBECF) || // Lo [27] HANGUL SYLLABLE BBYAEG..HANGUL SYLLABLE BBYAEH\r\n\t\t(0xBED1 <= code && code <= 0xBEEB) || // Lo [27] HANGUL SYLLABLE BBEOG..HANGUL SYLLABLE BBEOH\r\n\t\t(0xBEED <= code && code <= 0xBF07) || // Lo [27] HANGUL SYLLABLE BBEG..HANGUL SYLLABLE BBEH\r\n\t\t(0xBF09 <= code && code <= 0xBF23) || // Lo [27] HANGUL SYLLABLE BBYEOG..HANGUL SYLLABLE BBYEOH\r\n\t\t(0xBF25 <= code && code <= 0xBF3F) || // Lo [27] HANGUL SYLLABLE BBYEG..HANGUL SYLLABLE BBYEH\r\n\t\t(0xBF41 <= code && code <= 0xBF5B) || // Lo [27] HANGUL SYLLABLE BBOG..HANGUL SYLLABLE BBOH\r\n\t\t(0xBF5D <= code && code <= 0xBF77) || // Lo [27] HANGUL SYLLABLE BBWAG..HANGUL SYLLABLE BBWAH\r\n\t\t(0xBF79 <= code && code <= 0xBF93) || // Lo [27] HANGUL SYLLABLE BBWAEG..HANGUL SYLLABLE BBWAEH\r\n\t\t(0xBF95 <= code && code <= 0xBFAF) || // Lo [27] HANGUL SYLLABLE BBOEG..HANGUL SYLLABLE BBOEH\r\n\t\t(0xBFB1 <= code && code <= 0xBFCB) || // Lo [27] HANGUL SYLLABLE BBYOG..HANGUL SYLLABLE BBYOH\r\n\t\t(0xBFCD <= code && code <= 0xBFE7) || // Lo [27] HANGUL SYLLABLE BBUG..HANGUL SYLLABLE BBUH\r\n\t\t(0xBFE9 <= code && code <= 0xC003) || // Lo [27] HANGUL SYLLABLE BBWEOG..HANGUL SYLLABLE BBWEOH\r\n\t\t(0xC005 <= code && code <= 0xC01F) || // Lo [27] HANGUL SYLLABLE BBWEG..HANGUL SYLLABLE BBWEH\r\n\t\t(0xC021 <= code && code <= 0xC03B) || // Lo [27] HANGUL SYLLABLE BBWIG..HANGUL SYLLABLE BBWIH\r\n\t\t(0xC03D <= code && code <= 0xC057) || // Lo [27] HANGUL SYLLABLE BBYUG..HANGUL SYLLABLE BBYUH\r\n\t\t(0xC059 <= code && code <= 0xC073) || // Lo [27] HANGUL SYLLABLE BBEUG..HANGUL SYLLABLE BBEUH\r\n\t\t(0xC075 <= code && code <= 0xC08F) || // Lo [27] HANGUL SYLLABLE BBYIG..HANGUL SYLLABLE BBYIH\r\n\t\t(0xC091 <= code && code <= 0xC0AB) || // Lo [27] HANGUL SYLLABLE BBIG..HANGUL SYLLABLE BBIH\r\n\t\t(0xC0AD <= code && code <= 0xC0C7) || // Lo [27] HANGUL SYLLABLE SAG..HANGUL SYLLABLE SAH\r\n\t\t(0xC0C9 <= code && code <= 0xC0E3) || // Lo [27] HANGUL SYLLABLE SAEG..HANGUL SYLLABLE SAEH\r\n\t\t(0xC0E5 <= code && code <= 0xC0FF) || // Lo [27] HANGUL SYLLABLE SYAG..HANGUL SYLLABLE SYAH\r\n\t\t(0xC101 <= code && code <= 0xC11B) || // Lo [27] HANGUL SYLLABLE SYAEG..HANGUL SYLLABLE SYAEH\r\n\t\t(0xC11D <= code && code <= 0xC137) || // Lo [27] HANGUL SYLLABLE SEOG..HANGUL SYLLABLE SEOH\r\n\t\t(0xC139 <= code && code <= 0xC153) || // Lo [27] HANGUL SYLLABLE SEG..HANGUL SYLLABLE SEH\r\n\t\t(0xC155 <= code && code <= 0xC16F) || // Lo [27] HANGUL SYLLABLE SYEOG..HANGUL SYLLABLE SYEOH\r\n\t\t(0xC171 <= code && code <= 0xC18B) || // Lo [27] HANGUL SYLLABLE SYEG..HANGUL SYLLABLE SYEH\r\n\t\t(0xC18D <= code && code <= 0xC1A7) || // Lo [27] HANGUL SYLLABLE SOG..HANGUL SYLLABLE SOH\r\n\t\t(0xC1A9 <= code && code <= 0xC1C3) || // Lo [27] HANGUL SYLLABLE SWAG..HANGUL SYLLABLE SWAH\r\n\t\t(0xC1C5 <= code && code <= 0xC1DF) || // Lo [27] HANGUL SYLLABLE SWAEG..HANGUL SYLLABLE SWAEH\r\n\t\t(0xC1E1 <= code && code <= 0xC1FB) || // Lo [27] HANGUL SYLLABLE SOEG..HANGUL SYLLABLE SOEH\r\n\t\t(0xC1FD <= code && code <= 0xC217) || // Lo [27] HANGUL SYLLABLE SYOG..HANGUL SYLLABLE SYOH\r\n\t\t(0xC219 <= code && code <= 0xC233) || // Lo [27] HANGUL SYLLABLE SUG..HANGUL SYLLABLE SUH\r\n\t\t(0xC235 <= code && code <= 0xC24F) || // Lo [27] HANGUL SYLLABLE SWEOG..HANGUL SYLLABLE SWEOH\r\n\t\t(0xC251 <= code && code <= 0xC26B) || // Lo [27] HANGUL SYLLABLE SWEG..HANGUL SYLLABLE SWEH\r\n\t\t(0xC26D <= code && code <= 0xC287) || // Lo [27] HANGUL SYLLABLE SWIG..HANGUL SYLLABLE SWIH\r\n\t\t(0xC289 <= code && code <= 0xC2A3) || // Lo [27] HANGUL SYLLABLE SYUG..HANGUL SYLLABLE SYUH\r\n\t\t(0xC2A5 <= code && code <= 0xC2BF) || // Lo [27] HANGUL SYLLABLE SEUG..HANGUL SYLLABLE SEUH\r\n\t\t(0xC2C1 <= code && code <= 0xC2DB) || // Lo [27] HANGUL SYLLABLE SYIG..HANGUL SYLLABLE SYIH\r\n\t\t(0xC2DD <= code && code <= 0xC2F7) || // Lo [27] HANGUL SYLLABLE SIG..HANGUL SYLLABLE SIH\r\n\t\t(0xC2F9 <= code && code <= 0xC313) || // Lo [27] HANGUL SYLLABLE SSAG..HANGUL SYLLABLE SSAH\r\n\t\t(0xC315 <= code && code <= 0xC32F) || // Lo [27] HANGUL SYLLABLE SSAEG..HANGUL SYLLABLE SSAEH\r\n\t\t(0xC331 <= code && code <= 0xC34B) || // Lo [27] HANGUL SYLLABLE SSYAG..HANGUL SYLLABLE SSYAH\r\n\t\t(0xC34D <= code && code <= 0xC367) || // Lo [27] HANGUL SYLLABLE SSYAEG..HANGUL SYLLABLE SSYAEH\r\n\t\t(0xC369 <= code && code <= 0xC383) || // Lo [27] HANGUL SYLLABLE SSEOG..HANGUL SYLLABLE SSEOH\r\n\t\t(0xC385 <= code && code <= 0xC39F) || // Lo [27] HANGUL SYLLABLE SSEG..HANGUL SYLLABLE SSEH\r\n\t\t(0xC3A1 <= code && code <= 0xC3BB) || // Lo [27] HANGUL SYLLABLE SSYEOG..HANGUL SYLLABLE SSYEOH\r\n\t\t(0xC3BD <= code && code <= 0xC3D7) || // Lo [27] HANGUL SYLLABLE SSYEG..HANGUL SYLLABLE SSYEH\r\n\t\t(0xC3D9 <= code && code <= 0xC3F3) || // Lo [27] HANGUL SYLLABLE SSOG..HANGUL SYLLABLE SSOH\r\n\t\t(0xC3F5 <= code && code <= 0xC40F) || // Lo [27] HANGUL SYLLABLE SSWAG..HANGUL SYLLABLE SSWAH\r\n\t\t(0xC411 <= code && code <= 0xC42B) || // Lo [27] HANGUL SYLLABLE SSWAEG..HANGUL SYLLABLE SSWAEH\r\n\t\t(0xC42D <= code && code <= 0xC447) || // Lo [27] HANGUL SYLLABLE SSOEG..HANGUL SYLLABLE SSOEH\r\n\t\t(0xC449 <= code && code <= 0xC463) || // Lo [27] HANGUL SYLLABLE SSYOG..HANGUL SYLLABLE SSYOH\r\n\t\t(0xC465 <= code && code <= 0xC47F) || // Lo [27] HANGUL SYLLABLE SSUG..HANGUL SYLLABLE SSUH\r\n\t\t(0xC481 <= code && code <= 0xC49B) || // Lo [27] HANGUL SYLLABLE SSWEOG..HANGUL SYLLABLE SSWEOH\r\n\t\t(0xC49D <= code && code <= 0xC4B7) || // Lo [27] HANGUL SYLLABLE SSWEG..HANGUL SYLLABLE SSWEH\r\n\t\t(0xC4B9 <= code && code <= 0xC4D3) || // Lo [27] HANGUL SYLLABLE SSWIG..HANGUL SYLLABLE SSWIH\r\n\t\t(0xC4D5 <= code && code <= 0xC4EF) || // Lo [27] HANGUL SYLLABLE SSYUG..HANGUL SYLLABLE SSYUH\r\n\t\t(0xC4F1 <= code && code <= 0xC50B) || // Lo [27] HANGUL SYLLABLE SSEUG..HANGUL SYLLABLE SSEUH\r\n\t\t(0xC50D <= code && code <= 0xC527) || // Lo [27] HANGUL SYLLABLE SSYIG..HANGUL SYLLABLE SSYIH\r\n\t\t(0xC529 <= code && code <= 0xC543) || // Lo [27] HANGUL SYLLABLE SSIG..HANGUL SYLLABLE SSIH\r\n\t\t(0xC545 <= code && code <= 0xC55F) || // Lo [27] HANGUL SYLLABLE AG..HANGUL SYLLABLE AH\r\n\t\t(0xC561 <= code && code <= 0xC57B) || // Lo [27] HANGUL SYLLABLE AEG..HANGUL SYLLABLE AEH\r\n\t\t(0xC57D <= code && code <= 0xC597) || // Lo [27] HANGUL SYLLABLE YAG..HANGUL SYLLABLE YAH\r\n\t\t(0xC599 <= code && code <= 0xC5B3) || // Lo [27] HANGUL SYLLABLE YAEG..HANGUL SYLLABLE YAEH\r\n\t\t(0xC5B5 <= code && code <= 0xC5CF) || // Lo [27] HANGUL SYLLABLE EOG..HANGUL SYLLABLE EOH\r\n\t\t(0xC5D1 <= code && code <= 0xC5EB) || // Lo [27] HANGUL SYLLABLE EG..HANGUL SYLLABLE EH\r\n\t\t(0xC5ED <= code && code <= 0xC607) || // Lo [27] HANGUL SYLLABLE YEOG..HANGUL SYLLABLE YEOH\r\n\t\t(0xC609 <= code && code <= 0xC623) || // Lo [27] HANGUL SYLLABLE YEG..HANGUL SYLLABLE YEH\r\n\t\t(0xC625 <= code && code <= 0xC63F) || // Lo [27] HANGUL SYLLABLE OG..HANGUL SYLLABLE OH\r\n\t\t(0xC641 <= code && code <= 0xC65B) || // Lo [27] HANGUL SYLLABLE WAG..HANGUL SYLLABLE WAH\r\n\t\t(0xC65D <= code && code <= 0xC677) || // Lo [27] HANGUL SYLLABLE WAEG..HANGUL SYLLABLE WAEH\r\n\t\t(0xC679 <= code && code <= 0xC693) || // Lo [27] HANGUL SYLLABLE OEG..HANGUL SYLLABLE OEH\r\n\t\t(0xC695 <= code && code <= 0xC6AF) || // Lo [27] HANGUL SYLLABLE YOG..HANGUL SYLLABLE YOH\r\n\t\t(0xC6B1 <= code && code <= 0xC6CB) || // Lo [27] HANGUL SYLLABLE UG..HANGUL SYLLABLE UH\r\n\t\t(0xC6CD <= code && code <= 0xC6E7) || // Lo [27] HANGUL SYLLABLE WEOG..HANGUL SYLLABLE WEOH\r\n\t\t(0xC6E9 <= code && code <= 0xC703) || // Lo [27] HANGUL SYLLABLE WEG..HANGUL SYLLABLE WEH\r\n\t\t(0xC705 <= code && code <= 0xC71F) || // Lo [27] HANGUL SYLLABLE WIG..HANGUL SYLLABLE WIH\r\n\t\t(0xC721 <= code && code <= 0xC73B) || // Lo [27] HANGUL SYLLABLE YUG..HANGUL SYLLABLE YUH\r\n\t\t(0xC73D <= code && code <= 0xC757) || // Lo [27] HANGUL SYLLABLE EUG..HANGUL SYLLABLE EUH\r\n\t\t(0xC759 <= code && code <= 0xC773) || // Lo [27] HANGUL SYLLABLE YIG..HANGUL SYLLABLE YIH\r\n\t\t(0xC775 <= code && code <= 0xC78F) || // Lo [27] HANGUL SYLLABLE IG..HANGUL SYLLABLE IH\r\n\t\t(0xC791 <= code && code <= 0xC7AB) || // Lo [27] HANGUL SYLLABLE JAG..HANGUL SYLLABLE JAH\r\n\t\t(0xC7AD <= code && code <= 0xC7C7) || // Lo [27] HANGUL SYLLABLE JAEG..HANGUL SYLLABLE JAEH\r\n\t\t(0xC7C9 <= code && code <= 0xC7E3) || // Lo [27] HANGUL SYLLABLE JYAG..HANGUL SYLLABLE JYAH\r\n\t\t(0xC7E5 <= code && code <= 0xC7FF) || // Lo [27] HANGUL SYLLABLE JYAEG..HANGUL SYLLABLE JYAEH\r\n\t\t(0xC801 <= code && code <= 0xC81B) || // Lo [27] HANGUL SYLLABLE JEOG..HANGUL SYLLABLE JEOH\r\n\t\t(0xC81D <= code && code <= 0xC837) || // Lo [27] HANGUL SYLLABLE JEG..HANGUL SYLLABLE JEH\r\n\t\t(0xC839 <= code && code <= 0xC853) || // Lo [27] HANGUL SYLLABLE JYEOG..HANGUL SYLLABLE JYEOH\r\n\t\t(0xC855 <= code && code <= 0xC86F) || // Lo [27] HANGUL SYLLABLE JYEG..HANGUL SYLLABLE JYEH\r\n\t\t(0xC871 <= code && code <= 0xC88B) || // Lo [27] HANGUL SYLLABLE JOG..HANGUL SYLLABLE JOH\r\n\t\t(0xC88D <= code && code <= 0xC8A7) || // Lo [27] HANGUL SYLLABLE JWAG..HANGUL SYLLABLE JWAH\r\n\t\t(0xC8A9 <= code && code <= 0xC8C3) || // Lo [27] HANGUL SYLLABLE JWAEG..HANGUL SYLLABLE JWAEH\r\n\t\t(0xC8C5 <= code && code <= 0xC8DF) || // Lo [27] HANGUL SYLLABLE JOEG..HANGUL SYLLABLE JOEH\r\n\t\t(0xC8E1 <= code && code <= 0xC8FB) || // Lo [27] HANGUL SYLLABLE JYOG..HANGUL SYLLABLE JYOH\r\n\t\t(0xC8FD <= code && code <= 0xC917) || // Lo [27] HANGUL SYLLABLE JUG..HANGUL SYLLABLE JUH\r\n\t\t(0xC919 <= code && code <= 0xC933) || // Lo [27] HANGUL SYLLABLE JWEOG..HANGUL SYLLABLE JWEOH\r\n\t\t(0xC935 <= code && code <= 0xC94F) || // Lo [27] HANGUL SYLLABLE JWEG..HANGUL SYLLABLE JWEH\r\n\t\t(0xC951 <= code && code <= 0xC96B) || // Lo [27] HANGUL SYLLABLE JWIG..HANGUL SYLLABLE JWIH\r\n\t\t(0xC96D <= code && code <= 0xC987) || // Lo [27] HANGUL SYLLABLE JYUG..HANGUL SYLLABLE JYUH\r\n\t\t(0xC989 <= code && code <= 0xC9A3) || // Lo [27] HANGUL SYLLABLE JEUG..HANGUL SYLLABLE JEUH\r\n\t\t(0xC9A5 <= code && code <= 0xC9BF) || // Lo [27] HANGUL SYLLABLE JYIG..HANGUL SYLLABLE JYIH\r\n\t\t(0xC9C1 <= code && code <= 0xC9DB) || // Lo [27] HANGUL SYLLABLE JIG..HANGUL SYLLABLE JIH\r\n\t\t(0xC9DD <= code && code <= 0xC9F7) || // Lo [27] HANGUL SYLLABLE JJAG..HANGUL SYLLABLE JJAH\r\n\t\t(0xC9F9 <= code && code <= 0xCA13) || // Lo [27] HANGUL SYLLABLE JJAEG..HANGUL SYLLABLE JJAEH\r\n\t\t(0xCA15 <= code && code <= 0xCA2F) || // Lo [27] HANGUL SYLLABLE JJYAG..HANGUL SYLLABLE JJYAH\r\n\t\t(0xCA31 <= code && code <= 0xCA4B) || // Lo [27] HANGUL SYLLABLE JJYAEG..HANGUL SYLLABLE JJYAEH\r\n\t\t(0xCA4D <= code && code <= 0xCA67) || // Lo [27] HANGUL SYLLABLE JJEOG..HANGUL SYLLABLE JJEOH\r\n\t\t(0xCA69 <= code && code <= 0xCA83) || // Lo [27] HANGUL SYLLABLE JJEG..HANGUL SYLLABLE JJEH\r\n\t\t(0xCA85 <= code && code <= 0xCA9F) || // Lo [27] HANGUL SYLLABLE JJYEOG..HANGUL SYLLABLE JJYEOH\r\n\t\t(0xCAA1 <= code && code <= 0xCABB) || // Lo [27] HANGUL SYLLABLE JJYEG..HANGUL SYLLABLE JJYEH\r\n\t\t(0xCABD <= code && code <= 0xCAD7) || // Lo [27] HANGUL SYLLABLE JJOG..HANGUL SYLLABLE JJOH\r\n\t\t(0xCAD9 <= code && code <= 0xCAF3) || // Lo [27] HANGUL SYLLABLE JJWAG..HANGUL SYLLABLE JJWAH\r\n\t\t(0xCAF5 <= code && code <= 0xCB0F) || // Lo [27] HANGUL SYLLABLE JJWAEG..HANGUL SYLLABLE JJWAEH\r\n\t\t(0xCB11 <= code && code <= 0xCB2B) || // Lo [27] HANGUL SYLLABLE JJOEG..HANGUL SYLLABLE JJOEH\r\n\t\t(0xCB2D <= code && code <= 0xCB47) || // Lo [27] HANGUL SYLLABLE JJYOG..HANGUL SYLLABLE JJYOH\r\n\t\t(0xCB49 <= code && code <= 0xCB63) || // Lo [27] HANGUL SYLLABLE JJUG..HANGUL SYLLABLE JJUH\r\n\t\t(0xCB65 <= code && code <= 0xCB7F) || // Lo [27] HANGUL SYLLABLE JJWEOG..HANGUL SYLLABLE JJWEOH\r\n\t\t(0xCB81 <= code && code <= 0xCB9B) || // Lo [27] HANGUL SYLLABLE JJWEG..HANGUL SYLLABLE JJWEH\r\n\t\t(0xCB9D <= code && code <= 0xCBB7) || // Lo [27] HANGUL SYLLABLE JJWIG..HANGUL SYLLABLE JJWIH\r\n\t\t(0xCBB9 <= code && code <= 0xCBD3) || // Lo [27] HANGUL SYLLABLE JJYUG..HANGUL SYLLABLE JJYUH\r\n\t\t(0xCBD5 <= code && code <= 0xCBEF) || // Lo [27] HANGUL SYLLABLE JJEUG..HANGUL SYLLABLE JJEUH\r\n\t\t(0xCBF1 <= code && code <= 0xCC0B) || // Lo [27] HANGUL SYLLABLE JJYIG..HANGUL SYLLABLE JJYIH\r\n\t\t(0xCC0D <= code && code <= 0xCC27) || // Lo [27] HANGUL SYLLABLE JJIG..HANGUL SYLLABLE JJIH\r\n\t\t(0xCC29 <= code && code <= 0xCC43) || // Lo [27] HANGUL SYLLABLE CAG..HANGUL SYLLABLE CAH\r\n\t\t(0xCC45 <= code && code <= 0xCC5F) || // Lo [27] HANGUL SYLLABLE CAEG..HANGUL SYLLABLE CAEH\r\n\t\t(0xCC61 <= code && code <= 0xCC7B) || // Lo [27] HANGUL SYLLABLE CYAG..HANGUL SYLLABLE CYAH\r\n\t\t(0xCC7D <= code && code <= 0xCC97) || // Lo [27] HANGUL SYLLABLE CYAEG..HANGUL SYLLABLE CYAEH\r\n\t\t(0xCC99 <= code && code <= 0xCCB3) || // Lo [27] HANGUL SYLLABLE CEOG..HANGUL SYLLABLE CEOH\r\n\t\t(0xCCB5 <= code && code <= 0xCCCF) || // Lo [27] HANGUL SYLLABLE CEG..HANGUL SYLLABLE CEH\r\n\t\t(0xCCD1 <= code && code <= 0xCCEB) || // Lo [27] HANGUL SYLLABLE CYEOG..HANGUL SYLLABLE CYEOH\r\n\t\t(0xCCED <= code && code <= 0xCD07) || // Lo [27] HANGUL SYLLABLE CYEG..HANGUL SYLLABLE CYEH\r\n\t\t(0xCD09 <= code && code <= 0xCD23) || // Lo [27] HANGUL SYLLABLE COG..HANGUL SYLLABLE COH\r\n\t\t(0xCD25 <= code && code <= 0xCD3F) || // Lo [27] HANGUL SYLLABLE CWAG..HANGUL SYLLABLE CWAH\r\n\t\t(0xCD41 <= code && code <= 0xCD5B) || // Lo [27] HANGUL SYLLABLE CWAEG..HANGUL SYLLABLE CWAEH\r\n\t\t(0xCD5D <= code && code <= 0xCD77) || // Lo [27] HANGUL SYLLABLE COEG..HANGUL SYLLABLE COEH\r\n\t\t(0xCD79 <= code && code <= 0xCD93) || // Lo [27] HANGUL SYLLABLE CYOG..HANGUL SYLLABLE CYOH\r\n\t\t(0xCD95 <= code && code <= 0xCDAF) || // Lo [27] HANGUL SYLLABLE CUG..HANGUL SYLLABLE CUH\r\n\t\t(0xCDB1 <= code && code <= 0xCDCB) || // Lo [27] HANGUL SYLLABLE CWEOG..HANGUL SYLLABLE CWEOH\r\n\t\t(0xCDCD <= code && code <= 0xCDE7) || // Lo [27] HANGUL SYLLABLE CWEG..HANGUL SYLLABLE CWEH\r\n\t\t(0xCDE9 <= code && code <= 0xCE03) || // Lo [27] HANGUL SYLLABLE CWIG..HANGUL SYLLABLE CWIH\r\n\t\t(0xCE05 <= code && code <= 0xCE1F) || // Lo [27] HANGUL SYLLABLE CYUG..HANGUL SYLLABLE CYUH\r\n\t\t(0xCE21 <= code && code <= 0xCE3B) || // Lo [27] HANGUL SYLLABLE CEUG..HANGUL SYLLABLE CEUH\r\n\t\t(0xCE3D <= code && code <= 0xCE57) || // Lo [27] HANGUL SYLLABLE CYIG..HANGUL SYLLABLE CYIH\r\n\t\t(0xCE59 <= code && code <= 0xCE73) || // Lo [27] HANGUL SYLLABLE CIG..HANGUL SYLLABLE CIH\r\n\t\t(0xCE75 <= code && code <= 0xCE8F) || // Lo [27] HANGUL SYLLABLE KAG..HANGUL SYLLABLE KAH\r\n\t\t(0xCE91 <= code && code <= 0xCEAB) || // Lo [27] HANGUL SYLLABLE KAEG..HANGUL SYLLABLE KAEH\r\n\t\t(0xCEAD <= code && code <= 0xCEC7) || // Lo [27] HANGUL SYLLABLE KYAG..HANGUL SYLLABLE KYAH\r\n\t\t(0xCEC9 <= code && code <= 0xCEE3) || // Lo [27] HANGUL SYLLABLE KYAEG..HANGUL SYLLABLE KYAEH\r\n\t\t(0xCEE5 <= code && code <= 0xCEFF) || // Lo [27] HANGUL SYLLABLE KEOG..HANGUL SYLLABLE KEOH\r\n\t\t(0xCF01 <= code && code <= 0xCF1B) || // Lo [27] HANGUL SYLLABLE KEG..HANGUL SYLLABLE KEH\r\n\t\t(0xCF1D <= code && code <= 0xCF37) || // Lo [27] HANGUL SYLLABLE KYEOG..HANGUL SYLLABLE KYEOH\r\n\t\t(0xCF39 <= code && code <= 0xCF53) || // Lo [27] HANGUL SYLLABLE KYEG..HANGUL SYLLABLE KYEH\r\n\t\t(0xCF55 <= code && code <= 0xCF6F) || // Lo [27] HANGUL SYLLABLE KOG..HANGUL SYLLABLE KOH\r\n\t\t(0xCF71 <= code && code <= 0xCF8B) || // Lo [27] HANGUL SYLLABLE KWAG..HANGUL SYLLABLE KWAH\r\n\t\t(0xCF8D <= code && code <= 0xCFA7) || // Lo [27] HANGUL SYLLABLE KWAEG..HANGUL SYLLABLE KWAEH\r\n\t\t(0xCFA9 <= code && code <= 0xCFC3) || // Lo [27] HANGUL SYLLABLE KOEG..HANGUL SYLLABLE KOEH\r\n\t\t(0xCFC5 <= code && code <= 0xCFDF) || // Lo [27] HANGUL SYLLABLE KYOG..HANGUL SYLLABLE KYOH\r\n\t\t(0xCFE1 <= code && code <= 0xCFFB) || // Lo [27] HANGUL SYLLABLE KUG..HANGUL SYLLABLE KUH\r\n\t\t(0xCFFD <= code && code <= 0xD017) || // Lo [27] HANGUL SYLLABLE KWEOG..HANGUL SYLLABLE KWEOH\r\n\t\t(0xD019 <= code && code <= 0xD033) || // Lo [27] HANGUL SYLLABLE KWEG..HANGUL SYLLABLE KWEH\r\n\t\t(0xD035 <= code && code <= 0xD04F) || // Lo [27] HANGUL SYLLABLE KWIG..HANGUL SYLLABLE KWIH\r\n\t\t(0xD051 <= code && code <= 0xD06B) || // Lo [27] HANGUL SYLLABLE KYUG..HANGUL SYLLABLE KYUH\r\n\t\t(0xD06D <= code && code <= 0xD087) || // Lo [27] HANGUL SYLLABLE KEUG..HANGUL SYLLABLE KEUH\r\n\t\t(0xD089 <= code && code <= 0xD0A3) || // Lo [27] HANGUL SYLLABLE KYIG..HANGUL SYLLABLE KYIH\r\n\t\t(0xD0A5 <= code && code <= 0xD0BF) || // Lo [27] HANGUL SYLLABLE KIG..HANGUL SYLLABLE KIH\r\n\t\t(0xD0C1 <= code && code <= 0xD0DB) || // Lo [27] HANGUL SYLLABLE TAG..HANGUL SYLLABLE TAH\r\n\t\t(0xD0DD <= code && code <= 0xD0F7) || // Lo [27] HANGUL SYLLABLE TAEG..HANGUL SYLLABLE TAEH\r\n\t\t(0xD0F9 <= code && code <= 0xD113) || // Lo [27] HANGUL SYLLABLE TYAG..HANGUL SYLLABLE TYAH\r\n\t\t(0xD115 <= code && code <= 0xD12F) || // Lo [27] HANGUL SYLLABLE TYAEG..HANGUL SYLLABLE TYAEH\r\n\t\t(0xD131 <= code && code <= 0xD14B) || // Lo [27] HANGUL SYLLABLE TEOG..HANGUL SYLLABLE TEOH\r\n\t\t(0xD14D <= code && code <= 0xD167) || // Lo [27] HANGUL SYLLABLE TEG..HANGUL SYLLABLE TEH\r\n\t\t(0xD169 <= code && code <= 0xD183) || // Lo [27] HANGUL SYLLABLE TYEOG..HANGUL SYLLABLE TYEOH\r\n\t\t(0xD185 <= code && code <= 0xD19F) || // Lo [27] HANGUL SYLLABLE TYEG..HANGUL SYLLABLE TYEH\r\n\t\t(0xD1A1 <= code && code <= 0xD1BB) || // Lo [27] HANGUL SYLLABLE TOG..HANGUL SYLLABLE TOH\r\n\t\t(0xD1BD <= code && code <= 0xD1D7) || // Lo [27] HANGUL SYLLABLE TWAG..HANGUL SYLLABLE TWAH\r\n\t\t(0xD1D9 <= code && code <= 0xD1F3) || // Lo [27] HANGUL SYLLABLE TWAEG..HANGUL SYLLABLE TWAEH\r\n\t\t(0xD1F5 <= code && code <= 0xD20F) || // Lo [27] HANGUL SYLLABLE TOEG..HANGUL SYLLABLE TOEH\r\n\t\t(0xD211 <= code && code <= 0xD22B) || // Lo [27] HANGUL SYLLABLE TYOG..HANGUL SYLLABLE TYOH\r\n\t\t(0xD22D <= code && code <= 0xD247) || // Lo [27] HANGUL SYLLABLE TUG..HANGUL SYLLABLE TUH\r\n\t\t(0xD249 <= code && code <= 0xD263) || // Lo [27] HANGUL SYLLABLE TWEOG..HANGUL SYLLABLE TWEOH\r\n\t\t(0xD265 <= code && code <= 0xD27F) || // Lo [27] HANGUL SYLLABLE TWEG..HANGUL SYLLABLE TWEH\r\n\t\t(0xD281 <= code && code <= 0xD29B) || // Lo [27] HANGUL SYLLABLE TWIG..HANGUL SYLLABLE TWIH\r\n\t\t(0xD29D <= code && code <= 0xD2B7) || // Lo [27] HANGUL SYLLABLE TYUG..HANGUL SYLLABLE TYUH\r\n\t\t(0xD2B9 <= code && code <= 0xD2D3) || // Lo [27] HANGUL SYLLABLE TEUG..HANGUL SYLLABLE TEUH\r\n\t\t(0xD2D5 <= code && code <= 0xD2EF) || // Lo [27] HANGUL SYLLABLE TYIG..HANGUL SYLLABLE TYIH\r\n\t\t(0xD2F1 <= code && code <= 0xD30B) || // Lo [27] HANGUL SYLLABLE TIG..HANGUL SYLLABLE TIH\r\n\t\t(0xD30D <= code && code <= 0xD327) || // Lo [27] HANGUL SYLLABLE PAG..HANGUL SYLLABLE PAH\r\n\t\t(0xD329 <= code && code <= 0xD343) || // Lo [27] HANGUL SYLLABLE PAEG..HANGUL SYLLABLE PAEH\r\n\t\t(0xD345 <= code && code <= 0xD35F) || // Lo [27] HANGUL SYLLABLE PYAG..HANGUL SYLLABLE PYAH\r\n\t\t(0xD361 <= code && code <= 0xD37B) || // Lo [27] HANGUL SYLLABLE PYAEG..HANGUL SYLLABLE PYAEH\r\n\t\t(0xD37D <= code && code <= 0xD397) || // Lo [27] HANGUL SYLLABLE PEOG..HANGUL SYLLABLE PEOH\r\n\t\t(0xD399 <= code && code <= 0xD3B3) || // Lo [27] HANGUL SYLLABLE PEG..HANGUL SYLLABLE PEH\r\n\t\t(0xD3B5 <= code && code <= 0xD3CF) || // Lo [27] HANGUL SYLLABLE PYEOG..HANGUL SYLLABLE PYEOH\r\n\t\t(0xD3D1 <= code && code <= 0xD3EB) || // Lo [27] HANGUL SYLLABLE PYEG..HANGUL SYLLABLE PYEH\r\n\t\t(0xD3ED <= code && code <= 0xD407) || // Lo [27] HANGUL SYLLABLE POG..HANGUL SYLLABLE POH\r\n\t\t(0xD409 <= code && code <= 0xD423) || // Lo [27] HANGUL SYLLABLE PWAG..HANGUL SYLLABLE PWAH\r\n\t\t(0xD425 <= code && code <= 0xD43F) || // Lo [27] HANGUL SYLLABLE PWAEG..HANGUL SYLLABLE PWAEH\r\n\t\t(0xD441 <= code && code <= 0xD45B) || // Lo [27] HANGUL SYLLABLE POEG..HANGUL SYLLABLE POEH\r\n\t\t(0xD45D <= code && code <= 0xD477) || // Lo [27] HANGUL SYLLABLE PYOG..HANGUL SYLLABLE PYOH\r\n\t\t(0xD479 <= code && code <= 0xD493) || // Lo [27] HANGUL SYLLABLE PUG..HANGUL SYLLABLE PUH\r\n\t\t(0xD495 <= code && code <= 0xD4AF) || // Lo [27] HANGUL SYLLABLE PWEOG..HANGUL SYLLABLE PWEOH\r\n\t\t(0xD4B1 <= code && code <= 0xD4CB) || // Lo [27] HANGUL SYLLABLE PWEG..HANGUL SYLLABLE PWEH\r\n\t\t(0xD4CD <= code && code <= 0xD4E7) || // Lo [27] HANGUL SYLLABLE PWIG..HANGUL SYLLABLE PWIH\r\n\t\t(0xD4E9 <= code && code <= 0xD503) || // Lo [27] HANGUL SYLLABLE PYUG..HANGUL SYLLABLE PYUH\r\n\t\t(0xD505 <= code && code <= 0xD51F) || // Lo [27] HANGUL SYLLABLE PEUG..HANGUL SYLLABLE PEUH\r\n\t\t(0xD521 <= code && code <= 0xD53B) || // Lo [27] HANGUL SYLLABLE PYIG..HANGUL SYLLABLE PYIH\r\n\t\t(0xD53D <= code && code <= 0xD557) || // Lo [27] HANGUL SYLLABLE PIG..HANGUL SYLLABLE PIH\r\n\t\t(0xD559 <= code && code <= 0xD573) || // Lo [27] HANGUL SYLLABLE HAG..HANGUL SYLLABLE HAH\r\n\t\t(0xD575 <= code && code <= 0xD58F) || // Lo [27] HANGUL SYLLABLE HAEG..HANGUL SYLLABLE HAEH\r\n\t\t(0xD591 <= code && code <= 0xD5AB) || // Lo [27] HANGUL SYLLABLE HYAG..HANGUL SYLLABLE HYAH\r\n\t\t(0xD5AD <= code && code <= 0xD5C7) || // Lo [27] HANGUL SYLLABLE HYAEG..HANGUL SYLLABLE HYAEH\r\n\t\t(0xD5C9 <= code && code <= 0xD5E3) || // Lo [27] HANGUL SYLLABLE HEOG..HANGUL SYLLABLE HEOH\r\n\t\t(0xD5E5 <= code && code <= 0xD5FF) || // Lo [27] HANGUL SYLLABLE HEG..HANGUL SYLLABLE HEH\r\n\t\t(0xD601 <= code && code <= 0xD61B) || // Lo [27] HANGUL SYLLABLE HYEOG..HANGUL SYLLABLE HYEOH\r\n\t\t(0xD61D <= code && code <= 0xD637) || // Lo [27] HANGUL SYLLABLE HYEG..HANGUL SYLLABLE HYEH\r\n\t\t(0xD639 <= code && code <= 0xD653) || // Lo [27] HANGUL SYLLABLE HOG..HANGUL SYLLABLE HOH\r\n\t\t(0xD655 <= code && code <= 0xD66F) || // Lo [27] HANGUL SYLLABLE HWAG..HANGUL SYLLABLE HWAH\r\n\t\t(0xD671 <= code && code <= 0xD68B) || // Lo [27] HANGUL SYLLABLE HWAEG..HANGUL SYLLABLE HWAEH\r\n\t\t(0xD68D <= code && code <= 0xD6A7) || // Lo [27] HANGUL SYLLABLE HOEG..HANGUL SYLLABLE HOEH\r\n\t\t(0xD6A9 <= code && code <= 0xD6C3) || // Lo [27] HANGUL SYLLABLE HYOG..HANGUL SYLLABLE HYOH\r\n\t\t(0xD6C5 <= code && code <= 0xD6DF) || // Lo [27] HANGUL SYLLABLE HUG..HANGUL SYLLABLE HUH\r\n\t\t(0xD6E1 <= code && code <= 0xD6FB) || // Lo [27] HANGUL SYLLABLE HWEOG..HANGUL SYLLABLE HWEOH\r\n\t\t(0xD6FD <= code && code <= 0xD717) || // Lo [27] HANGUL SYLLABLE HWEG..HANGUL SYLLABLE HWEH\r\n\t\t(0xD719 <= code && code <= 0xD733) || // Lo [27] HANGUL SYLLABLE HWIG..HANGUL SYLLABLE HWIH\r\n\t\t(0xD735 <= code && code <= 0xD74F) || // Lo [27] HANGUL SYLLABLE HYUG..HANGUL SYLLABLE HYUH\r\n\t\t(0xD751 <= code && code <= 0xD76B) || // Lo [27] HANGUL SYLLABLE HEUG..HANGUL SYLLABLE HEUH\r\n\t\t(0xD76D <= code && code <= 0xD787) || // Lo [27] HANGUL SYLLABLE HYIG..HANGUL SYLLABLE HYIH\r\n\t\t(0xD789 <= code && code <= 0xD7A3) // Lo [27] HANGUL SYLLABLE HIG..HANGUL SYLLABLE HIH\r\n\t\t){\r\n\t\t\treturn LVT;\r\n\t\t}\r\n\t\t\r\n\t\tif(\r\n\t\t0x261D == code || // So WHITE UP POINTING INDEX\r\n\t\t0x26F9 == code || // So PERSON WITH BALL\r\n\t\t(0x270A <= code && code <= 0x270D) || // So [4] RAISED FIST..WRITING HAND\r\n\t\t0x1F385 == code || // So FATHER CHRISTMAS\r\n\t\t(0x1F3C2 <= code && code <= 0x1F3C4) || // So [3] SNOWBOARDER..SURFER\r\n\t\t0x1F3C7 == code || // So HORSE RACING\r\n\t\t(0x1F3CA <= code && code <= 0x1F3CC) || // So [3] SWIMMER..GOLFER\r\n\t\t(0x1F442 <= code && code <= 0x1F443) || // So [2] EAR..NOSE\r\n\t\t(0x1F446 <= code && code <= 0x1F450) || // So [11] WHITE UP POINTING BACKHAND INDEX..OPEN HANDS SIGN\r\n\t\t0x1F46E == code || // So POLICE OFFICER\r\n\t\t(0x1F470 <= code && code <= 0x1F478) || // So [9] BRIDE WITH VEIL..PRINCESS\r\n\t\t0x1F47C == code || // So BABY ANGEL\r\n\t\t(0x1F481 <= code && code <= 0x1F483) || // So [3] INFORMATION DESK PERSON..DANCER\r\n\t\t(0x1F485 <= code && code <= 0x1F487) || // So [3] NAIL POLISH..HAIRCUT\r\n\t\t0x1F4AA == code || // So FLEXED BICEPS\r\n\t\t(0x1F574 <= code && code <= 0x1F575) || // So [2] MAN IN BUSINESS SUIT LEVITATING..SLEUTH OR SPY\r\n\t\t0x1F57A == code || // So MAN DANCING\r\n\t\t0x1F590 == code || // So RAISED HAND WITH FINGERS SPLAYED\r\n\t\t(0x1F595 <= code && code <= 0x1F596) || // So [2] REVERSED HAND WITH MIDDLE FINGER EXTENDED..RAISED HAND WITH PART BETWEEN MIDDLE AND RING FINGERS\r\n\t\t(0x1F645 <= code && code <= 0x1F647) || // So [3] FACE WITH NO GOOD GESTURE..PERSON BOWING DEEPLY\r\n\t\t(0x1F64B <= code && code <= 0x1F64F) || // So [5] HAPPY PERSON RAISING ONE HAND..PERSON WITH FOLDED HANDS\r\n\t\t0x1F6A3 == code || // So ROWBOAT\r\n\t\t(0x1F6B4 <= code && code <= 0x1F6B6) || // So [3] BICYCLIST..PEDESTRIAN\r\n\t\t0x1F6C0 == code || // So BATH\r\n\t\t0x1F6CC == code || // So SLEEPING ACCOMMODATION\r\n\t\t(0x1F918 <= code && code <= 0x1F91C) || // So [5] SIGN OF THE HORNS..RIGHT-FACING FIST\r\n\t\t(0x1F91E <= code && code <= 0x1F91F) || // So [2] HAND WITH INDEX AND MIDDLE FINGERS CROSSED..I LOVE YOU HAND SIGN\r\n\t\t0x1F926 == code || // So FACE PALM\r\n\t\t(0x1F930 <= code && code <= 0x1F939) || // So [10] PREGNANT WOMAN..JUGGLING\r\n\t\t(0x1F93D <= code && code <= 0x1F93E) || // So [2] WATER POLO..HANDBALL\r\n\t\t(0x1F9D1 <= code && code <= 0x1F9DD) // So [13] ADULT..ELF\r\n\t\t){\r\n\t\t\treturn E_Base;\r\n\t\t}\r\n\r\n\t\tif(\r\n\t\t(0x1F3FB <= code && code <= 0x1F3FF) // Sk [5] EMOJI MODIFIER FITZPATRICK TYPE-1-2..EMOJI MODIFIER FITZPATRICK TYPE-6\r\n\t\t){\r\n\t\t\treturn E_Modifier;\r\n\t\t}\r\n\r\n\t\tif(\r\n\t\t0x200D == code // Cf ZERO WIDTH JOINER\r\n\t\t){\r\n\t\t\treturn ZWJ;\r\n\t\t}\r\n\r\n\t\tif(\r\n\t\t0x2640 == code || // So FEMALE SIGN\r\n\t\t0x2642 == code || // So MALE SIGN\r\n\t\t(0x2695 <= code && code <= 0x2696) || // So [2] STAFF OF AESCULAPIUS..SCALES\r\n\t\t0x2708 == code || // So AIRPLANE\r\n\t\t0x2764 == code || // So HEAVY BLACK HEART\r\n\t\t0x1F308 == code || // So RAINBOW\r\n\t\t0x1F33E == code || // So EAR OF RICE\r\n\t\t0x1F373 == code || // So COOKING\r\n\t\t0x1F393 == code || // So GRADUATION CAP\r\n\t\t0x1F3A4 == code || // So MICROPHONE\r\n\t\t0x1F3A8 == code || // So ARTIST PALETTE\r\n\t\t0x1F3EB == code || // So SCHOOL\r\n\t\t0x1F3ED == code || // So FACTORY\r\n\t\t0x1F48B == code || // So KISS MARK\r\n\t\t(0x1F4BB <= code && code <= 0x1F4BC) || // So [2] PERSONAL COMPUTER..BRIEFCASE\r\n\t\t0x1F527 == code || // So WRENCH\r\n\t\t0x1F52C == code || // So MICROSCOPE\r\n\t\t0x1F5E8 == code || // So LEFT SPEECH BUBBLE\r\n\t\t0x1F680 == code || // So ROCKET\r\n\t\t0x1F692 == code // So FIRE ENGINE\r\n\t\t){\r\n\t\t\treturn Glue_After_Zwj;\r\n\t\t}\r\n\r\n\t\tif(\r\n\t\t(0x1F466 <= code && code <= 0x1F469) // So [4] BOY..WOMAN\r\n\t\t){\r\n\t\t\treturn E_Base_GAZ;\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\t//all unlisted characters have a grapheme break property of \"Other\"\r\n\t\treturn Other;\r\n\t}\r\n\treturn this;\r\n}\r\n\r\nif (typeof module != 'undefined' && module.exports) {\r\n module.exports = GraphemeSplitter;\r\n}\r\n", "/*\n * Represent a User Data Header https://en.wikipedia.org/wiki/User_Data_Header\n * Twilio messages reserve 6 of this per segment in a concatenated message\n */\n\nclass UserDataHeader {\n isReservedChar: boolean;\n\n isUserDataHeader: boolean;\n\n constructor() {\n this.isReservedChar = true;\n this.isUserDataHeader = true;\n }\n\n static codeUnitSizeInBits(): number {\n return 8;\n }\n\n sizeInBits(): number {\n return 8;\n }\n}\n\nexport default UserDataHeader;\n", "import UserDataHeader from './UserDataHeader';\nimport EncodedChar from './EncodedChar';\n\n/**\n * Segment Class\n * A modified array representing one segment and add some helper functions\n */\n\nclass Segment extends Array {\n hasTwilioReservedBits: boolean;\n\n hasUserDataHeader: boolean;\n\n constructor(withUserDataHeader: boolean = false) {\n super();\n // TODO: Refactor this. Bad practice to extend basic types\n Object.setPrototypeOf(this, Object.create(Segment.prototype));\n this.hasTwilioReservedBits = withUserDataHeader;\n this.hasUserDataHeader = withUserDataHeader;\n if (withUserDataHeader) {\n for (let i = 0; i < 6; i++) {\n this.push(new UserDataHeader());\n }\n }\n }\n\n // Size in bits *including* User Data Header (if present)\n sizeInBits(): number {\n return this.reduce((accumulator: number, encodedChar: Segment) => accumulator + encodedChar.sizeInBits(), 0);\n }\n\n // Size in bits *excluding* User Data Header (if present)\n messageSizeInBits(): number {\n return this.reduce(\n (accumulator: number, encodedChar: Segment) =>\n accumulator + (encodedChar instanceof UserDataHeader ? 0 : encodedChar.sizeInBits()),\n 0,\n );\n }\n\n freeSizeInBits(): number {\n const maxBitsInSegment = 1120; // max size of a SMS is 140 octets -> 140 * 8bits = 1120 bits\n return maxBitsInSegment - this.sizeInBits();\n }\n\n addHeader(): EncodedChar[] {\n if (this.hasUserDataHeader) {\n return [];\n }\n const leftOverChar: EncodedChar[] = [];\n this.hasTwilioReservedBits = true;\n this.hasUserDataHeader = false;\n for (let i = 0; i < 6; i++) {\n this.unshift(new UserDataHeader());\n }\n // Remove characters\n while (this.freeSizeInBits() < 0) {\n leftOverChar.unshift(this.pop());\n }\n return leftOverChar;\n }\n}\n\nexport default Segment;\n", "/*\n * In order to avoid confusion here is a list of terms\n * used throughout this code:\n * - octet: represent a byte or 8bits\n * - septet: represent 7bits\n * - character: a text unit, think one char is one glyph (Warning: this is an oversimplification and not always true)\n * - code point: a character value in a given encoding\n * - code unit: a single \"block\" used to encode a character\n * UCS-2 is of fixed length and every character is 2 code units long\n * GSM-7 is of variable length and require 1 or 2 code unit per character\n */\n\n// Map of Javascript code points to GSM-7\nconst UnicodeToGsm: Record> = {\n 0x000a: [0x0a],\n 0x000c: [0x1b, 0x0a],\n 0x000d: [0x0d],\n 0x0020: [0x20],\n 0x0021: [0x21],\n 0x0022: [0x22],\n 0x0023: [0x23],\n 0x0024: [0x02],\n 0x0025: [0x25],\n 0x0026: [0x26],\n 0x0027: [0x27],\n 0x0028: [0x28],\n 0x0029: [0x29],\n 0x002a: [0x2a],\n 0x002b: [0x2b],\n 0x002c: [0x2c],\n 0x002d: [0x2d],\n 0x002e: [0x2e],\n 0x002f: [0x2f],\n 0x0030: [0x30],\n 0x0031: [0x31],\n 0x0032: [0x32],\n 0x0033: [0x33],\n 0x0034: [0x34],\n 0x0035: [0x35],\n 0x0036: [0x36],\n 0x0037: [0x37],\n 0x0038: [0x38],\n 0x0039: [0x39],\n 0x003a: [0x3a],\n 0x003b: [0x3b],\n 0x003c: [0x3c],\n 0x003d: [0x3d],\n 0x003e: [0x3e],\n 0x003f: [0x3f],\n 0x0040: [0x00],\n 0x0041: [0x41],\n 0x0042: [0x42],\n 0x0043: [0x43],\n 0x0044: [0x44],\n 0x0045: [0x45],\n 0x0046: [0x46],\n 0x0047: [0x47],\n 0x0048: [0x48],\n 0x0049: [0x49],\n 0x004a: [0x4a],\n 0x004b: [0x4b],\n 0x004c: [0x4c],\n 0x004d: [0x4d],\n 0x004e: [0x4e],\n 0x004f: [0x4f],\n 0x0050: [0x50],\n 0x0051: [0x51],\n 0x0052: [0x52],\n 0x0053: [0x53],\n 0x0054: [0x54],\n 0x0055: [0x55],\n 0x0056: [0x56],\n 0x0057: [0x57],\n 0x0058: [0x58],\n 0x0059: [0x59],\n 0x005a: [0x5a],\n 0x005b: [0x1b, 0x3c],\n 0x005c: [0x1b, 0x2f],\n 0x005d: [0x1b, 0x3e],\n 0x005e: [0x1b, 0x14],\n 0x005f: [0x11],\n 0x0061: [0x61],\n 0x0062: [0x62],\n 0x0063: [0x63],\n 0x0064: [0x64],\n 0x0065: [0x65],\n 0x0066: [0x66],\n 0x0067: [0x67],\n 0x0068: [0x68],\n 0x0069: [0x69],\n 0x006a: [0x6a],\n 0x006b: [0x6b],\n 0x006c: [0x6c],\n 0x006d: [0x6d],\n 0x006e: [0x6e],\n 0x006f: [0x6f],\n 0x0070: [0x70],\n 0x0071: [0x71],\n 0x0072: [0x72],\n 0x0073: [0x73],\n 0x0074: [0x74],\n 0x0075: [0x75],\n 0x0076: [0x76],\n 0x0077: [0x77],\n 0x0078: [0x78],\n 0x0079: [0x79],\n 0x007a: [0x7a],\n 0x007b: [0x1b, 0x28],\n 0x007c: [0x1b, 0x40],\n 0x007d: [0x1b, 0x29],\n 0x007e: [0x1b, 0x3d],\n 0x00a1: [0x40],\n 0x00a3: [0x01],\n 0x00a4: [0x24],\n 0x00a5: [0x03],\n 0x00a7: [0x5f],\n 0x00bf: [0x60],\n 0x00c4: [0x5b],\n 0x00c5: [0x0e],\n 0x00c6: [0x1c],\n 0x00c9: [0x1f],\n 0x00d1: [0x5d],\n 0x00d6: [0x5c],\n 0x00d8: [0x0b],\n 0x00dc: [0x5e],\n 0x00df: [0x1e],\n 0x00e0: [0x7f],\n 0x00e4: [0x7b],\n 0x00e5: [0x0f],\n 0x00e6: [0x1d],\n 0x00c7: [0x09],\n 0x00e8: [0x04],\n 0x00e9: [0x05],\n 0x00ec: [0x07],\n 0x00f1: [0x7d],\n 0x00f2: [0x08],\n 0x00f6: [0x7c],\n 0x00f8: [0x0c],\n 0x00f9: [0x06],\n 0x00fc: [0x7e],\n 0x0393: [0x13],\n 0x0394: [0x10],\n 0x0398: [0x19],\n 0x039b: [0x14],\n 0x039e: [0x1a],\n 0x03a0: [0x16],\n 0x03a3: [0x18],\n 0x03a6: [0x12],\n 0x03a8: [0x17],\n 0x03a9: [0x15],\n 0x20ac: [0x1b, 0x65],\n};\n\nexport default UnicodeToGsm;\n", "import UnicodeToGsm from './UnicodeToGSM';\n\n/**\n * Encoded Character Classes\n * Utility classes to represent a character in a given encoding.\n */\n\nclass EncodedChar {\n // Raw character (grapheme) as passed in the constructor\n raw: string;\n\n // Array of 8 bits number rapresenting the encoded character\n codeUnits: number[];\n\n // True if the character is a GSM7 one\n isGSM7: boolean;\n\n // Which encoding to use for this char\n encoding: 'GSM-7' | 'UCS-2';\n\n constructor(char: string, encoding: 'GSM-7' | 'UCS-2') {\n this.raw = char;\n this.encoding = encoding;\n this.isGSM7 = Boolean(char && UnicodeToGsm[char.charCodeAt(0)]);\n if (this.isGSM7) {\n this.codeUnits = UnicodeToGsm[char.charCodeAt(0)];\n } else {\n this.codeUnits = [];\n for (let i = 0; i < char.length; i++) {\n this.codeUnits.push(char.charCodeAt(i));\n }\n }\n }\n\n codeUnitSizeInBits(): number {\n return this.encoding === 'GSM-7' ? 7 : 8;\n }\n\n sizeInBits(): number {\n if (this.encoding === 'UCS-2' && this.isGSM7) {\n // GSM characters are always using 16 bits in UCS-2 encoding\n return 16;\n }\n const bitsPerUnits = this.encoding === 'GSM-7' ? 7 : 16;\n return bitsPerUnits * this.codeUnits.length;\n }\n}\n\nexport default EncodedChar;\n", "const SmartEncodingMap: {\n [key: string]: string;\n} = {\n '\\u00ab': '\"', // LEFT-POINTING DOUBLE ANGLE QUOTATION MARK\n '\\u00bb': '\"', // RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK\n '\\u201c': '\"', // LEFT DOUBLE QUOTATION MARK\n '\\u201d': '\"', // RIGHT DOUBLE QUOTATION MARK\n '\\u02ba': '\"', // MODIFIER LETTER DOUBLE PRIME\n '\\u02ee': '\"', // MODIFIER LETTER DOUBLE APOSTROPHE\n '\\u201f': '\"', // DOUBLE HIGH-REVERSED-9 QUOTATION MARK\n '\\u275d': '\"', // HEAVY DOUBLE TURNED COMMA QUOTATION MARK ORNAMENT\n '\\u275e': '\"', // HEAVY DOUBLE COMMA QUOTATION MARK ORNAMENT\n '\\u301d': '\"', // REVERSED DOUBLE PRIME QUOTATION MARK\n '\\u301e': '\"', // DOUBLE PRIME QUOTATION MARK\n '\\uff02': '\"', // FULLWIDTH QUOTATION MARK\n '\\u2018': \"'\", // LEFT SINGLE QUOTATION MARK\n '\\u2019': \"'\", // RIGHT SINGLE QUOTATION MARK\n '\\u02BB': \"'\", // MODIFIER LETTER TURNED COMMA\n '\\u02c8': \"'\", // MODIFIER LETTER VERTICAL LINE\n '\\u02bc': \"'\", // MODIFIER LETTER APOSTROPHE\n '\\u02bd': \"'\", // MODIFIER LETTER REVERSED COMMA\n '\\u02b9': \"'\", // MODIFIER LETTER PRIME\n '\\u201b': \"'\", // SINGLE HIGH-REVERSED-9 QUOTATION MARK\n '\\uff07': \"'\", // FULLWIDTH APOSTROPHE\n '\\u00b4': \"'\", // ACUTE ACCENT\n '\\u02ca': \"'\", // MODIFIER LETTER ACUTE ACCENT\n '\\u0060': \"'\", // GRAVE ACCENT\n '\\u02cb': \"'\", // MODIFIER LETTER GRAVE ACCENT\n '\\u275b': \"'\", // HEAVY SINGLE TURNED COMMA QUOTATION MARK ORNAMENT\n '\\u275c': \"'\", // HEAVY SINGLE COMMA QUOTATION MARK ORNAMENT\n '\\u0313': \"'\", // COMBINING COMMA ABOVE\n '\\u0314': \"'\", // COMBINING REVERSED COMMA ABOVE\n '\\ufe10': \"'\", // PRESENTATION FORM FOR VERTICAL COMMA\n '\\ufe11': \"'\", // PRESENTATION FORM FOR VERTICAL IDEOGRAPHIC COMMA\n '\\u00F7': '/', // DIVISION SIGN\n '\\u00bc': '1/4', // VULGAR FRACTION ONE QUARTER\n '\\u00bd': '1/2', // VULGAR FRACTION ONE HALF\n '\\u00be': '3/4', // VULGAR FRACTION THREE QUARTERS\n '\\u29f8': '/', // BIG SOLIDUS\n '\\u0337': '/', // COMBINING SHORT SOLIDUS OVERLAY\n '\\u0338': '/', // COMBINING LONG SOLIDUS OVERLAY\n '\\u2044': '/', // FRACTION SLASH\n '\\u2215': '/', // DIVISION SLASH\n '\\uff0f': '/', // FULLWIDTH SOLIDUS\n '\\u29f9': '\\\\', // BIG REVERSE SOLIDUS\n '\\u29f5': '\\\\', // REVERSE SOLIDUS OPERATOR\n '\\u20e5': '\\\\', // COMBINING REVERSE SOLIDUS OVERLAY\n '\\ufe68': '\\\\', // SMALL REVERSE SOLIDUS\n '\\uff3c': '\\\\', // FULLWIDTH REVERSE SOLIDUS\n '\\u0332': '_', // COMBINING LOW LINE\n '\\uff3f': '_', // FULLWIDTH LOW LINE\n '\\u20d2': '|', // COMBINING LONG VERTICAL LINE OVERLAY\n '\\u20d3': '|', // COMBINING SHORT VERTICAL LINE OVERLAY\n '\\u2223': '|', // DIVIDES\n '\\uff5c': '|', // FULLWIDTH VERTICAL LINE\n '\\u23b8': '|', // LEFT VERTICAL BOX LINE\n '\\u23b9': '|', // RIGHT VERTICAL BOX LINE\n '\\u23d0': '|', // VERTICAL LINE EXTENSION\n '\\u239c': '|', // LEFT PARENTHESIS EXTENSION\n '\\u239f': '|', // RIGHT PARENTHESIS EXTENSION\n '\\u23bc': '-', // HORIZONTAL SCAN LINE-7\n '\\u23bd': '-', // HORIZONTAL SCAN LINE-9\n '\\u2015': '-', // HORIZONTAL BAR\n '\\ufe63': '-', // SMALL HYPHEN-MINUS\n '\\uff0d': '-', // FULLWIDTH HYPHEN-MINUS\n '\\u2010': '-', // HYPHEN\n '\\u2043': '-', // HYPHEN BULLET\n '\\ufe6b': '@', // SMALL COMMERCIAL AT\n '\\uff20': '@', // FULLWIDTH COMMERCIAL AT\n '\\ufe69': '$', // SMALL DOLLAR SIGN\n '\\uff04': '$', // FULLWIDTH DOLLAR SIGN\n '\\u01c3': '!', // LATIN LETTER RETROFLEX CLICK\n '\\ufe15': '!', // PRESENTATION FORM FOR VERTICAL EXLAMATION MARK\n '\\ufe57': '!', // SMALL EXCLAMATION MARK\n '\\uff01': '!', // FULLWIDTH EXCLAMATION MARK\n '\\ufe5f': '#', // SMALL NUMBER SIGN\n '\\uff03': '#', // FULLWIDTH NUMBER SIGN\n '\\ufe6a': '%', // SMALL PERCENT SIGN\n '\\uff05': '%', // FULLWIDTH PERCENT SIGN\n '\\ufe60': '&', // SMALL AMPERSAND\n '\\uff06': '&', // FULLWIDTH AMPERSAND\n '\\u201a': ',', // SINGLE LOW-9 QUOTATION MARK\n '\\u0326': ',', // COMBINING COMMA BELOW\n '\\ufe50': ',', // SMALL COMMA\n '\\ufe51': ',', // SMALL IDEOGRAPHIC COMMA\n '\\uff0c': ',', // FULLWIDTH COMMA\n '\\uff64': ',', // HALFWIDTH IDEOGRAPHIC COMMA\n '\\u2768': '(', // MEDIUM LEFT PARENTHESIS ORNAMENT\n '\\u276a': '(', // MEDIUM FLATTENED LEFT PARENTHESIS ORNAMENT\n '\\ufe59': '(', // SMALL LEFT PARENTHESIS\n '\\uff08': '(', // FULLWIDTH LEFT PARENTHESIS\n '\\u27ee': '(', // MATHEMATICAL LEFT FLATTENED PARENTHESIS\n '\\u2985': '(', // LEFT WHITE PARENTHESIS\n '\\u2769': ')', // MEDIUM RIGHT PARENTHESIS ORNAMENT\n '\\u276b': ')', // MEDIUM FLATTENED RIGHT PARENTHESIS ORNAMENT\n '\\ufe5a': ')', // SMALL RIGHT PARENTHESIS\n '\\uff09': ')', // FULLWIDTH RIGHT PARENTHESIS\n '\\u27ef': ')', // MATHEMATICAL RIGHT FLATTENED PARENTHESIS\n '\\u2986': ')', // RIGHT WHITE PARENTHESIS\n '\\u204e': '*', // LOW ASTERISK\n '\\u2217': '*', // ASTERISK OPERATOR\n '\\u229B': '*', // CIRCLED ASTERISK OPERATOR\n '\\u2722': '*', // FOUR TEARDROP-SPOKED ASTERISK\n '\\u2723': '*', // FOUR BALLOON-SPOKED ASTERISK\n '\\u2724': '*', // HEAVY FOUR BALLOON-SPOKED ASTERISK\n '\\u2725': '*', // FOUR CLUB-SPOKED ASTERISK\n '\\u2731': '*', // HEAVY ASTERISK\n '\\u2732': '*', // OPEN CENTRE ASTERISK\n '\\u2733': '*', // EIGHT SPOKED ASTERISK\n '\\u273a': '*', // SIXTEEN POINTED ASTERISK\n '\\u273b': '*', // TEARDROP-SPOKED ASTERISK\n '\\u273c': '*', // OPEN CENTRE TEARDROP-SPOKED ASTERISK\n '\\u273d': '*', // HEAVY TEARDROP-SPOKED ASTERISK\n '\\u2743': '*', // HEAVY TEARDROP-SPOKED PINWHEEL ASTERISK\n '\\u2749': '*', // BALLOON-SPOKED ASTERISK\n '\\u274a': '*', // EIGHT TEARDROP-SPOKED PROPELLER ASTERISK\n '\\u274b': '*', // HEAVY EIGHT TEARDROP-SPOKED PROPELLER ASTERISK\n '\\u29c6': '*', // SQUARED ASTERISK\n '\\ufe61': '*', // SMALL ASTERISK\n '\\uff0a': '*', // FULLWIDTH ASTERISK\n '\\u02d6': '+', // MODIFIER LETTER PLUS SIGN\n '\\ufe62': '+', // SMALL PLUS SIGN\n '\\uff0b': '+', // FULLWIDTH PLUS SIGN\n '\\u3002': '.', // IDEOGRAPHIC FULL STOP\n '\\ufe52': '.', // SMALL FULL STOP\n '\\uff0e': '.', // FULLWIDTH FULL STOP\n '\\uff61': '.', // HALFWIDTH IDEOGRAPHIC FULL STOP\n '\\uff10': '0', // FULLWIDTH DIGIT ZERO\n '\\uff11': '1', // FULLWIDTH DIGIT ONE\n '\\uff12': '2', // FULLWIDTH DIGIT TWO\n '\\uff13': '3', // FULLWIDTH DIGIT THREE\n '\\uff14': '4', // FULLWIDTH DIGIT FOUR\n '\\uff15': '5', // FULLWIDTH DIGIT FIVE\n '\\uff16': '6', // FULLWIDTH DIGIT SIX\n '\\uff17': '7', // FULLWIDTH DIGIT SEVEN\n '\\uff18': '8', // FULLWIDTH DIGIT EIGHT\n '\\uff19': '9', // FULLWIDTH DIGIT NINE\n '\\u02d0': ':', // MODIFIER LETTER TRIANGULAR COLON\n '\\u02f8': ':', // MODIFIER LETTER RAISED COLON\n '\\u2982': ':', // Z NOTATION TYPE COLON\n '\\ua789': ':', // MODIFIER LETTER COLON\n '\\ufe13': ':', // PRESENTATION FORM FOR VERTICAL COLON\n '\\uff1a': ':', // FULLWIDTH COLON\n '\\u204f': ';', // REVERSED SEMICOLON\n '\\ufe14': ';', // PRESENTATION FORM FOR VERTICAL SEMICOLON\n '\\ufe54': ';', // SMALL SEMICOLON\n '\\uff1b': ';', // FULLWIDTH SEMICOLON\n '\\ufe64': '<', // SMALL LESS-THAN SIGN\n '\\uff1c': '<', // FULLWIDTH LESS-THAN SIGN\n '\\u0347': '=', // COMBINING EQUALS SIGN BELOW\n '\\ua78a': '=', // MODIFIER LETTER SHORT EQUALS SIGN\n '\\ufe66': '=', // SMALL EQUALS SIGN\n '\\uff1d': '=', // FULLWIDTH EQUALS SIGN\n '\\ufe65': '>', // SMALL GREATER-THAN SIGN\n '\\uff1e': '>', // FULLWIDTH GREATER-THAN SIGN\n '\\ufe16': '?', // PRESENTATION FORM FOR VERTICAL QUESTION MARK\n '\\ufe56': '?', // SMALL QUESTION MARK\n '\\uff1f': '?', // FULLWIDTH QUESTION MARK\n '\\uff21': 'A', // FULLWIDTH LATIN CAPITAL LETTER A\n '\\u1d00': 'A', // LATIN LETTER SMALL CAPITAL A\n '\\uff22': 'B', // FULLWIDTH LATIN CAPITAL LETTER B\n '\\u0299': 'B', // LATIN LETTER SMALL CAPITAL B\n '\\uff23': 'C', // FULLWIDTH LATIN CAPITAL LETTER C\n '\\u1d04': 'C', // LATIN LETTER SMALL CAPITAL C\n '\\uff24': 'D', // FULLWIDTH LATIN CAPITAL LETTER D\n '\\u1d05': 'D', // LATIN LETTER SMALL CAPITAL D\n '\\uff25': 'E', // FULLWIDTH LATIN CAPITAL LETTER E\n '\\u1d07': 'E', // LATIN LETTER SMALL CAPITAL E\n '\\uff26': 'F', // FULLWIDTH LATIN CAPITAL LETTER F\n '\\ua730': 'F', // LATIN LETTER SMALL CAPITAL F\n '\\uff27': 'G', // FULLWIDTH LATIN CAPITAL LETTER G\n '\\u0262': 'G', // LATIN LETTER SMALL CAPITAL G\n '\\uff28': 'H', // FULLWIDTH LATIN CAPITAL LETTER H\n '\\u029c': 'H', // LATIN LETTER SMALL CAPITAL H\n '\\uff29': 'I', // FULLWIDTH LATIN CAPITAL LETTER I\n '\\u026a': 'I', // LATIN LETTER SMALL CAPITAL I\n '\\uff2a': 'J', // FULLWIDTH LATIN CAPITAL LETTER J\n '\\u1d0a': 'J', // LATIN LETTER SMALL CAPITAL J\n '\\uff2b': 'K', // FULLWIDTH LATIN CAPITAL LETTER K\n '\\u1d0b': 'K', // LATIN LETTER SMALL CAPITAL K\n '\\uff2c': 'L', // FULLWIDTH LATIN CAPITAL LETTER L\n '\\u029f': 'L', // LATIN LETTER SMALL CAPITAL L\n '\\uff2d': 'M', // FULLWIDTH LATIN CAPITAL LETTER M\n '\\u1d0d': 'M', // LATIN LETTER SMALL CAPITAL M\n '\\uff2e': 'N', // FULLWIDTH LATIN CAPITAL LETTER N\n '\\u0274': 'N', // LATIN LETTER SMALL CAPITAL N\n '\\uff2f': 'O', // FULLWIDTH LATIN CAPITAL LETTER O\n '\\u1d0f': 'O', // LATIN LETTER SMALL CAPITAL O\n '\\uff30': 'P', // FULLWIDTH LATIN CAPITAL LETTER P\n '\\u1d18': 'P', // LATIN LETTER SMALL CAPITAL P\n '\\uff31': 'Q', // FULLWIDTH LATIN CAPITAL LETTER Q\n '\\uff32': 'R', // FULLWIDTH LATIN CAPITAL LETTER R\n '\\u0280': 'R', // LATIN LETTER SMALL CAPITAL R\n '\\uff33': 'S', // FULLWIDTH LATIN CAPITAL LETTER S\n '\\ua731': 'S', // LATIN LETTER SMALL CAPITAL S\n '\\uff34': 'T', // FULLWIDTH LATIN CAPITAL LETTER T\n '\\u1d1b': 'T', // LATIN LETTER SMALL CAPITAL T\n '\\uff35': 'U', // FULLWIDTH LATIN CAPITAL LETTER U\n '\\u1d1c': 'U', // LATIN LETTER SMALL CAPITAL U\n '\\uff36': 'V', // FULLWIDTH LATIN CAPITAL LETTER V\n '\\u1d20': 'V', // LATIN LETTER SMALL CAPITAL V\n '\\uff37': 'W', // FULLWIDTH LATIN CAPITAL LETTER W\n '\\u1d21': 'W', // LATIN LETTER SMALL CAPITAL W\n '\\uff38': 'X', // FULLWIDTH LATIN CAPITAL LETTER X\n '\\uff39': 'Y', // FULLWIDTH LATIN CAPITAL LETTER Y\n '\\u028f': 'Y', // LATIN LETTER SMALL CAPITAL Y\n '\\uff3a': 'Z', // FULLWIDTH LATIN CAPITAL LETTER Z\n '\\u1d22': 'Z', // LATIN LETTER SMALL CAPITAL Z\n '\\u02c6': '^', // MODIFIER LETTER CIRCUMFLEX ACCENT\n '\\u0302': '^', // COMBINING CIRCUMFLEX ACCENT\n '\\uff3e': '^', // FULLWIDTH CIRCUMFLEX ACCENT\n '\\u1dcd': '^', // COMBINING DOUBLE CIRCUMFLEX ABOVE\n '\\u2774': '{', // MEDIUM LEFT CURLY BRACKET ORNAMENT\n '\\ufe5b': '{', // SMALL LEFT CURLY BRACKET\n '\\uff5b': '{', // FULLWIDTH LEFT CURLY BRACKET\n '\\u2775': '}', // MEDIUM RIGHT CURLY BRACKET ORNAMENT\n '\\ufe5c': '}', // SMALL RIGHT CURLY BRACKET\n '\\uff5d': '}', // FULLWIDTH RIGHT CURLY BRACKET\n '\\uff3b': '[', // FULLWIDTH LEFT SQUARE BRACKET\n '\\uff3d': ']', // FULLWIDTH RIGHT SQUARE BRACKET\n '\\u02dc': '~', // SMALL TILDE\n '\\u02f7': '~', // MODIFIER LETTER LOW TILDE\n '\\u0303': '~', // COMBINING TILDE\n '\\u0330': '~', // COMBINING TILDE BELOW\n '\\u0334': '~', // COMBINING TILDE OVERLAY\n '\\u223c': '~', // TILDE OPERATOR\n '\\uff5e': '~', // FULLWIDTH TILDE\n '\\u00a0': ' ', // NO-BREAK SPACE\n '\\u2000': ' ', // EN QUAD\n '\\u2002': ' ', // EN SPACE\n '\\u2003': ' ', // EM SPACE\n '\\u2004': ' ', // THREE-PER-EM SPACE\n '\\u2005': ' ', // FOUR-PER-EM SPACE\n '\\u2006': ' ', // SIX-PER-EM SPACE\n '\\u2007': ' ', // FIGURE SPACE\n '\\u2008': ' ', // PUNCTUATION SPACE\n '\\u2009': ' ', // THIN SPACE\n '\\u200a': ' ', // HAIR SPACE\n '\\u202f': ' ', // NARROW NO-BREAK SPACE\n '\\u205f': ' ', // MEDIUM MATHEMATICAL SPACE\n '\\u3000': ' ', // IDEOGRAHPIC SPACE\n '\\u008d': ' ', // REVERSE LINE FEED (standard LF looks like \\n, this looks like a space)\n '\\u009f': ' ', // \n '\\u0080': ' ', // C1 CONTROL CODES\n '\\u0090': ' ', // DEVICE CONTROL STRING\n '\\u009b': ' ', // CONTROL SEQUENCE INTRODUCER\n '\\u0010': '', // ESCAPE, DATA LINK (not visible)\n '\\u0009': ' ', // TAB (7 spaces based on print statement in Python interpreter)\n '\\u0000': '', // NULL\n '\\u0003': '', // END OF TEXT\n '\\u0004': '', // END OF TRANSMISSION\n '\\u0017': '', // END OF TRANSMISSION BLOCK\n '\\u0019': '', // END OF MEDIUM\n '\\u0011': '', // DEVICE CONTROL ONE\n '\\u0012': '', // DEVICE CONTROL TWO\n '\\u0013': '', // DEVICE CONTROL THREE\n '\\u0014': '', // DEVICE CONTROL FOUR\n '\\u2060': '', // WORD JOINER\n '\\u2017': \"'\", // Horizontal ellipsis\n '\\u2014': '-', // Single low-9 quotation mark\n '\\u2013': '-', // Single high-reversed-9 quotation mark\n '\\u2039': '>', // Single left-pointing angle quotation mark\n '\\u203A': '<', // Single right-pointing angle quotation mark\n '\\u203C': '!!', // Double exclamation mark\n '\\u201E': '\"', // Double low line\n '\\u2028': ' ', // Whitespace: Line Separator\n '\\u2029': ' ', // Whitespace: Paragraph Separator\n '\\u2026': '...', // Whitespace: Narrow No-Break Space\n '\\u2001': ' ', // Whitespace: Medium Mathematical Space\n '\\u200b': '', // ZERO WIDTH SPACE\n '\\u3001': ',', // IDEOGRAPHIC COMMA\n '\\uFEFF': '', // ZERO WIDTH NO-BREAK SPACE\n '\\u2022': '-', // Bullet\n};\n\nexport default SmartEncodingMap;\n", "import GraphemeSplitter from 'grapheme-splitter';\n\nimport Segment from './Segment';\nimport EncodedChar from './EncodedChar';\nimport UnicodeToGsm from './UnicodeToGSM';\nimport SmartEncodingMap from './SmartEncodingMap';\n\ntype SmsEncoding = 'GSM-7' | 'UCS-2';\n\ntype EncodedChars = Array;\n\nconst validEncodingValues = ['GSM-7', 'UCS-2', 'auto'];\n\n/**\n * Class representing a segmented SMS\n */\nexport class SegmentedMessage {\n encoding: SmsEncoding | 'auto';\n\n segments: Segment[];\n\n graphemes: string[];\n\n encodingName: SmsEncoding;\n\n numberOfUnicodeScalars: number;\n\n numberOfCharacters: number;\n\n encodedChars: EncodedChars;\n\n /**\n *\n * Create a new segmented message from a string\n *\n * @param {string} message Body of the message\n * @param {boolean} [encoding] Optional: encoding. It can be 'GSM-7', 'UCS-2', 'auto'. Default value: 'auto'\n * @param {boolean} smartEncoding Optional: whether or not Twilio's [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) is emulated. Default value: false\n * @property {number} numberOfUnicodeScalars Number of Unicode Scalars (i.e. unicode pairs) the message is made of\n *\n */\n constructor(message: string, encoding: SmsEncoding | 'auto' = 'auto', smartEncoding: boolean = false) {\n const splitter = new GraphemeSplitter();\n\n if (!validEncodingValues.includes(encoding)) {\n throw new Error(\n `Encoding ${encoding} not supported. Valid values for encoding are ${validEncodingValues.join(', ')}`,\n );\n }\n\n if (smartEncoding) {\n message = [...message]\n .map((char) => (SmartEncodingMap[char] === undefined ? char : SmartEncodingMap[char]))\n .join('');\n }\n\n /**\n * @property {string[]} graphemes Graphemes (array of strings) the message have been split into\n */\n this.graphemes = splitter.splitGraphemes(message);\n /**\n * @property {number} numberOfUnicodeScalars Number of Unicode Scalars (i.e. unicode pairs) the message is made of\n * Some characters (e.g. extended emoji) can be made of more than one unicode pair\n */\n this.numberOfUnicodeScalars = [...message].length;\n /**\n * @property {string} encoding Encoding set in the constructor for the message. Allowed values: 'GSM-7', 'UCS-2', 'auto'.\n * @private\n */\n this.encoding = encoding;\n\n if (this.encoding === 'auto') {\n /**\n * @property {string} encodingName Calculated encoding name. It can be: \"GSM-7\" or \"UCS-2\"\n */\n this.encodingName = this._hasAnyUCSCharacters(this.graphemes) ? 'UCS-2' : 'GSM-7';\n } else {\n if (encoding === 'GSM-7' && this._hasAnyUCSCharacters(this.graphemes)) {\n throw new Error('The string provided is incompatible with GSM-7 encoding');\n }\n this.encodingName = this.encoding;\n }\n\n /**\n * @property {string[]} encodedChars Array of encoded characters composing the message\n */\n this.encodedChars = this._encodeChars(this.graphemes);\n\n /**\n * @property {number} numberOfCharacters Number of characters in the message. Each character count as 1 except for\n * the characters in the GSM extension character set.\n */\n this.numberOfCharacters =\n this.encodingName === 'UCS-2' ? this.graphemes.length : this._countCodeUnits(this.encodedChars);\n\n /**\n * @property {object[]} segments Array of segment(s) the message have been segmented into\n */\n this.segments = this._buildSegments(this.encodedChars);\n }\n\n /**\n * Internal method to check if the message has any non-GSM7 characters\n *\n * @param {string[]} graphemes Message body\n * @returns {boolean} True if there are non-GSM-7 characters\n * @private\n */\n _hasAnyUCSCharacters(graphemes: string[]): boolean {\n let result = false;\n for (const grapheme of graphemes) {\n if (grapheme.length >= 2 || (grapheme.length === 1 && !UnicodeToGsm[grapheme.charCodeAt(0)])) {\n result = true;\n break;\n }\n }\n return result;\n }\n\n /**\n * Internal method used to build message's segment(s)\n *\n * @param {object[]} encodedChars Array of EncodedChar\n * @returns {object[]} Array of Segment\n * @private\n */\n\n _buildSegments(encodedChars: EncodedChars): Segment[] {\n const segments: Segment[] = [];\n segments.push(new Segment());\n let currentSegment = segments[0];\n\n for (const encodedChar of encodedChars) {\n if (currentSegment.freeSizeInBits() < encodedChar.sizeInBits()) {\n segments.push(new Segment(true));\n currentSegment = segments[segments.length - 1];\n const previousSegment = segments[segments.length - 2];\n\n if (!previousSegment.hasUserDataHeader) {\n const removedChars = previousSegment.addHeader();\n // eslint-disable-next-line no-loop-func\n removedChars.forEach((char) => currentSegment.push(char));\n }\n }\n currentSegment.push(encodedChar);\n }\n\n return segments;\n }\n\n /**\n * Return the encoding of the message segment\n *\n * @returns {string} Encoding for the message segment(s)\n */\n getEncodingName(): string {\n return this.encodingName;\n }\n\n /**\n * Internal method to create an array of EncodedChar from a string\n *\n * @param {string[]} graphemes Array of graphemes representing the message\n * @returns {object[]} Array of EncodedChar\n * @private\n */\n _encodeChars(graphemes: string[]): EncodedChars {\n const encodedChars: EncodedChars = [];\n\n for (const grapheme of graphemes) {\n encodedChars.push(new EncodedChar(grapheme, this.encodingName));\n }\n return encodedChars;\n }\n\n /**\n * Internal method to count the total number of code units of the message\n *\n * @param {EncodedChar[]} encodedChars Encoded message body\n * @returns {number} The total number of code units\n * @private\n */\n _countCodeUnits(encodedChars: EncodedChar[]): number {\n return encodedChars.reduce(\n (acumulator: number, nextEncodedChar: EncodedChar) => acumulator + nextEncodedChar.codeUnits.length,\n 0,\n );\n }\n\n /**\n * @returns {number} Total size of the message in bits (including User Data Header if present)\n */\n get totalSize(): number {\n let size = 0;\n for (const segment of this.segments) {\n size += segment.sizeInBits();\n }\n return size;\n }\n\n /**\n * @returns {number} Total size of the message in bits (excluding User Data Header if present)\n */\n get messageSize(): number {\n let size = 0;\n for (const segment of this.segments) {\n size += segment.messageSizeInBits();\n }\n return size;\n }\n\n /**\n *\n * @returns {number} Number of segments\n */\n get segmentsCount(): number {\n return this.segments.length;\n }\n\n /**\n *\n * @returns {string[]} Array of characters representing the non GSM-7 characters in the message body\n */\n getNonGsmCharacters(): string[] {\n return this.encodedChars.filter((encodedChar) => !encodedChar.isGSM7).map((encodedChar) => encodedChar.raw);\n }\n}\n", "import { SegmentedMessage } from './libs/SegmentedMessage';\n\n// eslint-disable-next-line import/no-unused-modules\nexport { SegmentedMessage };\n", "// Entry point for the build script in your package.json\n\nimport Toastify from \"toastify-js\";\n\nimport \"./boot\";\nimport \"./sentry\";\nimport \"./error_notifier\";\nimport \"./extensions/arrays\";\nimport \"./extensions/highlight\";\nimport \"./concerns/spinners\";\nimport \"./utils/elements\";\nimport \"./utils/analytics\";\nimport \"./utils/posthog\";\nimport \"./ui/flash\";\nimport \"./logic/vin\";\nimport \"./forms/editor\";\nimport \"./ui/integration_questionnaire\";\nimport \"./views/upsheet\";\nimport \"./app\";\nimport \"./firebase\";\nimport \"./turbo\";\nimport \"./editor/config/setup\";\nimport \"./upsheets/boot\";\nimport \"./controllers/validator_controller\";\nimport \"./billing/payments\";\nimport \"./forms/contact_editor\";\nimport * as ActiveStorage from \"@rails/activestorage\";\nimport \"rhino-editor\";\nimport { Turbo } from \"@hotwired/turbo-rails\";\nimport \"./controllers\";\nimport fetch from \"@/utils/fetch\";\nimport confirm from \"@/utils/confirm\";\n\nActiveStorage.start();\n\n// Make Toastify available globally\nwindow.Toastify = Toastify;\n\nTurbo.session.drive = false;\nTurbo.config.forms.confirm = confirm;\n\nwindow.addEventListener(\"register-fcm-token\", ({ detail: { token } }) => {\n fetch(\"/fcm_token\", {\n method: \"POST\",\n body: JSON.stringify({ fcm_token: token }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n});\n", "window.UI = {};\nwindow.Views = {};\nif (!window.params) { window.params = {}; }\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 `debug` singleton, 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 { Carrier } from '../carrier';\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport type InternalGlobal = {\n navigator?: { userAgent?: string; maxTouchPoints?: number };\n console: Console;\n PerformanceObserver?: any;\n Sentry?: any;\n onerror?: {\n (event: object | string, source?: string, lineno?: number, colno?: number, error?: Error): any;\n __SENTRY_INSTRUMENTED__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: 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 /**\n * Native debug IDs implementation (e.g., from Vercel).\n * This uses the same format as _sentryDebugIds but with a different global name.\n * Keys are `error.stack` strings, values are debug IDs.\n */\n _debugIds?: Record;\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 _sentryEsmLoaderHookRegistered?: boolean;\n _sentryInjectLoaderHookRegister?: () => void;\n _sentryInjectLoaderHookRegistered?: boolean;\n} & Carrier;\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ = globalThis as unknown as InternalGlobal;\n", "// This is a magic string replaced by rollup\ndeclare const __SENTRY_SDK_VERSION__: string;\n\nexport const SDK_VERSION = typeof __SENTRY_SDK_VERSION__ === 'string' ? __SENTRY_SDK_VERSION__ : '0.0.0-unknown.0';\n", "import type { AsyncContextStack } from './asyncContext/stackStrategy';\nimport type { AsyncContextStrategy } from './asyncContext/types';\nimport type { Client } from './client';\nimport type { Scope } from './scope';\nimport type { SerializedLog } from './types-hoist/log';\nimport type { SerializedMetric } from './types-hoist/metric';\nimport { SDK_VERSION } from './utils/version';\nimport { GLOBAL_OBJ } from './utils/worldwide';\n\n/**\n * An object that contains globally accessible properties and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: VersionedCarrier;\n}\n\ntype VersionedCarrier = {\n version?: string;\n} & Record, SentryCarrier>;\n\nexport interface SentryCarrier {\n acs?: AsyncContextStrategy;\n stack?: AsyncContextStack;\n\n globalScope?: Scope;\n defaultIsolationScope?: Scope;\n defaultCurrentScope?: Scope;\n loggerSettings?: { enabled: boolean };\n /**\n * A map of Sentry clients to their log buffers.\n * This is used to store logs that are sent to Sentry.\n */\n clientToLogBufferMap?: WeakMap>;\n\n /**\n * A map of Sentry clients to their metric buffers.\n * This is used to store metrics that are sent to Sentry.\n */\n clientToMetricBufferMap?: WeakMap>;\n\n /** Overwrites TextEncoder used in `@sentry/core`, need for `react-native@0.73` and older */\n encodePolyfill?: (input: string) => Uint8Array;\n /** Overwrites TextDecoder used in `@sentry/core`, need for `react-native@0.73` and older */\n decodePolyfill?: (input: Uint8Array) => string;\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 // This ensures a Sentry carrier exists\n getSentryCarrier(GLOBAL_OBJ);\n return GLOBAL_OBJ;\n}\n\n/** Will either get the existing sentry carrier, or create a new one. */\nexport function getSentryCarrier(carrier: Carrier): SentryCarrier {\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n\n // For now: First SDK that sets the .version property wins\n __SENTRY__.version = __SENTRY__.version || SDK_VERSION;\n\n // Intentionally populating and returning the version of \"this\" SDK instance\n // rather than what's set in .version so that \"this\" SDK always gets its carrier\n return (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});\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(\n name: Prop,\n creator: () => NonNullable,\n obj = GLOBAL_OBJ,\n): NonNullable {\n const __SENTRY__ = (obj.__SENTRY__ = obj.__SENTRY__ || {});\n const carrier = (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});\n // Note: We do not want to set `carrier.version` here, as this may be called before any `init` is called, e.g. for the default scopes\n return carrier[name] || (carrier[name] = creator());\n}\n", "import { getGlobalSingleton } from '../carrier';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ConsoleLevel } from '../types-hoist/instrument';\nimport { GLOBAL_OBJ } from './worldwide';\n\nexport interface SentryDebugLogger {\n disable(): void;\n enable(): void;\n isEnabled(): boolean;\n log(...args: Parameters): void;\n warn(...args: Parameters): void;\n error(...args: Parameters): void;\n}\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\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\n/** This may be mutated by the console instrumentation. */\nexport const originalConsoleMethods: Partial<{\n log(...args: Parameters): void;\n info(...args: Parameters): void;\n warn(...args: Parameters): void;\n error(...args: Parameters): void;\n debug(...args: Parameters): void;\n assert(...args: Parameters): void;\n trace(...args: Parameters): void;\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;\n const wrappedFuncs: Partial void>> = {};\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];\n wrappedFuncs[level] = console[level] as (...args: unknown[]) => void;\n console[level] = originalConsoleMethod as (...args: unknown[]) => void;\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 (...args: unknown[]) => void;\n });\n }\n}\n\nfunction enable(): void {\n _getLoggerSettings().enabled = true;\n}\n\nfunction disable(): void {\n _getLoggerSettings().enabled = false;\n}\n\nfunction isEnabled(): boolean {\n return _getLoggerSettings().enabled;\n}\n\nfunction log(...args: Parameters): void {\n _maybeLog('log', ...args);\n}\n\nfunction info(...args: Parameters): void {\n _maybeLog('info', ...args);\n}\n\nfunction warn(...args: Parameters): void {\n _maybeLog('warn', ...args);\n}\n\nfunction error(...args: Parameters): void {\n _maybeLog('error', ...args);\n}\n\nfunction _maybeLog(level: ConsoleLevel, ...args: Parameters<(typeof console)[typeof level]>): void {\n if (!DEBUG_BUILD) {\n return;\n }\n\n if (isEnabled()) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[level](`${PREFIX}[${level}]:`, ...args);\n });\n }\n}\n\nfunction _getLoggerSettings(): { enabled: boolean } {\n if (!DEBUG_BUILD) {\n return { enabled: false };\n }\n\n return getGlobalSingleton('loggerSettings', () => ({ enabled: false }));\n}\n\n/**\n * This is a logger singleton which either logs things or no-ops if logging is not enabled.\n */\nexport const debug = {\n /** Enable logging. */\n enable,\n /** Disable logging. */\n disable,\n /** Check if logging is enabled. */\n isEnabled,\n /** Log a message. */\n log,\n /** Log a warning. */\n warn,\n /** Log an error. */\n error,\n} satisfies SentryDebugLogger;\n", "import type { Event } from '../types-hoist/event';\nimport type { StackFrame } from '../types-hoist/stackframe';\nimport type { StackLineParser, StackParser } from '../types-hoist/stacktrace';\nimport type { VNode, VueViewModel } from '../types-hoist/vue';\n\nconst STACKTRACE_FRAME_LIMIT = 50;\nexport const UNKNOWN_FUNCTION = '?';\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, skipFirstLines: number = 0, framesToPop: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirstLines; i < lines.length; i++) {\n let line = lines[i] as string;\n // Truncate lines over 1kb because many of the regular expressions use\n // backtracking which results in run time that increases exponentially\n // with 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 line = line.slice(0, 1024);\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 + framesToPop) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames.slice(framesToPop));\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(getLastStackFrame(localStack).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(getLastStackFrame(localStack).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 scope itself, making it:\n //\n // Sentry.captureException()\n // scope.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(getLastStackFrame(localStack).function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || getLastStackFrame(localStack).filename,\n function: frame.function || UNKNOWN_FUNCTION,\n }));\n}\n\nfunction getLastStackFrame(arr: StackFrame[]): StackFrame {\n return arr[arr.length - 1] || {};\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 {\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 * Get's stack frames from an event without needing to check for undefined properties.\n */\nexport function getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n const frames: StackFrame[] = [];\n try {\n // @ts-expect-error Object could be undefined\n exception.values.forEach(value => {\n // @ts-expect-error Value could be undefined\n if (value.stacktrace.frames) {\n // @ts-expect-error Value could be undefined\n frames.push(...value.stacktrace.frames);\n }\n });\n return frames;\n } catch {\n return undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Get the internal name of an internal Vue value, to represent it in a stacktrace.\n *\n * @param value The value to get the internal name of.\n */\nexport function getVueInternalName(value: VueViewModel | VNode): string {\n // Check if it's a VNode (has __v_isVNode) or a component instance (has _isVue/__isVue)\n const isVNode = '__v_isVNode' in value && value.__v_isVNode;\n\n return isVNode ? '[VueVNode]' : '[VueViewModel]';\n}\n", "import { DEBUG_BUILD } from '../debug-build';\nimport { debug } from '../utils/debug-logger';\nimport { getFunctionName } from '../utils/stacktrace';\n\nexport type InstrumentHandlerType =\n | 'console'\n | 'dom'\n | 'fetch'\n | 'fetch-body-resolved'\n | 'history'\n | 'xhr'\n | 'error'\n | '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].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 instrumented[type] = true;\n try {\n instrumentFn();\n } catch (e) {\n DEBUG_BUILD && debug.error(`Error while instrumenting ${type}`, e);\n }\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 debug.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n", "import type { HandlerDataError } from '../types-hoist/instrument';\nimport { GLOBAL_OBJ } from '../utils/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 // Note: The reason we are doing window.onerror instead of window.addEventListener('error')\n // is that we are using this handler in the Loader Script, to handle buffered errors consistently\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) {\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", "import type { HandlerDataUnhandledRejection } from '../types-hoist/instrument';\nimport { GLOBAL_OBJ } from '../utils/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 // Note: The reason we are doing window.onunhandledrejection instead of window.addEventListener('unhandledrejection')\n // is that we are using this handler in the Loader Script, to handle buffered rejections consistently\n GLOBAL_OBJ.onunhandledrejection = function (e: unknown): boolean {\n const handlerData: HandlerDataUnhandledRejection = e;\n triggerHandlers('unhandledrejection', handlerData);\n\n if (_oldOnUnhandledRejectionHandler) {\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-explicit-any */\n\nimport type { Primitive } from '../types-hoist/misc';\nimport type { ParameterizedString } from '../types-hoist/parameterize';\nimport type { PolymorphicEvent } from '../types-hoist/polymorphics';\nimport type { VNode, VueViewModel } from '../types-hoist/vue';\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 case '[object WebAssembly.Exception]':\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?.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'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 {\n return false;\n }\n}\n\n/**\n * Checks whether given value's type is a Vue ViewModel or a VNode.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isVueViewModel(wat: unknown): wat is VueViewModel | VNode {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n // We also need to check for __v_isVNode because Vue 3 component render instances have an internal __v_isVNode property.\n return !!(\n typeof wat === 'object' &&\n wat !== null &&\n ((wat as VueViewModel).__isVue || (wat as VueViewModel)._isVue || (wat as { __v_isVNode?: boolean }).__v_isVNode)\n );\n}\n\n/**\n * Checks whether the given parameter is a Standard Web API Request instance.\n *\n * Returns false if Request is not available in the current runtime.\n */\nexport function isRequest(request: unknown): request is Request {\n return typeof Request !== 'undefined' && isInstanceOf(request, Request);\n}\n", "import { isString } from './is';\nimport { GLOBAL_OBJ } from './worldwide';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\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 {\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\n if (!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) {\n if (elem.dataset['sentryComponent']) {\n return elem.dataset['sentryComponent'];\n }\n if (elem.dataset['sentryElement']) {\n return elem.dataset['sentryElement'];\n }\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 = keyAttrs?.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (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 const className = elem.className;\n if (className && isString(className)) {\n const classes = className.split(/\\s+/);\n for (const c of classes) {\n out.push(`.${c}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (const k of allowedAttrs) {\n const attr = elem.getAttribute(k);\n if (attr) {\n out.push(`[${k}=\"${attr}\"]`);\n }\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 {\n return '';\n }\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` or `data-sentry-element` attribute with `data-sentry-component` taking\n * precedence. This attribute is added at build-time 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) {\n if (currentElem.dataset['sentryComponent']) {\n return currentElem.dataset['sentryComponent'];\n }\n if (currentElem.dataset['sentryElement']) {\n return currentElem.dataset['sentryElement'];\n }\n }\n\n currentElem = currentElem.parentNode;\n }\n\n return null;\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { WrappedFunction } from '../types-hoist/wrappedfunction';\nimport { htmlTreeAsString } from './browser';\nimport { debug } from './debug-logger';\nimport { isElement, isError, isEvent, isInstanceOf, isPrimitive } from './is';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * If the method on the passed object is not a function, the wrapper will not be applied.\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 // explicitly casting to unknown because we don't know the type of the method initially at all\n const original = source[name] as unknown;\n\n if (typeof original !== 'function') {\n return;\n }\n\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 try {\n source[name] = wrapped;\n } catch {\n DEBUG_BUILD && debug.log(`Failed to replace method \"${name}\" in object`, source);\n }\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 {\n DEBUG_BUILD && debug.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 {} // 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 */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function getOriginalFunction(func: WrappedFunction): T | undefined {\n return func.__sentry_original__;\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 argument itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject(value: V):\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 {\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): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n return !keys[0] ? '[object has no keys]' : keys.join(', ');\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 *\n * @deprecated This function is no longer used by the SDK and will be removed in a future major version.\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 // Early return for primitive values\n if (inputValue === null || typeof inputValue !== 'object') {\n return inputValue;\n }\n\n // Check memo map first for all object types\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n // handle arrays\n if (Array.isArray(inputValue)) {\n const returnValue: unknown[] = [];\n // Store mapping to handle circular references\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach(value => {\n returnValue.push(_dropUndefinedKeys(value, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n if (isPojo(inputValue)) {\n const returnValue: { [key: string]: unknown } = {};\n // Store mapping to handle circular references\n memoizationMap.set(inputValue, returnValue);\n\n const keys = Object.keys(inputValue);\n\n keys.forEach(key => {\n const val = inputValue[key];\n if (val !== undefined) {\n returnValue[key] = _dropUndefinedKeys(val, memoizationMap);\n }\n });\n\n return returnValue as T;\n }\n\n // For other object types, return as is\n return inputValue;\n}\n\nfunction isPojo(input: unknown): input is Record {\n // Plain objects have Object as constructor or no constructor\n const constructor = (input as object).constructor;\n return constructor === Object || constructor === undefined;\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 // this will catch both undefined and null\n case wat == undefined:\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", "import { isRegExp, isString, isVueViewModel } from './is';\nimport { getVueInternalName } from './stacktrace';\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 */\nexport function safeJoin(input: unknown[], 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(getVueInternalName(value));\n } else {\n output.push(String(value));\n }\n } catch {\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", "import type { Event } from '../types-hoist/event';\nimport type { Exception } from '../types-hoist/exception';\nimport type { Mechanism } from '../types-hoist/mechanism';\nimport type { StackFrame } from '../types-hoist/stackframe';\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\nfunction getCrypto(): CryptoInternal | undefined {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n return gbl.crypto || gbl.msCrypto;\n}\n\nlet emptyUuid: string | undefined;\n\nfunction getRandomByte(): number {\n return Math.random() * 16;\n}\n\n/**\n * UUID4 generator\n * @param crypto Object that provides the crypto API.\n * @returns string Generated UUID4.\n */\nexport function uuid4(crypto = getCrypto()): string {\n try {\n if (crypto?.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n } catch {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n if (!emptyUuid) {\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 emptyUuid = ([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11;\n }\n\n return emptyUuid.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?.values?.[0];\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?.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\nfunction _parseInt(input: string | undefined): number {\n return parseInt(input || '', 10);\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]);\n const minor = _parseInt(match[2]);\n const patch = _parseInt(match[3]);\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 // We guard here to ensure this is not larger than the existing number of lines\n const lineIndex = Math.min(maxLines - 1, sourceLine);\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n frame.context_line = snipLine(lines[lineIndex]!, 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 if (isAlreadyCaptured(exception)) {\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 {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\nfunction isAlreadyCaptured(exception: unknown): boolean | void {\n try {\n return (exception as { __sentry_captured__?: boolean }).__sentry_captured__;\n } catch {} // eslint-disable-line no-empty\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 */\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 // Some browser and environments don't have a performance or timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n if (!performance?.now || !performance.timeOrigin) {\n return dateTimestampInSeconds;\n }\n\n const timeOrigin = 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\nlet _cachedTimestampInSeconds: (() => number) | undefined;\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 function timestampInSeconds(): number {\n // We store this in a closure so that we don't have to create a new function every time this is called.\n const func = _cachedTimestampInSeconds ?? (_cachedTimestampInSeconds = createUnixTimestampInSecondsFunc());\n return func();\n}\n\n/**\n * Cached result of getBrowserTimeOrigin.\n */\nlet cachedTimeOrigin: [number | undefined, string] | undefined;\n\n/**\n * Gets the time origin and the mode used to determine it.\n */\nfunction getBrowserTimeOrigin(): [number | undefined, string] {\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?.now) {\n return [undefined, 'none'];\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?.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 return [performance.timeOrigin, 'timeOrigin'];\n } else {\n return [navigationStart, 'navigationStart'];\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n return [dateNow, 'dateNow'];\n}\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 function browserPerformanceTimeOrigin(): number | undefined {\n if (!cachedTimeOrigin) {\n cachedTimeOrigin = getBrowserTimeOrigin();\n }\n\n return cachedTimeOrigin[0];\n}\n", "import type { SerializedSession, Session, SessionContext, SessionStatus } from './types-hoist/session';\nimport { uuid4 } from './utils/misc';\nimport { timestampInSeconds } from './utils/time';\n\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 Client.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 {\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", "/**\n * Shallow merge two objects.\n * Does not mutate the passed in objects.\n * Undefined/empty values in the merge object will overwrite existing values.\n *\n * By default, this merges 2 levels deep.\n */\nexport function merge(initialObj: T, mergeObj: T, levels = 2): T {\n // If the merge value is not an object, or we have no merge levels left,\n // we just set the value to the merge value\n if (!mergeObj || typeof mergeObj !== 'object' || levels <= 0) {\n return mergeObj;\n }\n\n // If the merge object is an empty object, and the initial object is not undefined, we return the initial object\n if (initialObj && Object.keys(mergeObj).length === 0) {\n return initialObj;\n }\n\n // Clone object\n const output = { ...initialObj };\n\n // Merge values into output, resursively\n for (const key in mergeObj) {\n if (Object.prototype.hasOwnProperty.call(mergeObj, key)) {\n output[key] = merge(output[key], mergeObj[key], levels - 1);\n }\n }\n\n return output;\n}\n", "import { uuid4 } from './misc';\n\n/**\n * Generate a random, valid trace ID.\n */\nexport function generateTraceId(): string {\n return uuid4();\n}\n\n/**\n * Generate a random, valid span ID.\n */\nexport function generateSpanId(): string {\n return uuid4().substring(16);\n}\n", "import type { Scope } from '../scope';\nimport type { Span } from '../types-hoist/span';\nimport { addNonEnumerableProperty } from '../utils/object';\n\nconst SCOPE_SPAN_FIELD = '_sentrySpan';\n\ntype ScopeWithMaybeSpan = Scope & {\n [SCOPE_SPAN_FIELD]?: Span;\n};\n\n/**\n * Set the active span for a given scope.\n * NOTE: This should NOT be used directly, but is only used internally by the trace methods.\n */\nexport function _setSpanForScope(scope: Scope, span: Span | undefined): void {\n if (span) {\n addNonEnumerableProperty(scope as ScopeWithMaybeSpan, SCOPE_SPAN_FIELD, span);\n } else {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete (scope as ScopeWithMaybeSpan)[SCOPE_SPAN_FIELD];\n }\n}\n\n/**\n * Get the active span for a given scope.\n * NOTE: This should NOT be used directly, but is only used internally by the trace methods.\n */\nexport function _getSpanForScope(scope: ScopeWithMaybeSpan): Span | undefined {\n return scope[SCOPE_SPAN_FIELD];\n}\n", "/* eslint-disable max-lines */\nimport type { AttributeObject, RawAttribute, RawAttributes } from './attributes';\nimport type { Client } from './client';\nimport { DEBUG_BUILD } from './debug-build';\nimport { updateSession } from './session';\nimport type { Attachment } from './types-hoist/attachment';\nimport type { Breadcrumb } from './types-hoist/breadcrumb';\nimport type { Context, Contexts } from './types-hoist/context';\nimport type { DynamicSamplingContext } from './types-hoist/envelope';\nimport type { Event, EventHint } from './types-hoist/event';\nimport type { EventProcessor } from './types-hoist/eventprocessor';\nimport type { Extra, Extras } from './types-hoist/extra';\nimport type { Primitive } from './types-hoist/misc';\nimport type { RequestEventData } from './types-hoist/request';\nimport type { Session } from './types-hoist/session';\nimport type { SeverityLevel } from './types-hoist/severity';\nimport type { Span } from './types-hoist/span';\nimport type { PropagationContext } from './types-hoist/tracing';\nimport type { User } from './types-hoist/user';\nimport { debug } from './utils/debug-logger';\nimport { isPlainObject } from './utils/is';\nimport { merge } from './utils/merge';\nimport { uuid4 } from './utils/misc';\nimport { generateTraceId } from './utils/propagationContext';\nimport { _getSpanForScope, _setSpanForScope } from './utils/spanOnScope';\nimport { truncate } from './utils/string';\nimport { dateTimestampInSeconds } from './utils/time';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * A context to be used for capturing an event.\n * This can either be a Scope, or a partial ScopeContext,\n * or a callback that receives the current scope and returns a new scope to use.\n */\nexport type CaptureContext = Scope | Partial | ((scope: Scope) => Scope);\n\n/**\n * Data that can be converted to a Scope.\n */\nexport interface ScopeContext {\n user: User;\n level: SeverityLevel;\n extra: Extras;\n contexts: Contexts;\n tags: { [key: string]: Primitive };\n attributes?: RawAttributes>;\n fingerprint: string[];\n propagationContext: PropagationContext;\n}\n\nexport interface SdkProcessingMetadata {\n [key: string]: unknown;\n requestSession?: {\n status: 'ok' | 'errored' | 'crashed';\n };\n normalizedRequest?: RequestEventData;\n dynamicSamplingContext?: Partial;\n capturedSpanScope?: Scope;\n capturedSpanIsolationScope?: Scope;\n spanCountBeforeProcessing?: number;\n ipAddress?: string;\n}\n\n/**\n * Normalized data of the Scope, ready to be used.\n */\nexport interface ScopeData {\n eventProcessors: EventProcessor[];\n breadcrumbs: Breadcrumb[];\n user: User;\n tags: { [key: string]: Primitive };\n // TODO(v11): Make this a required field (could be subtly breaking if we did it today)\n attributes?: RawAttributes>;\n extra: Extras;\n contexts: Contexts;\n attachments: Attachment[];\n propagationContext: PropagationContext;\n sdkProcessingMetadata: SdkProcessingMetadata;\n fingerprint: string[];\n level?: SeverityLevel;\n transactionName?: string;\n span?: Span;\n}\n\n/**\n * Holds additional event information.\n */\nexport class Scope {\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 during event processing. */\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 /** Attributes */\n protected _attributes: RawAttributes>;\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: SdkProcessingMetadata;\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n protected _level?: SeverityLevel;\n\n /**\n * Transaction Name\n *\n * IMPORTANT: The transaction name on the scope has nothing to do with root spans/transaction objects.\n * It's purpose is to assign a transaction to the scope that's added to non-transaction events.\n */\n protected _transactionName?: string;\n\n /** Session */\n protected _session?: Session;\n\n /** The client on this scope */\n protected _client?: Client;\n\n /** Contains the last event id of a captured event. */\n protected _lastEventId?: string;\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._attributes = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = {\n traceId: generateTraceId(),\n sampleRand: Math.random(),\n };\n }\n\n /**\n * Clone all data from this scope into a new scope.\n */\n public clone(): Scope {\n const newScope = new Scope();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._attributes = { ...this._attributes };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n if (this._contexts.flags) {\n // We need to copy the `values` array so insertions on a cloned scope\n // won't affect the original array.\n newScope._contexts.flags = {\n values: [...this._contexts.flags.values],\n };\n }\n\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n newScope._lastEventId = this._lastEventId;\n\n _setSpanForScope(newScope, _getSpanForScope(this));\n\n return newScope;\n }\n\n /**\n * Update the client assigned to this scope.\n * Note that not every scope will have a client assigned - isolation scopes & the global scope will generally not have a client,\n * as well as manually created scopes.\n */\n public setClient(client: Client | undefined): void {\n this._client = client;\n }\n\n /**\n * Set the ID of the last captured error event.\n * This is generally only captured on the isolation scope.\n */\n public setLastEventId(lastEventId: string | undefined): void {\n this._lastEventId = lastEventId;\n }\n\n /**\n * Get the client assigned to this scope.\n */\n public getClient(): C | undefined {\n return this._client as C | undefined;\n }\n\n /**\n * Get the ID of the last captured error event.\n * This is generally only available on the isolation scope.\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * Add an event processor that will be called before an event is sent.\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * Set the user for this scope.\n * Set to `null` to unset the user.\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 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 * Get the user from this scope.\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * Set an object that will be merged into existing tags on the scope,\n * and will be sent as tags data with the event.\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 * Set a single tag that will be sent as tags data with the event.\n */\n public setTag(key: string, value: Primitive): this {\n return this.setTags({ [key]: value });\n }\n\n /**\n * Sets attributes onto the scope.\n *\n * TODO:\n * Currently, these attributes are not applied to any telemetry data but they will be in the future.\n *\n * @param newAttributes - The attributes to set on the scope. You can either pass in key-value pairs, or\n * an object with a `value` and an optional `unit` (if applicable to your attribute).\n *\n * @example\n * ```typescript\n * scope.setAttributes({\n * is_admin: true,\n * payment_selection: 'credit_card',\n * clicked_products: [130, 554, 292],\n * render_duration: { value: 'render_duration', unit: 'ms' },\n * });\n * ```\n */\n public setAttributes>(newAttributes: RawAttributes): this {\n this._attributes = {\n ...this._attributes,\n ...newAttributes,\n };\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets an attribute onto the scope.\n *\n * TODO:\n * Currently, these attributes are not applied to any telemetry data but they will be in the future.\n *\n * @param key - The attribute key.\n * @param value - the attribute value. You can either pass in a raw value, or an attribute\n * object with a `value` and an optional `unit` (if applicable to your attribute).\n *\n * @example\n * ```typescript\n * scope.setAttribute('is_admin', true);\n * scope.setAttribute('clicked_products', [130, 554, 292]);\n * scope.setAttribute('render_duration', { value: 'render_duration', unit: 'ms' });\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setAttribute extends { value: any } | { unit: any } ? AttributeObject : unknown>(\n key: string,\n value: RawAttribute,\n ): this {\n return this.setAttributes({ [key]: value });\n }\n\n /**\n * Removes the attribute with the given key from the scope.\n *\n * @param key - The attribute key.\n *\n * @example\n * ```typescript\n * scope.removeAttribute('is_admin');\n * ```\n */\n public removeAttribute(key: string): this {\n if (key in this._attributes) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._attributes[key];\n this._notifyScopeListeners();\n }\n return this;\n }\n\n /**\n * Set an object that will be merged into existing extra on the scope,\n * and will be sent as extra data with the event.\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 * Set a single key:value extra entry that will be sent as extra data with the event.\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 * Sets the fingerprint on the scope to send with the events.\n * @param {string[]} fingerprint Fingerprint to group events in Sentry.\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the level on the scope for future events.\n */\n public setLevel(level: SeverityLevel): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the transaction name on the scope so that the name of e.g. taken server route or\n * the page location is attached to future events.\n *\n * IMPORTANT: Calling this function does NOT change the name of the currently active\n * root span. If you want to change the name of the active root span, use\n * `Sentry.updateSpanName(rootSpan, 'new name')` instead.\n *\n * By default, the SDK updates the scope's transaction name automatically on sensible\n * occasions, such as a page navigation or when handling a new request on the server.\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets context data with the given name.\n * Data passed as context will be normalized. You can also pass `null` to unset the context.\n * Note that context data will not be merged - calling `setContext` will overwrite an existing context with the same key.\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 * Set the session for the scope.\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 * Get the session from the scope.\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * Updates the scope with provided data. Can work in three variations:\n * - plain object containing updatable attributes\n * - Scope instance that'll extract the attributes from\n * - callback function that'll receive the current scope as an argument and allow for modifications\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 const scopeInstance =\n scopeToMerge instanceof Scope\n ? scopeToMerge.getScopeData()\n : isPlainObject(scopeToMerge)\n ? (captureContext as ScopeContext)\n : undefined;\n\n const {\n tags,\n attributes,\n extra,\n user,\n contexts,\n level,\n fingerprint = [],\n propagationContext,\n } = scopeInstance || {};\n\n this._tags = { ...this._tags, ...tags };\n this._attributes = { ...this._attributes, ...attributes };\n this._extra = { ...this._extra, ...extra };\n this._contexts = { ...this._contexts, ...contexts };\n\n if (user && Object.keys(user).length) {\n this._user = user;\n }\n\n if (level) {\n this._level = level;\n }\n\n if (fingerprint.length) {\n this._fingerprint = fingerprint;\n }\n\n if (propagationContext) {\n this._propagationContext = propagationContext;\n }\n\n return this;\n }\n\n /**\n * Clears the current scope and resets its properties.\n * Note: The client will not be cleared.\n */\n public clear(): this {\n // client is not cleared here on purpose!\n this._breadcrumbs = [];\n this._tags = {};\n this._attributes = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._session = undefined;\n _setSpanForScope(this, undefined);\n this._attachments = [];\n this.setPropagationContext({ traceId: generateTraceId(), sampleRand: Math.random() });\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Adds a breadcrumb to the scope.\n * By default, the last 100 breadcrumbs are kept.\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: Breadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n // Breadcrumb messages can theoretically be infinitely large and they're held in memory so we truncate them not to leak (too much) memory\n message: breadcrumb.message ? truncate(breadcrumb.message, 2048) : breadcrumb.message,\n };\n\n this._breadcrumbs.push(mergedBreadcrumb);\n if (this._breadcrumbs.length > maxCrumbs) {\n this._breadcrumbs = this._breadcrumbs.slice(-maxCrumbs);\n this._client?.recordDroppedEvent('buffer_overflow', 'log_item');\n }\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * Get the last breadcrumb of the scope.\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * Clear all breadcrumbs from the scope.\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Add an attachment to the scope.\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * Clear all attachments from the scope.\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /**\n * Get the data of this scope, which should be applied to an event during processing.\n */\n public getScopeData(): ScopeData {\n return {\n breadcrumbs: this._breadcrumbs,\n attachments: this._attachments,\n contexts: this._contexts,\n tags: this._tags,\n attributes: this._attributes,\n extra: this._extra,\n user: this._user,\n level: this._level,\n fingerprint: this._fingerprint || [],\n eventProcessors: this._eventProcessors,\n propagationContext: this._propagationContext,\n sdkProcessingMetadata: this._sdkProcessingMetadata,\n transactionName: this._transactionName,\n span: _getSpanForScope(this),\n };\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: SdkProcessingMetadata): this {\n this._sdkProcessingMetadata = merge(this._sdkProcessingMetadata, newData, 2);\n return this;\n }\n\n /**\n * Add propagation context to the scope, used for distributed tracing\n */\n public setPropagationContext(context: PropagationContext): this {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * Get propagation context from the scope, used for distributed tracing\n */\n public getPropagationContext(): PropagationContext {\n return this._propagationContext;\n }\n\n /**\n * Capture an exception for this scope.\n *\n * @returns {string} The id of the captured Sentry event.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = hint?.event_id || uuid4();\n\n if (!this._client) {\n DEBUG_BUILD && debug.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 * @returns {string} The id of the captured message.\n */\n public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string {\n const eventId = hint?.event_id || uuid4();\n\n if (!this._client) {\n DEBUG_BUILD && debug.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = hint?.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 * Capture a Sentry event for this scope.\n *\n * @returns {string} The id of the captured event.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint?.event_id || uuid4();\n\n if (!this._client) {\n DEBUG_BUILD && debug.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", "import { getGlobalSingleton } from './carrier';\nimport { Scope } from './scope';\n\n/** Get the default current scope. */\nexport function getDefaultCurrentScope(): Scope {\n return getGlobalSingleton('defaultCurrentScope', () => new Scope());\n}\n\n/** Get the default isolation scope. */\nexport function getDefaultIsolationScope(): Scope {\n return getGlobalSingleton('defaultIsolationScope', () => new Scope());\n}\n", "import type { Client } from '../client';\nimport { getDefaultCurrentScope, getDefaultIsolationScope } from '../defaultScopes';\nimport { Scope } from '../scope';\nimport { isThenable } from '../utils/is';\nimport { getMainCarrier, getSentryCarrier } from './../carrier';\nimport type { AsyncContextStrategy } from './types';\n\ninterface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * This is an object that holds a stack of scopes.\n */\nexport class AsyncContextStack {\n private readonly _stack: [Layer, ...Layer[]];\n private _isolationScope: Scope;\n\n public constructor(scope?: Scope, isolationScope?: Scope) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n // scope stack for domains or the process\n this._stack = [{ scope: assignedScope }];\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Fork a scope for the stack.\n */\n public withScope(callback: (scope: Scope) => T): T {\n const scope = this._pushScope();\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\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 this._popScope();\n return res;\n },\n e => {\n this._popScope();\n throw e;\n },\n );\n }\n\n this._popScope();\n return maybePromiseResult;\n }\n\n /**\n * Get the client of the stack.\n */\n public getClient(): C | undefined {\n return this.getStackTop().client as C;\n }\n\n /**\n * Returns the scope of the top stack.\n */\n public getScope(): Scope {\n return this.getStackTop().scope;\n }\n\n /**\n * Get the isolation scope for the stack.\n */\n public getIsolationScope(): Scope {\n return this._isolationScope;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1] as Layer;\n }\n\n /**\n * Push a scope to the stack.\n */\n private _pushScope(): Scope {\n // We want to clone the content of prev scope\n const scope = this.getScope().clone();\n this._stack.push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * Pop a scope from the stack.\n */\n private _popScope(): boolean {\n if (this._stack.length <= 1) return false;\n return !!this._stack.pop();\n }\n}\n\n/**\n * Get the global async context stack.\n * This will be removed during the v8 cycle and is only here to make migration easier.\n */\nfunction getAsyncContextStack(): AsyncContextStack {\n const registry = getMainCarrier();\n const sentry = getSentryCarrier(registry);\n\n return (sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope()));\n}\n\nfunction withScope(callback: (scope: Scope) => T): T {\n return getAsyncContextStack().withScope(callback);\n}\n\nfunction withSetScope(scope: Scope, callback: (scope: Scope) => T): T {\n const stack = getAsyncContextStack();\n return stack.withScope(() => {\n stack.getStackTop().scope = scope;\n return callback(scope);\n });\n}\n\nfunction withIsolationScope(callback: (isolationScope: Scope) => T): T {\n return getAsyncContextStack().withScope(() => {\n return callback(getAsyncContextStack().getIsolationScope());\n });\n}\n\n/**\n * Get the stack-based async context strategy.\n */\nexport function getStackAsyncContextStrategy(): AsyncContextStrategy {\n return {\n withIsolationScope,\n withScope,\n withSetScope,\n withSetIsolationScope: (_isolationScope: Scope, callback: (isolationScope: Scope) => T) => {\n return withIsolationScope(callback);\n },\n getCurrentScope: () => getAsyncContextStack().getScope(),\n getIsolationScope: () => getAsyncContextStack().getIsolationScope(),\n };\n}\n", "import type { Carrier } from './../carrier';\nimport { getMainCarrier, getSentryCarrier } from './../carrier';\nimport { getStackAsyncContextStrategy } from './stackStrategy';\nimport type { AsyncContextStrategy } from './types';\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 const sentry = getSentryCarrier(registry);\n sentry.acs = strategy;\n}\n\n/**\n * Get the current async context strategy.\n * If none has been setup, the default will be used.\n */\nexport function getAsyncContextStrategy(carrier: Carrier): AsyncContextStrategy {\n const sentry = getSentryCarrier(carrier);\n\n if (sentry.acs) {\n return sentry.acs;\n }\n\n // Otherwise, use the default one (stack)\n return getStackAsyncContextStrategy();\n}\n", "import { getAsyncContextStrategy } from './asyncContext';\nimport { getGlobalSingleton, getMainCarrier } from './carrier';\nimport type { Client } from './client';\nimport { Scope } from './scope';\nimport type { TraceContext } from './types-hoist/context';\nimport { generateSpanId } from './utils/propagationContext';\n\n/**\n * Get the currently active scope.\n */\nexport function getCurrentScope(): Scope {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n return acs.getCurrentScope();\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current execution context.\n */\nexport function getIsolationScope(): Scope {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n return acs.getIsolationScope();\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nexport function getGlobalScope(): Scope {\n return getGlobalSingleton('globalScope', () => new Scope());\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 */\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: Scope | 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: Scope | undefined, callback: (scope: Scope) => T]\n): T {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\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\n if (!scope) {\n return acs.withScope(callback);\n }\n\n return acs.withSetScope(scope, callback);\n }\n\n return acs.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 */\nexport function withIsolationScope(callback: (isolationScope: Scope) => T): T;\n/**\n * Set the provided isolation scope as active in the given callback. 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 * If you pass in `undefined` as a scope, it will fork a new isolation scope, the same as if no scope is passed.\n */\nexport function withIsolationScope(isolationScope: Scope | undefined, callback: (isolationScope: Scope) => T): T;\n/**\n * Either creates a new active isolation scope, or sets the given isolation scope as active scope in the given callback.\n */\nexport function withIsolationScope(\n ...rest:\n | [callback: (isolationScope: Scope) => T]\n | [isolationScope: Scope | undefined, callback: (isolationScope: Scope) => T]\n): T {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\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 [isolationScope, callback] = rest;\n\n if (!isolationScope) {\n return acs.withIsolationScope(callback);\n }\n\n return acs.withSetIsolationScope(isolationScope, callback);\n }\n\n return acs.withIsolationScope(rest[0]);\n}\n\n/**\n * Get the currently active client.\n */\nexport function getClient(): C | undefined {\n return getCurrentScope().getClient();\n}\n\n/**\n * Get a trace context for the given scope.\n */\nexport function getTraceContextFromScope(scope: Scope): TraceContext {\n const propagationContext = scope.getPropagationContext();\n\n const { traceId, parentSpanId, propagationSpanId } = propagationContext;\n\n const traceContext: TraceContext = {\n trace_id: traceId,\n span_id: propagationSpanId || generateSpanId(),\n };\n\n if (parentSpanId) {\n traceContext.parent_span_id = parentSpanId;\n }\n\n return traceContext;\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 * Attributes that holds the sample rate that was locally applied to a span.\n * If this attribute is not defined, it means that the span inherited a sampling decision.\n *\n * NOTE: Is only defined on root spans.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';\n\n/**\n * Attribute holding the sample rate of the previous trace.\n * This is used to sample consistently across subsequent traces in the browser SDK.\n *\n * Note: Only defined on root spans, if opted into consistent sampling\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE = 'sentry.previous_trace_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/** The reason why an idle span finished. */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON = 'sentry.idle_span_finish_reason';\n\n/** The unit of a measurement, which may be stored as a TimedEvent. */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = 'sentry.measurement_unit';\n\n/** The value of a measurement, which may be stored as a TimedEvent. */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = 'sentry.measurement_value';\n\n/**\n * A custom span name set by users guaranteed to be taken over any automatically\n * inferred name. This attribute is removed before the span is sent.\n *\n * @internal only meant for internal SDK usage\n * @hidden\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = 'sentry.custom_span_name';\n\n/**\n * The id of the profile that this span occurred in.\n */\nexport const SEMANTIC_ATTRIBUTE_PROFILE_ID = 'sentry.profile_id';\n\nexport const SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = 'sentry.exclusive_time';\n\nexport const SEMANTIC_ATTRIBUTE_CACHE_HIT = 'cache.hit';\n\nexport const SEMANTIC_ATTRIBUTE_CACHE_KEY = 'cache.key';\n\nexport const SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE = 'cache.item_size';\n\n/** TODO: Remove these once we update to latest semantic conventions */\nexport const SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD = 'http.request.method';\nexport const SEMANTIC_ATTRIBUTE_URL_FULL = 'url.full';\n\n/**\n * A span link attribute to mark the link as a special span link.\n *\n * Known values:\n * - `previous_trace`: The span links to the frontend root span of the previous trace.\n * - `next_trace`: The span links to the frontend root span of the next trace. (Not set by the SDK)\n *\n * Other values may be set as appropriate.\n * @see https://develop.sentry.dev/sdk/telemetry/traces/span-links/#link-types\n */\nexport const SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE = 'sentry.link.type';\n", "import type { Span } from '../types-hoist/span';\nimport type { SpanStatus } from '../types-hoist/spanStatus';\n\nexport const SPAN_STATUS_UNSET = 0;\nexport const SPAN_STATUS_OK = 1;\nexport const SPAN_STATUS_ERROR = 2;\n\n/**\n * Converts a HTTP status code into a sentry status with a message.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or internal_error.\n */\n// https://develop.sentry.dev/sdk/event-payloads/span/\nexport function getSpanStatusFromHttpCode(httpStatus: number): SpanStatus {\n if (httpStatus < 400 && httpStatus >= 100) {\n return { code: SPAN_STATUS_OK };\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return { code: SPAN_STATUS_ERROR, message: 'unauthenticated' };\n case 403:\n return { code: SPAN_STATUS_ERROR, message: 'permission_denied' };\n case 404:\n return { code: SPAN_STATUS_ERROR, message: 'not_found' };\n case 409:\n return { code: SPAN_STATUS_ERROR, message: 'already_exists' };\n case 413:\n return { code: SPAN_STATUS_ERROR, message: 'failed_precondition' };\n case 429:\n return { code: SPAN_STATUS_ERROR, message: 'resource_exhausted' };\n case 499:\n return { code: SPAN_STATUS_ERROR, message: 'cancelled' };\n default:\n return { code: SPAN_STATUS_ERROR, message: 'invalid_argument' };\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return { code: SPAN_STATUS_ERROR, message: 'unimplemented' };\n case 503:\n return { code: SPAN_STATUS_ERROR, message: 'unavailable' };\n case 504:\n return { code: SPAN_STATUS_ERROR, message: 'deadline_exceeded' };\n default:\n return { code: SPAN_STATUS_ERROR, message: 'internal_error' };\n }\n }\n\n return { code: SPAN_STATUS_ERROR, message: 'internal_error' };\n}\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 span.setAttribute('http.response.status_code', httpStatus);\n\n const spanStatus = getSpanStatusFromHttpCode(httpStatus);\n if (spanStatus.message !== 'unknown_error') {\n span.setStatus(spanStatus);\n }\n}\n", "import type { Scope } from '../scope';\nimport type { Span } from '../types-hoist/span';\nimport { addNonEnumerableProperty } from '../utils/object';\nimport { GLOBAL_OBJ } from '../utils/worldwide';\n\nconst SCOPE_ON_START_SPAN_FIELD = '_sentryScope';\nconst ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';\n\ntype ScopeWeakRef = { deref(): Scope | undefined } | Scope;\n\ntype SpanWithScopes = Span & {\n [SCOPE_ON_START_SPAN_FIELD]?: Scope;\n [ISOLATION_SCOPE_ON_START_SPAN_FIELD]?: ScopeWeakRef;\n};\n\n/** Wrap a scope with a WeakRef if available, falling back to a direct scope. */\nfunction wrapScopeWithWeakRef(scope: Scope): ScopeWeakRef {\n try {\n // @ts-expect-error - WeakRef is not available in all environments\n const WeakRefClass = GLOBAL_OBJ.WeakRef;\n if (typeof WeakRefClass === 'function') {\n return new WeakRefClass(scope);\n }\n } catch {\n // WeakRef not available or failed to create\n // We'll fall back to a direct scope\n }\n\n return scope;\n}\n\n/** Try to unwrap a scope from a potential WeakRef wrapper. */\nfunction unwrapScopeFromWeakRef(scopeRef: ScopeWeakRef | undefined): Scope | undefined {\n if (!scopeRef) {\n return undefined;\n }\n\n if (typeof scopeRef === 'object' && 'deref' in scopeRef && typeof scopeRef.deref === 'function') {\n try {\n return scopeRef.deref();\n } catch {\n return undefined;\n }\n }\n\n // Fallback to a direct scope\n return scopeRef as Scope;\n}\n\n/** Store the scope & isolation scope for a span, which can the be used when it is finished. */\nexport function setCapturedScopesOnSpan(span: Span | undefined, scope: Scope, isolationScope: Scope): void {\n if (span) {\n addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, wrapScopeWithWeakRef(isolationScope));\n // We don't wrap the scope with a WeakRef here because webkit aggressively garbage collects\n // and scopes are not held in memory for long periods of time.\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 * If WeakRef was used and scopes have been garbage collected, returns undefined for those scopes.\n */\nexport function getCapturedScopesOnSpan(span: Span): { scope?: Scope; isolationScope?: Scope } {\n const spanWithScopes = span as SpanWithScopes;\n\n return {\n scope: spanWithScopes[SCOPE_ON_START_SPAN_FIELD],\n isolationScope: unwrapScopeFromWeakRef(spanWithScopes[ISOLATION_SCOPE_ON_START_SPAN_FIELD]),\n };\n}\n", "import { DEBUG_BUILD } from '../debug-build';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport { debug } from './debug-logger';\nimport { isString } from './is';\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 const baggageObject = parseBaggageHeader(baggageHeader);\n\n if (!baggageObject) {\n return undefined;\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 * Take a baggage header and parse it into an object.\n */\nexport function parseBaggageHeader(\n baggageHeader: string | string[] | number | null | undefined | boolean,\n): Record | undefined {\n if (!baggageHeader || (!isString(baggageHeader) && !Array.isArray(baggageHeader))) {\n return undefined;\n }\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 return baggageHeader.reduce>((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n Object.entries(currBaggageObject).forEach(([key, value]) => {\n acc[key] = value;\n });\n return acc;\n }, {});\n }\n\n return baggageHeaderToObject(baggageHeader);\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 => {\n const eqIdx = baggageEntry.indexOf('=');\n if (eqIdx === -1) {\n // Likely an invalid entry\n return [];\n }\n const key = baggageEntry.slice(0, eqIdx);\n const value = baggageEntry.slice(eqIdx + 1);\n return [key, value].map(keyOrValue => {\n try {\n return decodeURIComponent(keyOrValue.trim());\n } catch {\n // We ignore errors here, e.g. if the value cannot be URL decoded.\n // This will then be skipped in the next step\n return;\n }\n });\n })\n .reduce>((acc, [key, value]) => {\n if (key && value) {\n acc[key] = value;\n }\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 */\nexport function 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 debug.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 { Client } from '../client';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { DsnComponents, DsnLike, DsnProtocol } from '../types-hoist/dsn';\nimport { consoleSandbox, debug } from './debug-logger';\n\n/** Regular expression used to extract org ID from a DSN host. */\nconst ORG_ID_REGEX = /^o(\\d+)\\./;\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 debug.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 debug.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n debug.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n debug.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Extract the org ID from a DSN host.\n *\n * @param host The host from a DSN\n * @returns The org ID if found, undefined otherwise\n */\nexport function extractOrgIdFromDsnHost(host: string): string | undefined {\n const match = host.match(ORG_ID_REGEX);\n\n return match?.[1];\n}\n\n/**\n * Returns the organization ID of the client.\n *\n * The organization ID is extracted from the DSN. If the client options include a `orgId`, this will always take precedence.\n */\nexport function extractOrgIdFromClient(client: Client): string | undefined {\n const options = client.getOptions();\n\n const { host } = client.getDsn() || {};\n\n let org_id: string | undefined;\n\n if (options.orgId) {\n org_id = String(options.orgId);\n } else if (host) {\n org_id = extractOrgIdFromDsnHost(host);\n }\n\n return org_id;\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", "/**\n * Parse a sample rate from a given value.\n * This will either return a boolean or number sample rate, if the sample rate is valid (between 0 and 1).\n * If a string is passed, we try to convert it to a number.\n *\n * Any invalid sample rate will return `undefined`.\n */\nexport function parseSampleRate(sampleRate: unknown): number | undefined {\n if (typeof sampleRate === 'boolean') {\n return Number(sampleRate);\n }\n\n const rate = typeof sampleRate === 'string' ? parseFloat(sampleRate) : sampleRate;\n if (typeof rate !== 'number' || isNaN(rate) || rate < 0 || rate > 1) {\n return undefined;\n }\n\n return rate;\n}\n", "import type { Client } from '../client';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport type { PropagationContext } from '../types-hoist/tracing';\nimport type { TraceparentData } from '../types-hoist/transaction';\nimport { debug } from '../utils/debug-logger';\nimport { baggageHeaderToDynamicSamplingContext } from './baggage';\nimport { extractOrgIdFromClient } from './dsn';\nimport { parseSampleRate } from './parseSampleRate';\nimport { generateSpanId, generateTraceId } from './propagationContext';\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 * This is terrible naming but the function has nothing to do with the W3C traceparent header.\n * It can only parse the `sentry-trace` header and extract the \"trace parent\" data.\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 a propagation context from incoming headers or\n * creates a minimal new one if the headers are undefined.\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 if (!traceparentData?.traceId) {\n return {\n traceId: generateTraceId(),\n sampleRand: Math.random(),\n };\n }\n\n const sampleRand = getSampleRandFromTraceparentAndDsc(traceparentData, dynamicSamplingContext);\n\n // The sample_rand on the DSC needs to be generated based on traceparent + baggage.\n if (dynamicSamplingContext) {\n dynamicSamplingContext.sample_rand = sampleRand.toString();\n }\n\n const { traceId, parentSpanId, parentSampled } = traceparentData;\n\n return {\n traceId,\n parentSpanId,\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 sampleRand,\n };\n}\n\n/**\n * Create sentry-trace header from span context values.\n */\nexport function generateSentryTraceHeader(\n traceId: string | undefined = generateTraceId(),\n spanId: string | undefined = generateSpanId(),\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\n/**\n * Creates a W3C traceparent header from the given trace and span ids.\n */\nexport function generateTraceparentHeader(\n traceId: string | undefined = generateTraceId(),\n spanId: string | undefined = generateSpanId(),\n sampled?: boolean,\n): string {\n return `00-${traceId}-${spanId}-${sampled ? '01' : '00'}`;\n}\n\n/**\n * Given any combination of an incoming trace, generate a sample rand based on its defined semantics.\n *\n * Read more: https://develop.sentry.dev/sdk/telemetry/traces/#propagated-random-value\n */\nfunction getSampleRandFromTraceparentAndDsc(\n traceparentData: TraceparentData | undefined,\n dsc: Partial | undefined,\n): number {\n // When there is an incoming sample rand use it.\n const parsedSampleRand = parseSampleRate(dsc?.sample_rand);\n if (parsedSampleRand !== undefined) {\n return parsedSampleRand;\n }\n\n // Otherwise, if there is an incoming sampling decision + sample rate, generate a sample rand that would lead to the same sampling decision.\n const parsedSampleRate = parseSampleRate(dsc?.sample_rate);\n if (parsedSampleRate && traceparentData?.parentSampled !== undefined) {\n return traceparentData.parentSampled\n ? // Returns a sample rand with positive sampling decision [0, sampleRate)\n Math.random() * parsedSampleRate\n : // Returns a sample rand with negative sampling decision [sampleRate, 1)\n parsedSampleRate + Math.random() * (1 - parsedSampleRate);\n } else {\n // If nothing applies, return a random sample rand.\n return Math.random();\n }\n}\n\n/**\n * Determines whether a new trace should be continued based on the provided baggage org ID and the client's `strictTraceContinuation` option.\n * If the trace should not be continued, a new trace will be started.\n *\n * The result is dependent on the `strictTraceContinuation` option in the client.\n * See https://develop.sentry.dev/sdk/telemetry/traces/#stricttracecontinuation\n */\nexport function shouldContinueTrace(client: Client, baggageOrgId?: string): boolean {\n const clientOrgId = extractOrgIdFromClient(client);\n\n // Case: baggage orgID and Client orgID don't match - always start new trace\n if (baggageOrgId && clientOrgId && baggageOrgId !== clientOrgId) {\n debug.log(\n `Won't continue trace because org IDs don't match (incoming baggage: ${baggageOrgId}, SDK options: ${clientOrgId})`,\n );\n return false;\n }\n\n const strictTraceContinuation = client.getOptions().strictTraceContinuation || false; // default for `strictTraceContinuation` is `false`\n\n if (strictTraceContinuation) {\n // With strict continuation enabled, don't continue trace if:\n // - Baggage has orgID, but Client doesn't have one\n // - Client has orgID, but baggage doesn't have one\n if ((baggageOrgId && !clientOrgId) || (!baggageOrgId && clientOrgId)) {\n debug.log(\n `Starting a new trace because strict trace continuation is enabled but one org ID is missing (incoming baggage: ${baggageOrgId}, Sentry client: ${clientOrgId})`,\n );\n return false;\n }\n }\n\n return true;\n}\n", "import { getAsyncContextStrategy } from '../asyncContext';\nimport { getMainCarrier } from '../carrier';\nimport { getCurrentScope } from '../currentScopes';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n} from '../semanticAttributes';\nimport type { SentrySpan } from '../tracing/sentrySpan';\nimport { SPAN_STATUS_OK, SPAN_STATUS_UNSET } from '../tracing/spanstatus';\nimport { getCapturedScopesOnSpan } from '../tracing/utils';\nimport type { TraceContext } from '../types-hoist/context';\nimport type { SpanLink, SpanLinkJSON } from '../types-hoist/link';\nimport type { Span, SpanAttributes, SpanJSON, SpanOrigin, SpanTimeInput } from '../types-hoist/span';\nimport type { SpanStatus } from '../types-hoist/spanStatus';\nimport { addNonEnumerableProperty } from '../utils/object';\nimport { generateSpanId } from '../utils/propagationContext';\nimport { timestampInSeconds } from '../utils/time';\nimport { generateSentryTraceHeader, generateTraceparentHeader } from '../utils/tracing';\nimport { consoleSandbox } from './debug-logger';\nimport { _getSpanForScope } from './spanOnScope';\n\n// These are aligned with OpenTelemetry trace flags\nexport const TRACE_FLAG_NONE = 0x0;\nexport const TRACE_FLAG_SAMPLED = 0x1;\n\nlet hasShownSpanDropWarning = false;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n * By default, this will only include trace_id, span_id & parent_span_id.\n * If `includeAllData` is true, it will also include data, op, status & origin.\n */\nexport function spanToTransactionTraceContext(span: Span): TraceContext {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, origin, links } = spanToJSON(span);\n\n return {\n parent_span_id,\n span_id,\n trace_id,\n data,\n op,\n status,\n origin,\n links,\n };\n}\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in a non-transaction event.\n */\nexport function spanToTraceContext(span: Span): TraceContext {\n const { spanId, traceId: trace_id, isRemote } = span.spanContext();\n\n // If the span is remote, we use a random/virtual span as span_id to the trace context,\n // and the remote span as parent_span_id\n const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id;\n const scope = getCapturedScopesOnSpan(span).scope;\n\n const span_id = isRemote ? scope?.getPropagationContext().propagationSpanId || generateSpanId() : spanId;\n\n return {\n parent_span_id,\n span_id,\n trace_id,\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 to a W3C traceparent header.\n */\nexport function spanToTraceparentHeader(span: Span): string {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateTraceparentHeader(traceId, spanId, sampled);\n}\n\n/**\n * Converts the span links array to a flattened version to be sent within an envelope.\n *\n * If the links array is empty, it returns `undefined` so the empty value can be dropped before it's sent.\n */\nexport function convertSpanLinksForEnvelope(links?: SpanLink[]): SpanLinkJSON[] | undefined {\n if (links && links.length > 0) {\n return links.map(({ context: { spanId, traceId, traceFlags, ...restContext }, attributes }) => ({\n span_id: spanId,\n trace_id: traceId,\n sampled: traceFlags === TRACE_FLAG_SAMPLED,\n attributes,\n ...restContext,\n }));\n } else {\n return undefined;\n }\n}\n\n/**\n * Convert a span time input into 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 */\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.\nexport function spanToJSON(span: Span): SpanJSON {\n if (spanIsSentrySpan(span)) {\n return span.getSpanJSON();\n }\n\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n\n // Handle a span from @opentelemetry/sdk-base-trace's `Span` class\n if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {\n const { attributes, startTime, name, endTime, status, links } = span;\n\n // In preparation for the next major of OpenTelemetry, we want to support\n // looking up the parent span id according to the new API\n // In OTel v1, the parent span id is accessed as `parentSpanId`\n // In OTel v2, the parent span id is accessed as `spanId` on the `parentSpanContext`\n const parentSpanId =\n 'parentSpanId' in span\n ? span.parentSpanId\n : 'parentSpanContext' in span\n ? (span.parentSpanContext as { spanId?: string } | undefined)?.spanId\n : undefined;\n\n return {\n span_id,\n trace_id,\n data: attributes,\n description: name,\n parent_span_id: parentSpanId,\n start_timestamp: spanTimeInputToSeconds(startTime),\n // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time\n timestamp: spanTimeInputToSeconds(endTime) || undefined,\n status: getStatusMessage(status),\n op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],\n origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined,\n links: convertSpanLinksForEnvelope(links),\n };\n }\n\n // Finally, at least we have `spanContext()`....\n // This should not actually happen in reality, but we need to handle it for type safety.\n return {\n span_id,\n trace_id,\n start_timestamp: 0,\n data: {},\n };\n}\n\nfunction spanIsOpenTelemetrySdkTraceBaseSpan(span: Span): span is OpenTelemetrySdkTraceBaseSpan {\n const castSpan = span as Partial;\n return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status;\n}\n\n/** Exported only for tests. */\nexport interface OpenTelemetrySdkTraceBaseSpan extends Span {\n attributes: SpanAttributes;\n startTime: SpanTimeInput;\n name: string;\n status: SpanStatus;\n endTime: SpanTimeInput;\n parentSpanId?: string;\n links?: SpanLink[];\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 spanIsSentrySpan(span: Span): span is SentrySpan {\n return typeof (span as SentrySpan).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 return traceFlags === TRACE_FLAG_SAMPLED;\n}\n\n/** Get the status message to use for a JSON representation of a span. */\nexport function getStatusMessage(status: SpanStatus | undefined): string | undefined {\n if (!status || status.code === SPAN_STATUS_UNSET) {\n return undefined;\n }\n\n if (status.code === SPAN_STATUS_OK) {\n return 'ok';\n }\n\n return status.message || 'internal_error';\n}\n\nconst CHILD_SPANS_FIELD = '_sentryChildSpans';\nconst ROOT_SPAN_FIELD = '_sentryRootSpan';\n\ntype SpanWithPotentialChildren = Span & {\n [CHILD_SPANS_FIELD]?: Set;\n [ROOT_SPAN_FIELD]?: Span;\n};\n\n/**\n * Adds an opaque child span reference to a span.\n */\nexport function addChildSpanToSpan(span: SpanWithPotentialChildren, childSpan: Span): void {\n // We store the root span reference on the child span\n // We need this for `getRootSpan()` to work\n const rootSpan = span[ROOT_SPAN_FIELD] || span;\n addNonEnumerableProperty(childSpan as SpanWithPotentialChildren, ROOT_SPAN_FIELD, rootSpan);\n\n // We store a list of child spans on the parent span\n // We need this for `getSpanDescendants()` to work\n if (span[CHILD_SPANS_FIELD]) {\n span[CHILD_SPANS_FIELD].add(childSpan);\n } else {\n addNonEnumerableProperty(span, CHILD_SPANS_FIELD, new Set([childSpan]));\n }\n}\n\n/** This is only used internally by Idle Spans. */\nexport function removeChildSpanFromSpan(span: SpanWithPotentialChildren, childSpan: Span): void {\n if (span[CHILD_SPANS_FIELD]) {\n span[CHILD_SPANS_FIELD].delete(childSpan);\n }\n}\n\n/**\n * Returns an array of the given span and all of its descendants.\n */\nexport function getSpanDescendants(span: SpanWithPotentialChildren): Span[] {\n const resultSet = new Set();\n\n function addSpanChildren(span: SpanWithPotentialChildren): void {\n // This exit condition is required to not infinitely loop in case of a circular dependency.\n if (resultSet.has(span)) {\n return;\n // We want to ignore unsampled spans (e.g. non recording spans)\n } else if (spanIsSampled(span)) {\n resultSet.add(span);\n const childSpans = span[CHILD_SPANS_FIELD] ? Array.from(span[CHILD_SPANS_FIELD]) : [];\n for (const childSpan of childSpans) {\n addSpanChildren(childSpan);\n }\n }\n }\n\n addSpanChildren(span);\n\n return Array.from(resultSet);\n}\n\n/**\n * Returns the root span of a given span.\n */\nexport function getRootSpan(span: SpanWithPotentialChildren): Span {\n return span[ROOT_SPAN_FIELD] || span;\n}\n\n/**\n * Returns the currently active span.\n */\nexport function getActiveSpan(): Span | undefined {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n if (acs.getActiveSpan) {\n return acs.getActiveSpan();\n }\n\n return _getSpanForScope(getCurrentScope());\n}\n\n/**\n * Logs a warning once if `beforeSendSpan` is used to drop spans.\n */\nexport function showSpanDropWarning(): void {\n if (!hasShownSpanDropWarning) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`.',\n );\n });\n hasShownSpanDropWarning = true;\n }\n}\n\n/**\n * Updates the name of the given span and ensures that the span name is not\n * overwritten by the Sentry SDK.\n *\n * Use this function instead of `span.updateName()` if you want to make sure that\n * your name is kept. For some spans, for example root `http.server` spans the\n * Sentry SDK would otherwise overwrite the span name with a high-quality name\n * it infers when the span ends.\n *\n * Use this function in server code or when your span is started on the server\n * and on the client (browser). If you only update a span name on the client,\n * you can also use `span.updateName()` the SDK does not overwrite the name.\n *\n * @param span - The span to update the name of.\n * @param name - The name to set on the span.\n */\nexport function updateSpanName(span: Span, name: string): void {\n span.updateName(name);\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom',\n [SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]: name,\n });\n}\n", "import { DEBUG_BUILD } from '../debug-build';\nimport { addGlobalErrorInstrumentationHandler } from '../instrument/globalError';\nimport { addGlobalUnhandledRejectionInstrumentationHandler } from '../instrument/globalUnhandledRejection';\nimport { debug } from '../utils/debug-logger';\nimport { getActiveSpan, getRootSpan } from '../utils/spanUtils';\nimport { SPAN_STATUS_ERROR } from './spanstatus';\n\nlet errorsInstrumented = false;\n\n/** Only exposed for testing */\nexport function _resetErrorsInstrumented(): void {\n errorsInstrumented = false;\n}\n\n/**\n * Ensure that global errors automatically set the active span status.\n */\nexport function registerSpanErrorInstrumentation(): void {\n if (errorsInstrumented) {\n return;\n }\n\n /**\n * If an error or unhandled promise occurs, we mark the active root span as failed\n */\n function errorCallback(): void {\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n if (rootSpan) {\n const message = 'internal_error';\n DEBUG_BUILD && debug.log(`[Tracing] Root span: ${message} -> Global error occurred`);\n rootSpan.setStatus({ code: SPAN_STATUS_ERROR, message });\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\n errorCallback.tag = 'sentry_tracingErrorCallback';\n\n errorsInstrumented = true;\n addGlobalErrorInstrumentationHandler(errorCallback);\n addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);\n}\n", "import { getClient } from '../currentScopes';\nimport type { CoreOptions } from '../types-hoist/options';\n\n// Treeshakable guard to remove all code related to tracing\ndeclare const __SENTRY_TRACING__: boolean | undefined;\n\n/**\n * Determines if span recording is currently enabled.\n *\n * Spans are recorded when at least one of `tracesSampleRate` and `tracesSampler`\n * is defined in the SDK config. This function does not make any assumption about\n * sampling decisions, it only checks if the SDK is configured to record spans.\n *\n * Important: This function only determines if span recording is enabled. Trace\n * continuation and propagation is separately controlled and not covered by this function.\n * If this function returns `false`, traces can still be propagated (which is what\n * we refer to by \"Tracing without Performance\")\n * @see https://develop.sentry.dev/sdk/telemetry/traces/tracing-without-performance/\n *\n * @param maybeOptions An SDK options object to be passed to this function.\n * If this option is not provided, the function will use the current client's options.\n */\nexport function hasSpansEnabled(\n maybeOptions?: Pick | undefined,\n): boolean {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const options = maybeOptions || getClient()?.getOptions();\n return (\n !!options &&\n // Note: This check is `!= null`, meaning \"nullish\". `0` is not \"nullish\", `undefined` and `null` are. (This comment was brought to you by 15 minutes of questioning life)\n (options.tracesSampleRate != null || !!options.tracesSampler)\n );\n}\n", "import { DEBUG_BUILD } from '../debug-build';\nimport type { ClientOptions } from '../types-hoist/options';\nimport type { SpanJSON } from '../types-hoist/span';\nimport { debug } from './debug-logger';\nimport { isMatchingPattern } from './string';\n\nfunction logIgnoredSpan(droppedSpan: Pick): void {\n debug.log(`Ignoring span ${droppedSpan.op} - ${droppedSpan.description} because it matches \\`ignoreSpans\\`.`);\n}\n\n/**\n * Check if a span should be ignored based on the ignoreSpans configuration.\n */\nexport function shouldIgnoreSpan(\n span: Pick,\n ignoreSpans: Required['ignoreSpans'],\n): boolean {\n if (!ignoreSpans?.length || !span.description) {\n return false;\n }\n\n for (const pattern of ignoreSpans) {\n if (isStringOrRegExp(pattern)) {\n if (isMatchingPattern(span.description, pattern)) {\n DEBUG_BUILD && logIgnoredSpan(span);\n return true;\n }\n continue;\n }\n\n if (!pattern.name && !pattern.op) {\n continue;\n }\n\n const nameMatches = pattern.name ? isMatchingPattern(span.description, pattern.name) : true;\n const opMatches = pattern.op ? span.op && isMatchingPattern(span.op, pattern.op) : true;\n\n // This check here is only correct because we can guarantee that we ran `isMatchingPattern`\n // for at least one of `nameMatches` and `opMatches`. So in contrary to how this looks,\n // not both op and name actually have to match. This is the most efficient way to check\n // for all combinations of name and op patterns.\n if (nameMatches && opMatches) {\n DEBUG_BUILD && logIgnoredSpan(span);\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Takes a list of spans, and a span that was dropped, and re-parents the child spans of the dropped span to the parent of the dropped span, if possible.\n * This mutates the spans array in place!\n */\nexport function reparentChildSpans(spans: SpanJSON[], dropSpan: SpanJSON): void {\n const droppedSpanParentId = dropSpan.parent_span_id;\n const droppedSpanId = dropSpan.span_id;\n\n // This should generally not happen, as we do not apply this on root spans\n // but to be safe, we just bail in this case\n if (!droppedSpanParentId) {\n return;\n }\n\n for (const span of spans) {\n if (span.parent_span_id === droppedSpanId) {\n span.parent_span_id = droppedSpanParentId;\n }\n }\n}\n\nfunction isStringOrRegExp(value: unknown): value is string | RegExp {\n return typeof value === 'string' || value instanceof RegExp;\n}\n", "export const DEFAULT_ENVIRONMENT = 'production';\n", "import type { Client } from '../client';\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getClient } from '../currentScopes';\nimport type { Scope } from '../scope';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n} from '../semanticAttributes';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport type { Span } from '../types-hoist/span';\nimport { baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader } from '../utils/baggage';\nimport { extractOrgIdFromClient } from '../utils/dsn';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled';\nimport { addNonEnumerableProperty } from '../utils/object';\nimport { getRootSpan, spanIsSampled, spanToJSON } from '../utils/spanUtils';\nimport { getCapturedScopesOnSpan } from './utils';\n\n/**\n * If you change this value, also update the terser plugin config to\n * avoid minification of the object property!\n */\nconst FROZEN_DSC_FIELD = '_frozenDsc';\n\ntype SpanWithMaybeDsc = Span & {\n [FROZEN_DSC_FIELD]?: Partial | undefined;\n};\n\n/**\n * Freeze the given DSC on the given span.\n */\nexport function freezeDscOnSpan(span: Span, dsc: Partial): void {\n const spanWithMaybeDsc = span as SpanWithMaybeDsc;\n addNonEnumerableProperty(spanWithMaybeDsc, FROZEN_DSC_FIELD, dsc);\n}\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(trace_id: string, client: Client): DynamicSamplingContext {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n\n // Instead of conditionally adding non-undefined values, we add them and then remove them if needed\n // otherwise, the order of baggage entries changes, which \"breaks\" a bunch of tests etc.\n const dsc: DynamicSamplingContext = {\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n public_key,\n trace_id,\n org_id: extractOrgIdFromClient(client),\n };\n\n client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * Get the dynamic sampling context for the currently active scopes.\n */\nexport function getDynamicSamplingContextFromScope(client: Client, scope: Scope): Partial {\n const propagationContext = scope.getPropagationContext();\n return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);\n}\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 const rootSpan = getRootSpan(span);\n const rootSpanJson = spanToJSON(rootSpan);\n const rootSpanAttributes = rootSpanJson.data;\n const traceState = rootSpan.spanContext().traceState;\n\n // The span sample rate that was locally applied to the root span should also always be applied to the DSC, even if the DSC is frozen.\n // This is so that the downstream traces/services can use parentSampleRate in their `tracesSampler` to make consistent sampling decisions across the entire trace.\n const rootSpanSampleRate =\n traceState?.get('sentry.sample_rate') ??\n rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ??\n rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE];\n\n function applyLocalSampleRateToDsc(dsc: Partial): Partial {\n if (typeof rootSpanSampleRate === 'number' || typeof rootSpanSampleRate === 'string') {\n dsc.sample_rate = `${rootSpanSampleRate}`;\n }\n return dsc;\n }\n\n // For core implementation, we freeze the DSC onto the span as a non-enumerable property\n const frozenDsc = (rootSpan as SpanWithMaybeDsc)[FROZEN_DSC_FIELD];\n if (frozenDsc) {\n return applyLocalSampleRateToDsc(frozenDsc);\n }\n\n // For OpenTelemetry, we freeze the DSC on the trace state\n const traceStateDsc = traceState?.get('sentry.dsc');\n\n // If the span has a DSC, we want it to take precedence\n const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);\n\n if (dscOnTraceState) {\n return applyLocalSampleRateToDsc(dscOnTraceState);\n }\n\n // Else, we generate it from the span\n const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);\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 source = rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n const name = rootSpanJson.description;\n if (source !== 'url' && name) {\n dsc.transaction = name;\n }\n\n // How can we even land here with hasSpansEnabled() returning false?\n // Otel creates a Non-recording span in Tracing Without Performance mode when handling incoming requests\n // So we end up with an active span that is not sampled (neither positively nor negatively)\n if (hasSpansEnabled()) {\n dsc.sampled = String(spanIsSampled(rootSpan));\n dsc.sample_rand =\n // In OTEL we store the sample rand on the trace state because we cannot access scopes for NonRecordingSpans\n // The Sentry OTEL SpanSampler takes care of writing the sample rand on the root span\n traceState?.get('sentry.sample_rand') ??\n // On all other platforms we can actually get the scopes from a root span (we use this as a fallback)\n getCapturedScopesOnSpan(rootSpan).scope?.getPropagationContext().sampleRand.toString();\n }\n\n applyLocalSampleRateToDsc(dsc);\n\n client.emit('createDsc', dsc, rootSpan);\n\n return dsc;\n}\n\n/**\n * Convert a Span to a baggage header.\n */\nexport function spanToBaggageHeader(span: Span): string | undefined {\n const dsc = getDynamicSamplingContextFromSpan(span);\n return dynamicSamplingContextToSentryBaggageHeader(dsc);\n}\n", "import type {\n SentrySpanArguments,\n Span,\n SpanAttributes,\n SpanAttributeValue,\n SpanContextData,\n SpanTimeInput,\n} from '../types-hoist/span';\nimport type { SpanStatus } from '../types-hoist/spanStatus';\nimport { generateSpanId, generateTraceId } from '../utils/propagationContext';\nimport { TRACE_FLAG_NONE } from '../utils/spanUtils';\n\n/**\n * A Sentry Span that is non-recording, meaning it will not be sent to Sentry.\n */\nexport class SentryNonRecordingSpan implements Span {\n private _traceId: string;\n private _spanId: string;\n\n public constructor(spanContext: SentrySpanArguments = {}) {\n this._traceId = spanContext.traceId || generateTraceId();\n this._spanId = spanContext.spanId || generateSpanId();\n }\n\n /** @inheritdoc */\n public spanContext(): SpanContextData {\n return {\n spanId: this._spanId,\n traceId: this._traceId,\n traceFlags: TRACE_FLAG_NONE,\n };\n }\n\n /** @inheritdoc */\n public end(_timestamp?: SpanTimeInput): void {}\n\n /** @inheritdoc */\n public setAttribute(_key: string, _value: SpanAttributeValue | undefined): this {\n return this;\n }\n\n /** @inheritdoc */\n public setAttributes(_values: SpanAttributes): this {\n return this;\n }\n\n /** @inheritdoc */\n public setStatus(_status: SpanStatus): this {\n return this;\n }\n\n /** @inheritdoc */\n public updateName(_name: string): this {\n return this;\n }\n\n /** @inheritdoc */\n public isRecording(): boolean {\n return false;\n }\n\n /** @inheritdoc */\n public addEvent(\n _name: string,\n _attributesOrStartTime?: SpanAttributes | SpanTimeInput,\n _startTime?: SpanTimeInput,\n ): this {\n return this;\n }\n\n /** @inheritDoc */\n public addLink(_link: unknown): this {\n return this;\n }\n\n /** @inheritDoc */\n public addLinks(_links: unknown[]): this {\n return this;\n }\n\n /**\n * This should generally not be used,\n * but we need it for being compliant with the OTEL Span interface.\n *\n * @hidden\n * @internal\n */\n public recordException(_exception: unknown, _time?: number | undefined): void {\n // noop\n }\n}\n", "import type { Primitive } from '../types-hoist/misc';\nimport { isSyntheticEvent, isVueViewModel } from './is';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName, getVueInternalName } 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\ntype MemoFunc = [\n // memoize\n (obj: object) => boolean,\n // unmemoize\n (obj: object) => void,\n];\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 normalized 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 = 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 ['boolean', 'string'].includes(typeof value) ||\n (typeof value === 'number' && Number.isFinite(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 {\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/* 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 getVueInternalName(value);\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && !Number.isFinite(value)) {\n return `[${value}]`;\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?.constructor ? 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 {\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\n/**\n * Helper to decycle json objects\n */\nfunction memoBuilder(): MemoFunc {\n const inner = new WeakSet();\n function memoize(obj: object): boolean {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n\n function unmemoize(obj: object): void {\n inner.delete(obj);\n }\n return [memoize, unmemoize];\n}\n", "import { getSentryCarrier } from '../carrier';\nimport type { Attachment } from '../types-hoist/attachment';\nimport type { DataCategory } from '../types-hoist/datacategory';\nimport type { DsnComponents } from '../types-hoist/dsn';\nimport type {\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n Envelope,\n EnvelopeItemType,\n EventEnvelopeHeaders,\n SpanItem,\n} from '../types-hoist/envelope';\nimport type { Event } from '../types-hoist/event';\nimport type { SdkInfo } from '../types-hoist/sdkinfo';\nimport type { SdkMetadata } from '../types-hoist/sdkmetadata';\nimport type { SpanJSON } from '../types-hoist/span';\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { GLOBAL_OBJ } from './worldwide';\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 array.\n */\nfunction encodeUTF8(input: string): Uint8Array {\n const carrier = getSentryCarrier(GLOBAL_OBJ);\n return carrier.encodePolyfill ? carrier.encodePolyfill(input) : new TextEncoder().encode(input);\n}\n\n/**\n * Decode a UTF8 array to string.\n */\nfunction decodeUTF8(input: Uint8Array): string {\n const carrier = getSentryCarrier(GLOBAL_OBJ);\n return carrier.decodePolyfill ? carrier.decodePolyfill(input) : new TextDecoder().decode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope): string | Uint8Array {\n const [envHeaders, items] = envelope;\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), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next) : 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 {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.stringify()` 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\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(env: string | Uint8Array): Envelope {\n let buffer = typeof env === 'string' ? encodeUTF8(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(decodeUTF8(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 envelope item for a single span\n */\nexport function createSpanEnvelopeItem(spanJson: Partial): SpanItem {\n const spanHeaders: SpanItem[0] = {\n type: 'span',\n };\n\n return [spanHeaders, spanJson];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(attachment: Attachment): AttachmentItem {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data) : attachment.data;\n\n return [\n {\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 profile_chunk: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n span: 'span',\n raw_security: 'security',\n log: 'log_item',\n metric: 'metric',\n trace_metric: 'metric',\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?.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?.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: dynamicSamplingContext,\n }),\n };\n}\n", "import type { Client } from './client';\nimport { getDynamicSamplingContextFromSpan } from './tracing/dynamicSamplingContext';\nimport type { SentrySpan } from './tracing/sentrySpan';\nimport type { LegacyCSPReport } from './types-hoist/csp';\nimport type { DsnComponents } from './types-hoist/dsn';\nimport type {\n DynamicSamplingContext,\n EventEnvelope,\n EventItem,\n RawSecurityEnvelope,\n RawSecurityItem,\n SessionEnvelope,\n SessionItem,\n SpanEnvelope,\n SpanItem,\n} from './types-hoist/envelope';\nimport type { Event } from './types-hoist/event';\nimport type { SdkInfo } from './types-hoist/sdkinfo';\nimport type { SdkMetadata } from './types-hoist/sdkmetadata';\nimport type { Session, SessionAggregates } from './types-hoist/session';\nimport { dsnToString } from './utils/dsn';\nimport {\n createEnvelope,\n createEventEnvelopeHeaders,\n createSpanEnvelopeItem,\n getSdkMetadataForEnvelopeHeader,\n} from './utils/envelope';\nimport { uuid4 } from './utils/misc';\nimport { shouldIgnoreSpan } from './utils/should-ignore-span';\nimport { showSpanDropWarning, spanToJSON } from './utils/spanUtils';\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n *\n * @internal, exported only for testing\n **/\nexport function _enhanceEventWithSdkInfo(event: Event, newSdkInfo?: SdkInfo): Event {\n if (!newSdkInfo) {\n return event;\n }\n\n const eventSdkInfo = event.sdk || {};\n\n event.sdk = {\n ...eventSdkInfo,\n name: eventSdkInfo.name || newSdkInfo.name,\n version: eventSdkInfo.version || newSdkInfo.version,\n integrations: [...(event.sdk?.integrations || []), ...(newSdkInfo.integrations || [])],\n packages: [...(event.sdk?.packages || []), ...(newSdkInfo.packages || [])],\n settings:\n event.sdk?.settings || newSdkInfo.settings\n ? {\n ...event.sdk?.settings,\n ...newSdkInfo.settings,\n }\n : undefined,\n };\n\n return event;\n}\n\n/** Creates an envelope from a Session */\nexport function createSessionEnvelope(\n session: Session | SessionAggregates,\n dsn?: DsnComponents,\n metadata?: SdkMetadata,\n tunnel?: string,\n): SessionEnvelope {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n const envelopeHeaders = {\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const envelopeItem: SessionItem =\n 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session.toJSON()];\n\n return createEnvelope(envelopeHeaders, [envelopeItem]);\n}\n\n/**\n * Create an Envelope from an event.\n */\nexport function createEventEnvelope(\n event: Event,\n dsn?: DsnComponents,\n metadata?: SdkMetadata,\n tunnel?: string,\n): EventEnvelope {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n\n /*\n Note: Due to TS, event.type may be `replay_event`, theoretically.\n In practice, we never call `createEventEnvelope` with `replay_event` type,\n and we'd have to adjust a looot of types to make this work properly.\n We want to avoid casting this around, as that could lead to bugs (e.g. when we add another type)\n So the safe choice is to really guard against the replay_event type here.\n */\n const eventType = event.type && event.type !== 'replay_event' ? event.type : 'event';\n\n _enhanceEventWithSdkInfo(event, metadata?.sdk);\n\n const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);\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 event.sdkProcessingMetadata;\n\n const eventItem: EventItem = [{ type: eventType }, event];\n return createEnvelope(envelopeHeaders, [eventItem]);\n}\n\n/**\n * Create envelope from Span item.\n *\n * Takes an optional client and runs spans through `beforeSendSpan` if available.\n */\nexport function createSpanEnvelope(spans: [SentrySpan, ...SentrySpan[]], client?: Client): SpanEnvelope {\n function dscHasRequiredProps(dsc: Partial): dsc is DynamicSamplingContext {\n return !!dsc.trace_id && !!dsc.public_key;\n }\n\n // For the moment we'll obtain the DSC from the first span in the array\n // This might need to be changed if we permit sending multiple spans from\n // different segments in one envelope\n const dsc = getDynamicSamplingContextFromSpan(spans[0]);\n\n const dsn = client?.getDsn();\n const tunnel = client?.getOptions().tunnel;\n\n const headers: SpanEnvelope[0] = {\n sent_at: new Date().toISOString(),\n ...(dscHasRequiredProps(dsc) && { trace: dsc }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const { beforeSendSpan, ignoreSpans } = client?.getOptions() || {};\n\n const filteredSpans = ignoreSpans?.length\n ? spans.filter(span => !shouldIgnoreSpan(spanToJSON(span), ignoreSpans))\n : spans;\n const droppedSpans = spans.length - filteredSpans.length;\n\n if (droppedSpans) {\n client?.recordDroppedEvent('before_send', 'span', droppedSpans);\n }\n\n const convertToSpanJSON = beforeSendSpan\n ? (span: SentrySpan) => {\n const spanJson = spanToJSON(span);\n const processedSpan = beforeSendSpan(spanJson);\n\n if (!processedSpan) {\n showSpanDropWarning();\n return spanJson;\n }\n\n return processedSpan;\n }\n : spanToJSON;\n\n const items: SpanItem[] = [];\n for (const span of filteredSpans) {\n const spanJson = convertToSpanJSON(span);\n if (spanJson) {\n items.push(createSpanEnvelopeItem(spanJson));\n }\n }\n\n return createEnvelope(headers, items);\n}\n\n/**\n * Create an Envelope from a CSP report.\n */\nexport function createRawSecurityEnvelope(\n report: LegacyCSPReport,\n dsn: DsnComponents,\n tunnel?: string,\n release?: string,\n environment?: string,\n): RawSecurityEnvelope {\n const envelopeHeaders = {\n event_id: uuid4(),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const eventItem: RawSecurityItem = [\n { type: 'raw_security', sentry_release: release, sentry_environment: environment },\n report,\n ];\n\n return createEnvelope(envelopeHeaders, [eventItem]);\n}\n", "import { DEBUG_BUILD } from '../debug-build';\nimport type { Span } from '../types-hoist/span';\nimport { debug } from '../utils/debug-logger';\nimport { getRootSpan, spanIsSampled, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Print a log message for a started span.\n */\nexport function logSpanStart(span: Span): void {\n if (!DEBUG_BUILD) return;\n\n const { description = '< unknown name >', op = '< unknown op >', parent_span_id: parentSpanId } = spanToJSON(span);\n const { spanId } = span.spanContext();\n\n const sampled = spanIsSampled(span);\n const rootSpan = getRootSpan(span);\n const isRootSpan = rootSpan === span;\n\n const header = `[Tracing] Starting ${sampled ? 'sampled' : 'unsampled'} ${isRootSpan ? 'root ' : ''}span`;\n\n const infoParts: string[] = [`op: ${op}`, `name: ${description}`, `ID: ${spanId}`];\n\n if (parentSpanId) {\n infoParts.push(`parent ID: ${parentSpanId}`);\n }\n\n if (!isRootSpan) {\n const { op, description } = spanToJSON(rootSpan);\n infoParts.push(`root ID: ${rootSpan.spanContext().spanId}`);\n if (op) {\n infoParts.push(`root op: ${op}`);\n }\n if (description) {\n infoParts.push(`root description: ${description}`);\n }\n }\n\n debug.log(`${header}\n ${infoParts.join('\\n ')}`);\n}\n\n/**\n * Print a log message for an ended span.\n */\nexport function logSpanEnd(span: Span): void {\n if (!DEBUG_BUILD) return;\n\n const { description = '< unknown name >', op = '< unknown op >' } = spanToJSON(span);\n const { spanId } = span.spanContext();\n const rootSpan = getRootSpan(span);\n const isRootSpan = rootSpan === span;\n\n const msg = `[Tracing] Finishing \"${op}\" ${isRootSpan ? 'root ' : ''}span \"${description}\" with ID ${spanId}`;\n debug.log(msg);\n}\n", "import { DEBUG_BUILD } from '../debug-build';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT,\n SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE,\n} from '../semanticAttributes';\nimport type { Measurements, MeasurementUnit } from '../types-hoist/measurement';\nimport type { TimedEvent } from '../types-hoist/timedEvent';\nimport { debug } from '../utils/debug-logger';\nimport { getActiveSpan, getRootSpan } from '../utils/spanUtils';\n\n/**\n * Adds a measurement to the active transaction on the current global scope. You can optionally pass in a different span\n * as the 4th parameter.\n */\nexport function setMeasurement(name: string, value: number, unit: MeasurementUnit, activeSpan = getActiveSpan()): void {\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n\n if (rootSpan) {\n DEBUG_BUILD && debug.log(`[Measurement] Setting measurement on root span: ${name} = ${value} ${unit}`);\n rootSpan.addEvent(name, {\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: value,\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: unit as string,\n });\n }\n}\n\n/**\n * Convert timed events to measurements.\n */\nexport function timedEventsToMeasurements(events: TimedEvent[]): Measurements | undefined {\n if (!events || events.length === 0) {\n return undefined;\n }\n\n const measurements: Measurements = {};\n events.forEach(event => {\n const attributes = event.attributes || {};\n const unit = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT] as MeasurementUnit | undefined;\n const value = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE] as number | undefined;\n\n if (typeof unit === 'string' && typeof value === 'number') {\n measurements[event.name] = { value, unit };\n }\n });\n\n return measurements;\n}\n", "import { getClient, getCurrentScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { createSpanEnvelope } from '../envelope';\nimport {\n SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME,\n SEMANTIC_ATTRIBUTE_PROFILE_ID,\n SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n} from '../semanticAttributes';\nimport type { SpanEnvelope } from '../types-hoist/envelope';\nimport type { TransactionEvent } from '../types-hoist/event';\nimport type { SpanLink } from '../types-hoist/link';\nimport type {\n SentrySpanArguments,\n Span,\n SpanAttributes,\n SpanAttributeValue,\n SpanContextData,\n SpanJSON,\n SpanOrigin,\n SpanTimeInput,\n} from '../types-hoist/span';\nimport type { SpanStatus } from '../types-hoist/spanStatus';\nimport type { TimedEvent } from '../types-hoist/timedEvent';\nimport { debug } from '../utils/debug-logger';\nimport { generateSpanId, generateTraceId } from '../utils/propagationContext';\nimport {\n convertSpanLinksForEnvelope,\n getRootSpan,\n getSpanDescendants,\n getStatusMessage,\n spanTimeInputToSeconds,\n spanToJSON,\n spanToTransactionTraceContext,\n TRACE_FLAG_NONE,\n TRACE_FLAG_SAMPLED,\n} from '../utils/spanUtils';\nimport { timestampInSeconds } from '../utils/time';\nimport { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';\nimport { logSpanEnd } from './logSpans';\nimport { timedEventsToMeasurements } from './measurement';\nimport { getCapturedScopesOnSpan } from './utils';\n\nconst MAX_SPAN_COUNT = 1000;\n\n/**\n * Span contains all data about a span\n */\nexport class SentrySpan implements Span {\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 protected _links?: SpanLink[];\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?: SpanStatus;\n /** The timed events added to this span. */\n protected _events: TimedEvent[];\n\n /** if true, treat span as a standalone span (not part of a transaction) */\n private _isStandaloneSpan?: boolean;\n\n /**\n * You should never call the constructor manually, always use `Sentry.startSpan()`\n * or other span methods.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(spanContext: SentrySpanArguments = {}) {\n this._traceId = spanContext.traceId || generateTraceId();\n this._spanId = spanContext.spanId || generateSpanId();\n this._startTime = spanContext.startTimestamp || timestampInSeconds();\n this._links = spanContext.links;\n\n this._attributes = {};\n this.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'manual',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,\n ...spanContext.attributes,\n });\n\n this._name = spanContext.name;\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.endTimestamp) {\n this._endTime = spanContext.endTimestamp;\n }\n\n this._events = [];\n\n this._isStandaloneSpan = spanContext.isStandalone;\n\n // If the span is already ended, ensure we finalize the span immediately\n if (this._endTime) {\n this._onSpanEnded();\n }\n }\n\n /** @inheritDoc */\n public addLink(link: SpanLink): this {\n if (this._links) {\n this._links.push(link);\n } else {\n this._links = [link];\n }\n return this;\n }\n\n /** @inheritDoc */\n public addLinks(links: SpanLink[]): this {\n if (this._links) {\n this._links.push(...links);\n } else {\n this._links = links;\n }\n return this;\n }\n\n /**\n * This should generally not be used,\n * but it is needed for being compliant with the OTEL Span interface.\n *\n * @hidden\n * @internal\n */\n public recordException(_exception: unknown, _time?: number | undefined): void {\n // noop\n }\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 /** @inheritdoc */\n public setAttribute(key: string, value: SpanAttributeValue | undefined): this {\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 return this;\n }\n\n /** @inheritdoc */\n public setAttributes(attributes: SpanAttributes): this {\n Object.keys(attributes).forEach(key => this.setAttribute(key, attributes[key]));\n return this;\n }\n\n /**\n * This should generally not be used,\n * but we need it for browser tracing where we want to adjust the start time afterwards.\n * USE THIS WITH CAUTION!\n *\n * @hidden\n * @internal\n */\n public updateStartTime(timeInput: SpanTimeInput): void {\n this._startTime = spanTimeInputToSeconds(timeInput);\n }\n\n /**\n * @inheritDoc\n */\n public setStatus(value: SpanStatus): this {\n this._status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public updateName(name: string): this {\n this._name = name;\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'custom');\n return this;\n }\n\n /** @inheritdoc */\n public end(endTimestamp?: SpanTimeInput): void {\n // If already ended, skip\n if (this._endTime) {\n return;\n }\n\n this._endTime = spanTimeInputToSeconds(endTimestamp);\n logSpanEnd(this);\n\n this._onSpanEnded();\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 {\n data: this._attributes,\n description: this._name,\n op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],\n parent_span_id: this._parentSpanId,\n span_id: this._spanId,\n start_timestamp: this._startTime,\n status: getStatusMessage(this._status),\n timestamp: this._endTime,\n trace_id: this._traceId,\n origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined,\n profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID] as string | undefined,\n exclusive_time: this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME] as number | undefined,\n measurements: timedEventsToMeasurements(this._events),\n is_segment: (this._isStandaloneSpan && getRootSpan(this) === this) || undefined,\n segment_id: this._isStandaloneSpan ? getRootSpan(this).spanContext().spanId : undefined,\n links: convertSpanLinksForEnvelope(this._links),\n };\n }\n\n /** @inheritdoc */\n public isRecording(): boolean {\n return !this._endTime && !!this._sampled;\n }\n\n /**\n * @inheritdoc\n */\n public addEvent(\n name: string,\n attributesOrStartTime?: SpanAttributes | SpanTimeInput,\n startTime?: SpanTimeInput,\n ): this {\n DEBUG_BUILD && debug.log('[Tracing] Adding an event to span:', name);\n\n const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || timestampInSeconds();\n const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {};\n\n const event: TimedEvent = {\n name,\n time: spanTimeInputToSeconds(time),\n attributes,\n };\n\n this._events.push(event);\n\n return this;\n }\n\n /**\n * This method should generally not be used,\n * but for now we need a way to publicly check if the `_isStandaloneSpan` flag is set.\n * USE THIS WITH CAUTION!\n * @internal\n * @hidden\n * @experimental\n */\n public isStandaloneSpan(): boolean {\n return !!this._isStandaloneSpan;\n }\n\n /** Emit `spanEnd` when the span is ended. */\n private _onSpanEnded(): void {\n const client = getClient();\n if (client) {\n client.emit('spanEnd', this);\n }\n\n // A segment span is basically the root span of a local span tree.\n // So for now, this is either what we previously refer to as the root span,\n // or a standalone span.\n const isSegmentSpan = this._isStandaloneSpan || this === getRootSpan(this);\n\n if (!isSegmentSpan) {\n return;\n }\n\n // if this is a standalone span, we send it immediately\n if (this._isStandaloneSpan) {\n if (this._sampled) {\n sendSpanEnvelope(createSpanEnvelope([this], client));\n } else {\n DEBUG_BUILD &&\n debug.log('[Tracing] Discarding standalone span because its trace was not chosen to be sampled.');\n if (client) {\n client.recordDroppedEvent('sample_rate', 'span');\n }\n }\n return;\n }\n\n const transactionEvent = this._convertSpanToTransaction();\n if (transactionEvent) {\n const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope();\n scope.captureEvent(transactionEvent);\n }\n }\n\n /**\n * Finish the transaction & prepare the event to send to Sentry.\n */\n private _convertSpanToTransaction(): TransactionEvent | undefined {\n // We can only convert finished spans\n if (!isFullFinishedSpan(spanToJSON(this))) {\n return undefined;\n }\n\n if (!this._name) {\n DEBUG_BUILD && debug.warn('Transaction has no name, falling back to ``.');\n this._name = '';\n }\n\n const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);\n\n const normalizedRequest = capturedSpanScope?.getScopeData().sdkProcessingMetadata?.normalizedRequest;\n\n if (this._sampled !== true) {\n return undefined;\n }\n\n // The transaction span itself as well as any potential standalone spans should be filtered out\n const finishedSpans = getSpanDescendants(this).filter(span => span !== this && !isStandaloneSpan(span));\n\n const spans = finishedSpans.map(span => spanToJSON(span)).filter(isFullFinishedSpan);\n\n const source = this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n\n // remove internal root span attributes we don't need to send.\n /* eslint-disable @typescript-eslint/no-dynamic-delete */\n delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];\n spans.forEach(span => {\n delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];\n });\n // eslint-enabled-next-line @typescript-eslint/no-dynamic-delete\n\n const transaction: TransactionEvent = {\n contexts: {\n trace: spanToTransactionTraceContext(this),\n },\n spans:\n // spans.sort() mutates the array, but `spans` is already a copy so we can safely do this here\n // we do not use spans anymore after this point\n spans.length > MAX_SPAN_COUNT\n ? spans.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT)\n : spans,\n start_timestamp: this._startTime,\n timestamp: this._endTime,\n transaction: this._name,\n type: 'transaction',\n sdkProcessingMetadata: {\n capturedSpanScope,\n capturedSpanIsolationScope,\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),\n },\n request: normalizedRequest,\n ...(source && {\n transaction_info: {\n source,\n },\n }),\n };\n\n const measurements = timedEventsToMeasurements(this._events);\n const hasMeasurements = measurements && Object.keys(measurements).length;\n\n if (hasMeasurements) {\n DEBUG_BUILD &&\n debug.log(\n '[Measurements] Adding measurements to transaction event',\n JSON.stringify(measurements, undefined, 2),\n );\n transaction.measurements = measurements;\n }\n\n return transaction;\n }\n}\n\nfunction isSpanTimeInput(value: undefined | SpanAttributes | SpanTimeInput): value is SpanTimeInput {\n return (value && typeof value === 'number') || value instanceof Date || Array.isArray(value);\n}\n\n// We want to filter out any incomplete SpanJSON objects\nfunction isFullFinishedSpan(input: Partial): input is SpanJSON {\n return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id;\n}\n\n/** `SentrySpan`s can be sent as a standalone span rather than belonging to a transaction */\nfunction isStandaloneSpan(span: Span): boolean {\n return span instanceof SentrySpan && span.isStandaloneSpan();\n}\n\n/**\n * Sends a `SpanEnvelope`.\n *\n * Note: If the envelope's spans are dropped, e.g. via `beforeSendSpan`,\n * the envelope will not be sent either.\n */\nfunction sendSpanEnvelope(envelope: SpanEnvelope): void {\n const client = getClient();\n if (!client) {\n return;\n }\n\n const spanItems = envelope[1];\n if (!spanItems || spanItems.length === 0) {\n client.recordDroppedEvent('before_send', 'span');\n return;\n }\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n client.sendEnvelope(envelope);\n}\n", "import { isThenable } from '../utils/is';\n\n/* eslint-disable */\n// Vendor \"Awaited\" in to be TS 3.8 compatible\ntype AwaitedPromise = T extends null | undefined\n ? T // special case for `null | undefined` when not in `--strictNullChecks` mode\n : T extends object & { then(onfulfilled: infer F, ...args: infer _): any } // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped\n ? F extends (value: infer V, ...args: infer _) => any // if the argument to `then` is callable, extracts the first argument\n ? V // normally this would recursively unwrap, but this is not possible in TS3.8\n : never // the argument to `then` was not callable\n : T; // non-object or non-thenable\n/* eslint-enable */\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function handleCallbackErrors Promise, PromiseValue = AwaitedPromise>>(\n fn: Fn,\n onError: (error: unknown) => void,\n onFinally?: () => void,\n onSuccess?: (result: PromiseValue) => void,\n): ReturnType;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function handleCallbackErrors any>(\n fn: Fn,\n onError: (error: unknown) => void,\n onFinally?: () => void,\n onSuccess?: (result: ReturnType) => void,\n): ReturnType;\n/**\n * Wrap a callback function with error handling.\n * If an error is thrown, it will be passed to the `onError` callback and re-thrown.\n *\n * If the return value of the function is a promise, it will be handled with `maybeHandlePromiseRejection`.\n *\n * If an `onFinally` callback is provided, this will be called when the callback has finished\n * - so if it returns a promise, once the promise resolved/rejected,\n * else once the callback has finished executing.\n * The `onFinally` callback will _always_ be called, no matter if an error was thrown or not.\n */\nexport function handleCallbackErrors<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Fn extends () => any,\n ValueType = ReturnType,\n>(\n fn: Fn,\n onError: (error: unknown) => void,\n onFinally: () => void = () => {},\n onSuccess: (result: ValueType | AwaitedPromise) => void = () => {},\n): ValueType {\n let maybePromiseResult: ReturnType;\n try {\n maybePromiseResult = fn();\n } catch (e) {\n onError(e);\n onFinally();\n throw e;\n }\n\n return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally, onSuccess);\n}\n\n/**\n * Maybe handle a promise rejection.\n * This expects to be given a value that _may_ be a promise, or any other value.\n * If it is a promise, and it rejects, it will call the `onError` callback.\n * Other than this, it will generally return the given value as-is.\n */\nfunction maybeHandlePromiseRejection(\n value: MaybePromise,\n onError: (error: unknown) => void,\n onFinally: () => void,\n onSuccess: (result: MaybePromise | AwaitedPromise) => void,\n): MaybePromise {\n if (isThenable(value)) {\n // @ts-expect-error - the isThenable check returns the \"wrong\" type here\n return value.then(\n res => {\n onFinally();\n onSuccess(res);\n return res;\n },\n e => {\n onError(e);\n onFinally();\n throw e;\n },\n );\n }\n\n onFinally();\n onSuccess(value);\n return value;\n}\n", "import { DEBUG_BUILD } from '../debug-build';\nimport type { CoreOptions } from '../types-hoist/options';\nimport type { SamplingContext } from '../types-hoist/samplingcontext';\nimport { debug } from '../utils/debug-logger';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled';\nimport { parseSampleRate } from '../utils/parseSampleRate';\n\n/**\n * Makes a sampling decision for the given options.\n *\n * Called every time a root span is created. Only root spans which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n */\nexport function sampleSpan(\n options: Pick,\n samplingContext: SamplingContext,\n sampleRand: number,\n): [sampled: boolean, sampleRate?: number, localSampleRateWasApplied?: boolean] {\n // nothing to do if span recording is not enabled\n if (!hasSpansEnabled(options)) {\n return [false];\n }\n\n let localSampleRateWasApplied = undefined;\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` 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({\n ...samplingContext,\n inheritOrSampleWith: fallbackSampleRate => {\n // If we have an incoming parent sample rate, we'll just use that one.\n // The sampling decision will be inherited because of the sample_rand that was generated when the trace reached the incoming boundaries of the SDK.\n if (typeof samplingContext.parentSampleRate === 'number') {\n return samplingContext.parentSampleRate;\n }\n\n // Fallback if parent sample rate is not on the incoming trace (e.g. if there is no baggage)\n // This is to provide backwards compatibility if there are incoming traces from older SDKs that don't send a parent sample rate or a sample rand. In these cases we just want to force either a sampling decision on the downstream traces via the sample rate.\n if (typeof samplingContext.parentSampled === 'boolean') {\n return Number(samplingContext.parentSampled);\n }\n\n return fallbackSampleRate;\n },\n });\n localSampleRateWasApplied = true;\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n localSampleRateWasApplied = true;\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get.\n // (The only valid values are booleans or numbers between 0 and 1.)\n const parsedSampleRate = parseSampleRate(sampleRate);\n\n if (parsedSampleRate === undefined) {\n DEBUG_BUILD &&\n debug.warn(\n `[Tracing] Discarding root span because of invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n sampleRate,\n )} of type ${JSON.stringify(typeof sampleRate)}.`,\n );\n return [false];\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 (!parsedSampleRate) {\n DEBUG_BUILD &&\n debug.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 return [false, parsedSampleRate, localSampleRateWasApplied];\n }\n\n // We always compare the sample rand for the current execution context against the chosen sample rate.\n // Read more: https://develop.sentry.dev/sdk/telemetry/traces/#propagated-random-value\n const shouldSample = sampleRand < parsedSampleRate;\n\n // if we're not going to keep it, we're done\n if (!shouldSample) {\n DEBUG_BUILD &&\n debug.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n }\n\n return [shouldSample, parsedSampleRate, localSampleRateWasApplied];\n}\n", "/* eslint-disable max-lines */\n\nimport { getAsyncContextStrategy } from '../asyncContext';\nimport type { AsyncContextStrategy } from '../asyncContext/types';\nimport { getMainCarrier } from '../carrier';\nimport { getClient, getCurrentScope, getIsolationScope, withScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Scope } from '../scope';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport type { ClientOptions } from '../types-hoist/options';\nimport type { SentrySpanArguments, Span, SpanTimeInput } from '../types-hoist/span';\nimport type { StartSpanOptions } from '../types-hoist/startSpanOptions';\nimport { baggageHeaderToDynamicSamplingContext } from '../utils/baggage';\nimport { debug } from '../utils/debug-logger';\nimport { handleCallbackErrors } from '../utils/handleCallbackErrors';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled';\nimport { parseSampleRate } from '../utils/parseSampleRate';\nimport { generateTraceId } from '../utils/propagationContext';\nimport { _getSpanForScope, _setSpanForScope } from '../utils/spanOnScope';\nimport { addChildSpanToSpan, getRootSpan, spanIsSampled, spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';\nimport { propagationContextFromHeaders, shouldContinueTrace } from '../utils/tracing';\nimport { freezeDscOnSpan, getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';\nimport { logSpanStart } from './logSpans';\nimport { sampleSpan } from './sampling';\nimport { SentryNonRecordingSpan } from './sentryNonRecordingSpan';\nimport { SentrySpan } from './sentrySpan';\nimport { SPAN_STATUS_ERROR } from './spanstatus';\nimport { setCapturedScopesOnSpan } from './utils';\n\nconst SUPPRESS_TRACING_KEY = '__SENTRY_SUPPRESS_TRACING__';\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.getActiveSpan()`, 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 * You'll always get a span passed to the callback,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nexport function startSpan(options: StartSpanOptions, callback: (span: Span) => T): T {\n const acs = getAcs();\n if (acs.startSpan) {\n return acs.startSpan(options, callback);\n }\n\n const spanArguments = parseSentrySpanArguments(options);\n const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;\n\n // We still need to fork a potentially passed scope, as we set the active span on it\n // and we need to ensure that it is cleaned up properly once the span ends.\n const customForkedScope = customScope?.clone();\n\n return withScope(customForkedScope, () => {\n // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n const wrapper = getActiveSpanWrapper(customParentSpan);\n\n return wrapper(() => {\n const scope = getCurrentScope();\n const parentSpan = getParentSpan(scope, customParentSpan);\n\n const shouldSkipSpan = options.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? new SentryNonRecordingSpan()\n : createChildOrRootSpan({\n parentSpan,\n spanArguments,\n forceTransaction,\n scope,\n });\n\n _setSpanForScope(scope, activeSpan);\n\n return handleCallbackErrors(\n () => callback(activeSpan),\n () => {\n // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n const { status } = spanToJSON(activeSpan);\n if (activeSpan.isRecording() && (!status || status === 'ok')) {\n activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n },\n () => {\n activeSpan.end();\n },\n );\n });\n });\n}\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. Use `span.end()` to end the span.\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 * You'll always get a span passed to the callback,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nexport function startSpanManual(options: StartSpanOptions, callback: (span: Span, finish: () => void) => T): T {\n const acs = getAcs();\n if (acs.startSpanManual) {\n return acs.startSpanManual(options, callback);\n }\n\n const spanArguments = parseSentrySpanArguments(options);\n const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;\n\n const customForkedScope = customScope?.clone();\n\n return withScope(customForkedScope, () => {\n // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n const wrapper = getActiveSpanWrapper(customParentSpan);\n\n return wrapper(() => {\n const scope = getCurrentScope();\n const parentSpan = getParentSpan(scope, customParentSpan);\n\n const shouldSkipSpan = options.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? new SentryNonRecordingSpan()\n : createChildOrRootSpan({\n parentSpan,\n spanArguments,\n forceTransaction,\n scope,\n });\n\n _setSpanForScope(scope, activeSpan);\n\n return handleCallbackErrors(\n // We pass the `finish` function to the callback, so the user can finish the span manually\n // this is mainly here for historic purposes because previously, we instructed users to call\n // `finish` instead of `span.end()` to also clean up the scope. Nowadays, calling `span.end()`\n // or `finish` has the same effect and we simply leave it here to avoid breaking user code.\n () => callback(activeSpan, () => activeSpan.end()),\n () => {\n // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n const { status } = spanToJSON(activeSpan);\n if (activeSpan.isRecording() && (!status || status === 'ok')) {\n activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\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.getActiveSpan()`.\n *\n * If you want to create a span that is set as active, use {@link startSpan}.\n *\n * This function will always return a span,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nexport function startInactiveSpan(options: StartSpanOptions): Span {\n const acs = getAcs();\n if (acs.startInactiveSpan) {\n return acs.startInactiveSpan(options);\n }\n\n const spanArguments = parseSentrySpanArguments(options);\n const { forceTransaction, parentSpan: customParentSpan } = options;\n\n // If `options.scope` is defined, we use this as as a wrapper,\n // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n const wrapper = options.scope\n ? (callback: () => Span) => withScope(options.scope, callback)\n : customParentSpan !== undefined\n ? (callback: () => Span) => withActiveSpan(customParentSpan, callback)\n : (callback: () => Span) => callback();\n\n return wrapper(() => {\n const scope = getCurrentScope();\n const parentSpan = getParentSpan(scope, customParentSpan);\n\n const shouldSkipSpan = options.onlyIfParent && !parentSpan;\n\n if (shouldSkipSpan) {\n return new SentryNonRecordingSpan();\n }\n\n return createChildOrRootSpan({\n parentSpan,\n spanArguments,\n forceTransaction,\n scope,\n });\n });\n}\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 */\nexport const continueTrace = (\n options: {\n sentryTrace: Parameters[0];\n baggage: Parameters[1];\n },\n callback: () => V,\n): V => {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n if (acs.continueTrace) {\n return acs.continueTrace(options, callback);\n }\n\n const { sentryTrace, baggage } = options;\n\n const client = getClient();\n const incomingDsc = baggageHeaderToDynamicSamplingContext(baggage);\n if (client && !shouldContinueTrace(client, incomingDsc?.org_id)) {\n return startNewTrace(callback);\n }\n\n return withScope(scope => {\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n scope.setPropagationContext(propagationContext);\n _setSpanForScope(scope, undefined);\n return callback();\n });\n};\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be\n * passed `null` to start an entirely new span tree.\n *\n * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,\n * spans started within the callback will not be attached to a parent 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 | null, callback: (scope: Scope) => T): T {\n const acs = getAcs();\n if (acs.withActiveSpan) {\n return acs.withActiveSpan(span, callback);\n }\n\n return withScope(scope => {\n _setSpanForScope(scope, span || undefined);\n return callback(scope);\n });\n}\n\n/** Suppress tracing in the given callback, ensuring no spans are generated inside of it. */\nexport function suppressTracing(callback: () => T): T {\n const acs = getAcs();\n\n if (acs.suppressTracing) {\n return acs.suppressTracing(callback);\n }\n\n return withScope(scope => {\n // Note: We do not wait for the callback to finish before we reset the metadata\n // the reason for this is that otherwise, in the browser this can lead to very weird behavior\n // as there is only a single top scope, if the callback takes longer to finish,\n // other, unrelated spans may also be suppressed, which we do not want\n // so instead, we only suppress tracing synchronoysly in the browser\n scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true });\n const res = callback();\n scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: undefined });\n return res;\n });\n}\n\n/**\n * Starts a new trace for the duration of the provided callback. Spans started within the\n * callback will be part of the new trace instead of a potentially previously started trace.\n *\n * Important: Only use this function if you want to override the default trace lifetime and\n * propagation mechanism of the SDK for the duration and scope of the provided callback.\n * The newly created trace will also be the root of a new distributed trace, for example if\n * you make http requests within the callback.\n * This function might be useful if the operation you want to instrument should not be part\n * of a potentially ongoing trace.\n *\n * Default behavior:\n * - Server-side: A new trace is started for each incoming request.\n * - Browser: A new trace is started for each page our route. Navigating to a new route\n * or page will automatically create a new trace.\n */\nexport function startNewTrace(callback: () => T): T {\n return withScope(scope => {\n scope.setPropagationContext({\n traceId: generateTraceId(),\n sampleRand: Math.random(),\n });\n DEBUG_BUILD && debug.log(`Starting a new trace with id ${scope.getPropagationContext().traceId}`);\n return withActiveSpan(null, callback);\n });\n}\n\nfunction createChildOrRootSpan({\n parentSpan,\n spanArguments,\n forceTransaction,\n scope,\n}: {\n parentSpan: SentrySpan | undefined;\n spanArguments: SentrySpanArguments;\n forceTransaction?: boolean;\n scope: Scope;\n}): Span {\n if (!hasSpansEnabled()) {\n const span = new SentryNonRecordingSpan();\n\n // If this is a root span, we ensure to freeze a DSC\n // So we can have at least partial data here\n if (forceTransaction || !parentSpan) {\n const dsc = {\n sampled: 'false',\n sample_rate: '0',\n transaction: spanArguments.name,\n ...getDynamicSamplingContextFromSpan(span),\n } satisfies Partial;\n freezeDscOnSpan(span, dsc);\n }\n\n return span;\n }\n\n const isolationScope = getIsolationScope();\n\n let span: Span;\n if (parentSpan && !forceTransaction) {\n span = _startChildSpan(parentSpan, scope, spanArguments);\n addChildSpanToSpan(parentSpan, span);\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 parentSampled = spanIsSampled(parentSpan);\n\n span = _startRootSpan(\n {\n traceId,\n parentSpanId,\n ...spanArguments,\n },\n scope,\n parentSampled,\n );\n\n freezeDscOnSpan(span, dsc);\n } else {\n const {\n traceId,\n dsc,\n parentSpanId,\n sampled: parentSampled,\n } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n span = _startRootSpan(\n {\n traceId,\n parentSpanId,\n ...spanArguments,\n },\n scope,\n parentSampled,\n );\n\n if (dsc) {\n freezeDscOnSpan(span, dsc);\n }\n }\n\n logSpanStart(span);\n\n setCapturedScopesOnSpan(span, scope, isolationScope);\n\n return span;\n}\n\n/**\n * This converts StartSpanOptions to SentrySpanArguments.\n * For the most part (for now) we accept the same options,\n * but some of them need to be transformed.\n */\nfunction parseSentrySpanArguments(options: StartSpanOptions): SentrySpanArguments {\n const exp = options.experimental || {};\n const initialCtx: SentrySpanArguments = {\n isStandalone: exp.standalone,\n ...options,\n };\n\n if (options.startTime) {\n const ctx: SentrySpanArguments & { startTime?: SpanTimeInput } = { ...initialCtx };\n ctx.startTimestamp = spanTimeInputToSeconds(options.startTime);\n delete ctx.startTime;\n return ctx;\n }\n\n return initialCtx;\n}\n\nfunction getAcs(): AsyncContextStrategy {\n const carrier = getMainCarrier();\n return getAsyncContextStrategy(carrier);\n}\n\nfunction _startRootSpan(spanArguments: SentrySpanArguments, scope: Scope, parentSampled?: boolean): SentrySpan {\n const client = getClient();\n const options: Partial = client?.getOptions() || {};\n\n const { name = '' } = spanArguments;\n\n const mutableSpanSamplingData = { spanAttributes: { ...spanArguments.attributes }, spanName: name, parentSampled };\n\n // we don't care about the decision for the moment; this is just a placeholder\n client?.emit('beforeSampling', mutableSpanSamplingData, { decision: false });\n\n // If hook consumers override the parentSampled flag, we will use that value instead of the actual one\n const finalParentSampled = mutableSpanSamplingData.parentSampled ?? parentSampled;\n const finalAttributes = mutableSpanSamplingData.spanAttributes;\n\n const currentPropagationContext = scope.getPropagationContext();\n const [sampled, sampleRate, localSampleRateWasApplied] = scope.getScopeData().sdkProcessingMetadata[\n SUPPRESS_TRACING_KEY\n ]\n ? [false]\n : sampleSpan(\n options,\n {\n name,\n parentSampled: finalParentSampled,\n attributes: finalAttributes,\n parentSampleRate: parseSampleRate(currentPropagationContext.dsc?.sample_rate),\n },\n currentPropagationContext.sampleRand,\n );\n\n const rootSpan = new SentrySpan({\n ...spanArguments,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom',\n [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]:\n sampleRate !== undefined && localSampleRateWasApplied ? sampleRate : undefined,\n ...finalAttributes,\n },\n sampled,\n });\n\n if (!sampled && client) {\n DEBUG_BUILD && debug.log('[Tracing] Discarding root span because its trace was not chosen to be sampled.');\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n if (client) {\n client.emit('spanStart', rootSpan);\n }\n\n return rootSpan;\n}\n\n/**\n * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`.\n * This inherits the sampling decision from the parent span.\n */\nfunction _startChildSpan(parentSpan: Span, scope: Scope, spanArguments: SentrySpanArguments): Span {\n const { spanId, traceId } = parentSpan.spanContext();\n const sampled = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? false : spanIsSampled(parentSpan);\n\n const childSpan = sampled\n ? new SentrySpan({\n ...spanArguments,\n parentSpanId: spanId,\n traceId,\n sampled,\n })\n : new SentryNonRecordingSpan({ traceId });\n\n addChildSpanToSpan(parentSpan, childSpan);\n\n const client = getClient();\n if (client) {\n client.emit('spanStart', childSpan);\n // If it has an endTimestamp, it's already ended\n if (spanArguments.endTimestamp) {\n client.emit('spanEnd', childSpan);\n }\n }\n\n return childSpan;\n}\n\nfunction getParentSpan(scope: Scope, customParentSpan: Span | null | undefined): SentrySpan | undefined {\n // always use the passed in span directly\n if (customParentSpan) {\n return customParentSpan as SentrySpan;\n }\n\n // This is different from `undefined` as it means the user explicitly wants no parent span\n if (customParentSpan === null) {\n return undefined;\n }\n\n const span = _getSpanForScope(scope) as SentrySpan | undefined;\n\n if (!span) {\n return undefined;\n }\n\n const client = getClient();\n const options: Partial = client ? client.getOptions() : {};\n if (options.parentSpanIsAlwaysRootSpan) {\n return getRootSpan(span) as SentrySpan;\n }\n\n return span;\n}\n\nfunction getActiveSpanWrapper(parentSpan: Span | undefined | null): (callback: () => T) => T {\n return parentSpan !== undefined\n ? (callback: () => T) => {\n return withActiveSpan(parentSpan, callback);\n }\n : (callback: () => T) => callback();\n}\n", "import { getClient, getCurrentScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON } from '../semanticAttributes';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport type { Span } from '../types-hoist/span';\nimport type { StartSpanOptions } from '../types-hoist/startSpanOptions';\nimport { debug } from '../utils/debug-logger';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled';\nimport { shouldIgnoreSpan } from '../utils/should-ignore-span';\nimport { _setSpanForScope } from '../utils/spanOnScope';\nimport {\n getActiveSpan,\n getSpanDescendants,\n removeChildSpanFromSpan,\n spanTimeInputToSeconds,\n spanToJSON,\n} from '../utils/spanUtils';\nimport { timestampInSeconds } from '../utils/time';\nimport { freezeDscOnSpan, getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';\nimport { SentryNonRecordingSpan } from './sentryNonRecordingSpan';\nimport { SentrySpan } from './sentrySpan';\nimport { SPAN_STATUS_ERROR, SPAN_STATUS_OK } from './spanstatus';\nimport { startInactiveSpan } from './trace';\n\nexport const TRACING_DEFAULTS = {\n idleTimeout: 1_000,\n finalTimeout: 30_000,\n childSpanTimeout: 15_000,\n};\n\nconst FINISH_REASON_HEARTBEAT_FAILED = 'heartbeatFailed';\nconst FINISH_REASON_IDLE_TIMEOUT = 'idleTimeout';\nconst FINISH_REASON_FINAL_TIMEOUT = 'finalTimeout';\nconst FINISH_REASON_EXTERNAL_FINISH = 'externalFinish';\nconst FINISH_REASON_CANCELLED = 'cancelled';\n\n// unused\nconst FINISH_REASON_DOCUMENT_HIDDEN = 'documentHidden';\n\n// unused in this file, but used in BrowserTracing\nconst FINISH_REASON_INTERRUPTED = 'interactionInterrupted';\n\ntype IdleSpanFinishReason =\n | typeof FINISH_REASON_CANCELLED\n | typeof FINISH_REASON_DOCUMENT_HIDDEN\n | typeof FINISH_REASON_EXTERNAL_FINISH\n | typeof FINISH_REASON_FINAL_TIMEOUT\n | typeof FINISH_REASON_HEARTBEAT_FAILED\n | typeof FINISH_REASON_IDLE_TIMEOUT\n | typeof FINISH_REASON_INTERRUPTED;\n\ninterface IdleSpanOptions {\n /**\n * The time that has to pass without any span being created.\n * If this time is exceeded, the idle span will finish.\n */\n idleTimeout: number;\n /**\n * The max. time an idle span may run.\n * If this time is exceeded, the idle span will finish no matter what.\n */\n finalTimeout: number;\n /**\n * The max. time a child span may run.\n * If the time since the last span was started exceeds this time, the idle span will finish.\n */\n childSpanTimeout?: number;\n /**\n * When set to `true`, will disable the idle timeout and child timeout\n * until the `idleSpanEnableAutoFinish` hook is emitted for the idle span.\n * The final timeout mechanism will not be affected by this option,\n * meaning the idle span 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 disableAutoFinish?: boolean;\n\n /** Allows to configure a hook that is called when the idle span is ended, before it is processed. */\n beforeSpanEnd?: (span: Span) => void;\n\n /**\n * If set to `true`, the idle span will be trimmed to the latest span end timestamp of its children.\n *\n * @default `true`.\n */\n trimIdleSpanEndTimestamp?: boolean;\n}\n\n/**\n * An idle span is a span that automatically finishes. It does this by tracking child spans as activities.\n * An idle span is always the active span.\n */\nexport function startIdleSpan(startSpanOptions: StartSpanOptions, options: Partial = {}): Span {\n // Activities store a list of active spans\n const activities = new Map();\n\n // We should not use heartbeat if we finished a span\n let _finished = false;\n\n // Timer that tracks idleTimeout\n let _idleTimeoutID: ReturnType | undefined;\n\n // Timer that tracks maxSpanTime for child spans\n let _childSpanTimeoutID: ReturnType | undefined;\n\n // The reason why the span was finished\n let _finishReason: IdleSpanFinishReason = FINISH_REASON_EXTERNAL_FINISH;\n\n let _autoFinishAllowed: boolean = !options.disableAutoFinish;\n\n const _cleanupHooks: (() => void)[] = [];\n\n const {\n idleTimeout = TRACING_DEFAULTS.idleTimeout,\n finalTimeout = TRACING_DEFAULTS.finalTimeout,\n childSpanTimeout = TRACING_DEFAULTS.childSpanTimeout,\n beforeSpanEnd,\n trimIdleSpanEndTimestamp = true,\n } = options;\n\n const client = getClient();\n\n if (!client || !hasSpansEnabled()) {\n const span = new SentryNonRecordingSpan();\n\n const dsc = {\n sample_rate: '0',\n sampled: 'false',\n ...getDynamicSamplingContextFromSpan(span),\n } satisfies Partial;\n freezeDscOnSpan(span, dsc);\n\n return span;\n }\n\n const scope = getCurrentScope();\n const previousActiveSpan = getActiveSpan();\n const span = _startIdleSpan(startSpanOptions);\n\n // We patch span.end to ensure we can run some things before the span is ended\n // eslint-disable-next-line @typescript-eslint/unbound-method\n span.end = new Proxy(span.end, {\n apply(target, thisArg, args: Parameters) {\n if (beforeSpanEnd) {\n beforeSpanEnd(span);\n }\n\n // If the span is non-recording, nothing more to do here...\n // This is the case if tracing is enabled but this specific span was not sampled\n if (thisArg instanceof SentryNonRecordingSpan) {\n return;\n }\n\n // Just ensuring that this keeps working, even if we ever have more arguments here\n const [definedEndTimestamp, ...rest] = args;\n const timestamp = definedEndTimestamp || timestampInSeconds();\n const spanEndTimestamp = spanTimeInputToSeconds(timestamp);\n\n // Ensure we end with the last span timestamp, if possible\n const spans = getSpanDescendants(span).filter(child => child !== span);\n\n const spanJson = spanToJSON(span);\n\n // If we have no spans, we just end, nothing else to do here\n // Likewise, if users explicitly ended the span, we simply end the span without timestamp adjustment\n if (!spans.length || !trimIdleSpanEndTimestamp) {\n onIdleSpanEnded(spanEndTimestamp);\n return Reflect.apply(target, thisArg, [spanEndTimestamp, ...rest]);\n }\n\n const ignoreSpans = client.getOptions().ignoreSpans;\n\n const latestSpanEndTimestamp = spans?.reduce((acc: number | undefined, current) => {\n const currentSpanJson = spanToJSON(current);\n if (!currentSpanJson.timestamp) {\n return acc;\n }\n // Ignored spans will get dropped later (in the client) but since we already adjust\n // the idle span end timestamp here, we can already take to-be-ignored spans out of\n // the calculation here.\n if (ignoreSpans && shouldIgnoreSpan(currentSpanJson, ignoreSpans)) {\n return acc;\n }\n return acc ? Math.max(acc, currentSpanJson.timestamp) : currentSpanJson.timestamp;\n }, undefined);\n\n // In reality this should always exist here, but type-wise it may be undefined...\n const spanStartTimestamp = spanJson.start_timestamp;\n\n // The final endTimestamp should:\n // * Never be before the span start timestamp\n // * Be the latestSpanEndTimestamp, if there is one, and it is smaller than the passed span end timestamp\n // * Otherwise be the passed end timestamp\n // Final timestamp can never be after finalTimeout\n const endTimestamp = Math.min(\n spanStartTimestamp ? spanStartTimestamp + finalTimeout / 1000 : Infinity,\n Math.max(spanStartTimestamp || -Infinity, Math.min(spanEndTimestamp, latestSpanEndTimestamp || Infinity)),\n );\n\n onIdleSpanEnded(endTimestamp);\n return Reflect.apply(target, thisArg, [endTimestamp, ...rest]);\n },\n });\n\n /**\n * Cancels the existing idle timeout, if there is one.\n */\n function _cancelIdleTimeout(): void {\n if (_idleTimeoutID) {\n clearTimeout(_idleTimeoutID);\n _idleTimeoutID = undefined;\n }\n }\n\n /**\n * Cancels the existing child span timeout, if there is one.\n */\n function _cancelChildSpanTimeout(): void {\n if (_childSpanTimeoutID) {\n clearTimeout(_childSpanTimeoutID);\n _childSpanTimeoutID = undefined;\n }\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n function _restartIdleTimeout(endTimestamp?: number): void {\n _cancelIdleTimeout();\n _idleTimeoutID = setTimeout(() => {\n if (!_finished && activities.size === 0 && _autoFinishAllowed) {\n _finishReason = FINISH_REASON_IDLE_TIMEOUT;\n span.end(endTimestamp);\n }\n }, idleTimeout);\n }\n\n /**\n * Restarts child span timeout, if there is none running it will start one.\n */\n function _restartChildSpanTimeout(endTimestamp?: number): void {\n _cancelChildSpanTimeout();\n _idleTimeoutID = setTimeout(() => {\n if (!_finished && _autoFinishAllowed) {\n _finishReason = FINISH_REASON_HEARTBEAT_FAILED;\n span.end(endTimestamp);\n }\n }, childSpanTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n function _pushActivity(spanId: string): void {\n _cancelIdleTimeout();\n activities.set(spanId, true);\n\n const endTimestamp = timestampInSeconds();\n // We need to add the timeout here to have the real endtimestamp of the idle span\n // Remember timestampInSeconds is in seconds, timeout is in ms\n _restartChildSpanTimeout(endTimestamp + childSpanTimeout / 1000);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n function _popActivity(spanId: string): void {\n if (activities.has(spanId)) {\n activities.delete(spanId);\n }\n\n if (activities.size === 0) {\n const endTimestamp = timestampInSeconds();\n // We need to add the timeout here to have the real endtimestamp of the idle span\n // Remember timestampInSeconds is in seconds, timeout is in ms\n _restartIdleTimeout(endTimestamp + idleTimeout / 1000);\n _cancelChildSpanTimeout();\n }\n }\n\n function onIdleSpanEnded(endTimestamp: number): void {\n _finished = true;\n activities.clear();\n\n _cleanupHooks.forEach(cleanup => cleanup());\n\n _setSpanForScope(scope, previousActiveSpan);\n\n const spanJSON = spanToJSON(span);\n\n const { start_timestamp: startTimestamp } = spanJSON;\n // This should never happen, but to make TS happy...\n if (!startTimestamp) {\n return;\n }\n\n const attributes = spanJSON.data;\n if (!attributes[SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON]) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, _finishReason);\n }\n\n // Set span status to 'ok' if it hasn't been explicitly set to an error status\n const currentStatus = spanJSON.status;\n if (!currentStatus || currentStatus === 'unknown') {\n span.setStatus({ code: SPAN_STATUS_OK });\n }\n\n debug.log(`[Tracing] Idle span \"${spanJSON.op}\" finished`);\n\n const childSpans = getSpanDescendants(span).filter(child => child !== span);\n\n let discardedSpans = 0;\n childSpans.forEach(childSpan => {\n // We cancel all pending spans with status \"cancelled\" to indicate the idle span was finished early\n if (childSpan.isRecording()) {\n childSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n childSpan.end(endTimestamp);\n DEBUG_BUILD &&\n debug.log('[Tracing] Cancelling span since span ended early', JSON.stringify(childSpan, undefined, 2));\n }\n\n const childSpanJSON = spanToJSON(childSpan);\n const { timestamp: childEndTimestamp = 0, start_timestamp: childStartTimestamp = 0 } = childSpanJSON;\n\n const spanStartedBeforeIdleSpanEnd = childStartTimestamp <= endTimestamp;\n\n // Add a delta with idle timeout so that we prevent false positives\n const timeoutWithMarginOfError = (finalTimeout + idleTimeout) / 1000;\n const spanEndedBeforeFinalTimeout = childEndTimestamp - childStartTimestamp <= timeoutWithMarginOfError;\n\n if (DEBUG_BUILD) {\n const stringifiedSpan = JSON.stringify(childSpan, undefined, 2);\n if (!spanStartedBeforeIdleSpanEnd) {\n debug.log('[Tracing] Discarding span since it happened after idle span was finished', stringifiedSpan);\n } else if (!spanEndedBeforeFinalTimeout) {\n debug.log('[Tracing] Discarding span since it finished after idle span final timeout', stringifiedSpan);\n }\n }\n\n if (!spanEndedBeforeFinalTimeout || !spanStartedBeforeIdleSpanEnd) {\n removeChildSpanFromSpan(span, childSpan);\n discardedSpans++;\n }\n });\n\n if (discardedSpans > 0) {\n span.setAttribute('sentry.idle_span_discarded_spans', discardedSpans);\n }\n }\n\n _cleanupHooks.push(\n client.on('spanStart', startedSpan => {\n // If we already finished the idle span,\n // or if this is the idle span itself being started,\n // or if the started span has already been closed,\n // we don't care about it for activity\n if (\n _finished ||\n startedSpan === span ||\n !!spanToJSON(startedSpan).timestamp ||\n (startedSpan instanceof SentrySpan && startedSpan.isStandaloneSpan())\n ) {\n return;\n }\n\n const allSpans = getSpanDescendants(span);\n\n // If the span that was just started is a child of the idle span, we should track it\n if (allSpans.includes(startedSpan)) {\n _pushActivity(startedSpan.spanContext().spanId);\n }\n }),\n );\n\n _cleanupHooks.push(\n client.on('spanEnd', endedSpan => {\n if (_finished) {\n return;\n }\n\n _popActivity(endedSpan.spanContext().spanId);\n }),\n );\n\n _cleanupHooks.push(\n client.on('idleSpanEnableAutoFinish', spanToAllowAutoFinish => {\n if (spanToAllowAutoFinish === span) {\n _autoFinishAllowed = true;\n _restartIdleTimeout();\n\n if (activities.size) {\n _restartChildSpanTimeout();\n }\n }\n }),\n );\n\n // We only start the initial idle timeout if we are not delaying the auto finish\n if (!options.disableAutoFinish) {\n _restartIdleTimeout();\n }\n\n setTimeout(() => {\n if (!_finished) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'deadline_exceeded' });\n _finishReason = FINISH_REASON_FINAL_TIMEOUT;\n span.end();\n }\n }, finalTimeout);\n\n return span;\n}\n\nfunction _startIdleSpan(options: StartSpanOptions): Span {\n const span = startInactiveSpan(options);\n\n _setSpanForScope(getCurrentScope(), span);\n\n DEBUG_BUILD && debug.log('[Tracing] Started span is an idle span');\n\n return span;\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst STATE_PENDING = 0;\nconst STATE_RESOLVED = 1;\nconst STATE_REJECTED = 2;\n\ntype State = typeof STATE_PENDING | typeof STATE_RESOLVED | typeof STATE_REJECTED;\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\ntype Executor = (resolve: (value?: T | PromiseLike | null) => void, reject: (reason?: any) => void) => void;\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nexport class SyncPromise implements PromiseLike {\n private _state: State;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]>;\n private _value: any;\n\n public constructor(executor: Executor) {\n this._state = STATE_PENDING;\n this._handlers = [];\n\n this._runExecutor(executor);\n }\n\n /** @inheritdoc */\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 /** @inheritdoc */\n public catch(\n onrejected?: ((reason: any) => TResult | PromiseLike) | null,\n ): PromiseLike {\n return this.then(val => val, onrejected);\n }\n\n /** @inheritdoc */\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 /** Excute the resolve/reject handlers. */\n private _executeHandlers(): void {\n if (this._state === STATE_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 === STATE_RESOLVED) {\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === STATE_REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n }\n\n /** Run the executor for the SyncPromise. */\n private _runExecutor(executor: Executor): void {\n const setResult = (state: State, value?: T | PromiseLike | any): void => {\n if (this._state !== STATE_PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike).then(resolve, reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n const resolve = (value: unknown): void => {\n setResult(STATE_RESOLVED, value);\n };\n\n const reject = (reason: unknown): void => {\n setResult(STATE_REJECTED, reason);\n };\n\n try {\n executor(resolve, reject);\n } catch (e) {\n reject(e);\n }\n }\n}\n", "import { DEBUG_BUILD } from './debug-build';\nimport type { Event, EventHint } from './types-hoist/event';\nimport type { EventProcessor } from './types-hoist/eventprocessor';\nimport { debug } from './utils/debug-logger';\nimport { isThenable } from './utils/is';\nimport { rejectedSyncPromise, resolvedSyncPromise } from './utils/syncpromise';\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 try {\n const result = _notifyEventProcessors(event, hint, processors, index);\n return isThenable(result) ? result : resolvedSyncPromise(result);\n } catch (error) {\n return rejectedSyncPromise(error);\n }\n}\n\nfunction _notifyEventProcessors(\n event: Event | null,\n hint: EventHint,\n processors: EventProcessor[],\n index: number,\n): Event | null | PromiseLike {\n const processor = processors[index];\n\n if (!event || !processor) {\n return event;\n }\n\n const result = processor({ ...event }, hint);\n\n DEBUG_BUILD && result === null && debug.log(`Event processor \"${processor.id || '?'}\" dropped event`);\n\n if (isThenable(result)) {\n return result.then(final => _notifyEventProcessors(final, hint, processors, index + 1));\n }\n\n return _notifyEventProcessors(result, hint, processors, index + 1);\n}\n", "import type { ScopeData } from '../scope';\nimport { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext';\nimport type { Breadcrumb } from '../types-hoist/breadcrumb';\nimport type { Event } from '../types-hoist/event';\nimport type { Span } from '../types-hoist/span';\nimport { merge } from './merge';\nimport { getRootSpan, 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 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\n data.sdkProcessingMetadata = merge(data.sdkProcessingMetadata, sdkProcessingMetadata, 2);\n\n if (level) {\n data.level = level;\n }\n\n if (transactionName) {\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 data[prop] = merge(data[prop], mergeVal, 1);\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 { extra, tags, user, contexts, level, transactionName } = data;\n\n if (Object.keys(extra).length) {\n event.extra = { ...extra, ...event.extra };\n }\n\n if (Object.keys(tags).length) {\n event.tags = { ...tags, ...event.tags };\n }\n\n if (Object.keys(user).length) {\n event.user = { ...user, ...event.user };\n }\n\n if (Object.keys(contexts).length) {\n event.contexts = { ...contexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n // transaction events get their `transaction` from the root span name\n if (transactionName && event.type !== 'transaction') {\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 = {\n trace: spanToTraceContext(span),\n ...event.contexts,\n };\n\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n ...event.sdkProcessingMetadata,\n };\n\n const rootSpan = getRootSpan(span);\n const transactionName = spanToJSON(rootSpan).description;\n if (transactionName && !event.transaction && event.type === 'transaction') {\n event.transaction = transactionName;\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\n ? Array.isArray(event.fingerprint)\n ? event.fingerprint\n : [event.fingerprint]\n : [];\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.length) {\n delete event.fingerprint;\n }\n}\n", "import type { DebugImage } from '../types-hoist/debugMeta';\nimport type { StackParser } from '../types-hoist/stacktrace';\nimport { GLOBAL_OBJ } from './worldwide';\n\ntype StackString = string;\ntype CachedResult = [string, string];\n\nlet parsedStackResults: Record | undefined;\nlet lastSentryKeysCount: number | undefined;\nlet lastNativeKeysCount: number | undefined;\nlet cachedFilenameDebugIds: Record | undefined;\n\n/**\n * Returns a map of filenames to debug identifiers.\n * Supports both proprietary _sentryDebugIds and native _debugIds (e.g., from Vercel) formats.\n */\nexport function getFilenameToDebugIdMap(stackParser: StackParser): Record {\n const sentryDebugIdMap = GLOBAL_OBJ._sentryDebugIds;\n const nativeDebugIdMap = GLOBAL_OBJ._debugIds;\n\n if (!sentryDebugIdMap && !nativeDebugIdMap) {\n return {};\n }\n\n const sentryDebugIdKeys = sentryDebugIdMap ? Object.keys(sentryDebugIdMap) : [];\n const nativeDebugIdKeys = nativeDebugIdMap ? Object.keys(nativeDebugIdMap) : [];\n\n // If the count of registered globals hasn't changed since the last call, we\n // can just return the cached result.\n if (\n cachedFilenameDebugIds &&\n sentryDebugIdKeys.length === lastSentryKeysCount &&\n nativeDebugIdKeys.length === lastNativeKeysCount\n ) {\n return cachedFilenameDebugIds;\n }\n\n lastSentryKeysCount = sentryDebugIdKeys.length;\n lastNativeKeysCount = nativeDebugIdKeys.length;\n\n // Build a map of filename -> debug_id from both sources\n cachedFilenameDebugIds = {};\n\n if (!parsedStackResults) {\n parsedStackResults = {};\n }\n\n const processDebugIds = (debugIdKeys: string[], debugIdMap: Record): void => {\n for (const key of debugIdKeys) {\n const debugId = debugIdMap[key];\n const result = parsedStackResults?.[key];\n\n if (result && cachedFilenameDebugIds && debugId) {\n // Use cached filename but update with current debug ID\n cachedFilenameDebugIds[result[0]] = debugId;\n // Update cached result with new debug ID\n if (parsedStackResults) {\n parsedStackResults[key] = [result[0], debugId];\n }\n } else if (debugId) {\n const parsedStack = stackParser(key);\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n const filename = stackFrame?.filename;\n\n if (filename && cachedFilenameDebugIds && parsedStackResults) {\n cachedFilenameDebugIds[filename] = debugId;\n parsedStackResults[key] = [filename, debugId];\n break;\n }\n }\n }\n }\n };\n\n if (sentryDebugIdMap) {\n processDebugIds(sentryDebugIdKeys, sentryDebugIdMap);\n }\n\n // Native _debugIds will override _sentryDebugIds if same file\n if (nativeDebugIdMap) {\n processDebugIds(nativeDebugIdKeys, nativeDebugIdMap);\n }\n\n return cachedFilenameDebugIds;\n}\n\n/**\n * Returns a list of debug images for the given resources.\n */\nexport function getDebugImagesForResources(\n stackParser: StackParser,\n resource_paths: ReadonlyArray,\n): DebugImage[] {\n const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);\n\n if (!filenameDebugIdMap) {\n return [];\n }\n\n const images: DebugImage[] = [];\n for (const path of resource_paths) {\n if (path && filenameDebugIdMap[path]) {\n images.push({\n type: 'sourcemap',\n code_file: path,\n debug_id: filenameDebugIdMap[path],\n });\n }\n }\n\n return images;\n}\n", "import type { Client } from '../client';\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getGlobalScope } from '../currentScopes';\nimport { notifyEventProcessors } from '../eventProcessors';\nimport type { CaptureContext, ScopeContext } from '../scope';\nimport { Scope } from '../scope';\nimport type { Event, EventHint } from '../types-hoist/event';\nimport type { ClientOptions } from '../types-hoist/options';\nimport type { StackParser } from '../types-hoist/stacktrace';\nimport { applyScopeDataToEvent, mergeScopeData } from './applyScopeDataToEvent';\nimport { getFilenameToDebugIdMap } from './debug-ids';\nimport { addExceptionMechanism, uuid4 } from './misc';\nimport { normalize } from './normalize';\nimport { truncate } from './string';\nimport { dateTimestampInSeconds } from './time';\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 * @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 if (client) {\n client.emit('applyFrameMetadata', event);\n }\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() : [];\n\n // This should be the last thing called, since we want that\n // {@link Scope.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 const eventProcessors = [\n ...clientEventProcessors,\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 *\n * Only exported for tests.\n *\n * @param event event instance to be enhanced\n */\nexport function applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength } = options;\n\n // empty strings do not make sense for environment, release, and dist\n // so we handle them the same as if they were not provided\n event.environment = event.environment || environment || DEFAULT_ENVIRONMENT;\n\n if (!event.release && release) {\n event.release = release;\n }\n\n if (!event.dist && dist) {\n event.dist = dist;\n }\n\n const request = event.request;\n if (request?.url && maxValueLength) {\n request.url = truncate(request.url, maxValueLength);\n }\n\n if (maxValueLength) {\n event.exception?.values?.forEach(exception => {\n if (exception.value) {\n // Truncates error messages\n exception.value = truncate(exception.value, maxValueLength);\n }\n });\n }\n}\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);\n\n event.exception?.values?.forEach(exception => {\n exception.stacktrace?.frames?.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\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 event.exception?.values?.forEach(exception => {\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\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.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id,\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?.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 return {\n ...span,\n ...(span.data && {\n data: normalize(span.data, depth, maxBreadth),\n }),\n };\n });\n }\n\n // event.contexts.flags (FeatureFlagContext) stores context for our feature\n // flag integrations. It has a greater nesting depth than our other typed\n // Contexts, so we re-normalize with a fixed depth of 3 here. We do not want\n // to skip this in case of conflicting, user-provided context.\n if (event.contexts?.flags && normalized.contexts) {\n normalized.contexts.flags = normalize(event.contexts.flags, 3, maxBreadth);\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(hint: CaptureContext | EventHint): hint is Scope | ((scope: Scope) => Scope) {\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 '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", "import { getClient, getCurrentScope, getIsolationScope, withIsolationScope } from './currentScopes';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { CaptureContext } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport { startNewTrace } from './tracing/trace';\nimport type { CheckIn, FinishedCheckIn, MonitorConfig } from './types-hoist/checkin';\nimport type { Event, EventHint } from './types-hoist/event';\nimport type { EventProcessor } from './types-hoist/eventprocessor';\nimport type { Extra, Extras } from './types-hoist/extra';\nimport type { Primitive } from './types-hoist/misc';\nimport type { Session, SessionContext } from './types-hoist/session';\nimport type { SeverityLevel } from './types-hoist/severity';\nimport type { User } from './types-hoist/user';\nimport { debug } from './utils/debug-logger';\nimport { isThenable } from './utils/is';\nimport { uuid4 } from './utils/misc';\nimport type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { timestampInSeconds } from './utils/time';\nimport { GLOBAL_OBJ } from './utils/worldwide';\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(exception: unknown, hint?: ExclusiveEventHintOrCaptureContext): string {\n return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\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(message: string, captureContext?: CaptureContext | SeverityLevel): 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 hint = typeof captureContext !== 'string' ? { captureContext } : undefined;\n return getCurrentScope().captureMessage(message, level, hint);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event 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 return getCurrentScope().captureEvent(event, 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 */\nexport function setContext(name: string, context: { [key: string]: unknown } | null): void {\n getIsolationScope().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 */\nexport function setExtras(extras: Extras): void {\n getIsolationScope().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 */\nexport function setExtra(key: string, extra: Extra): void {\n getIsolationScope().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 */\nexport function setTags(tags: { [key: string]: Primitive }): void {\n getIsolationScope().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 */\nexport function setTag(key: string, value: Primitive): void {\n getIsolationScope().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 */\nexport function setUser(user: User | null): void {\n getIsolationScope().setUser(user);\n}\n\n/**\n * The last error event id of the isolation scope.\n *\n * Warning: This function really returns the last recorded error event id on the current\n * isolation scope. If you call this function after handling a certain error and another error\n * is captured in between, the last one is returned instead of the one you might expect.\n * Also, ids of events that were never sent to Sentry (for example because\n * they were dropped in `beforeSend`) could be returned.\n *\n * @returns The last event id of the isolation scope.\n */\nexport function lastEventId(): string | undefined {\n return getIsolationScope().lastEventId();\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 && debug.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && debug.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 callback Callback to be monitored\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 function runCallback(): 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 // Default behavior without isolateTrace\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 return maybePromiseResult.then(\n r => {\n finishCheckIn('ok');\n return r;\n },\n e => {\n finishCheckIn('error');\n throw e;\n },\n ) as T;\n }\n finishCheckIn('ok');\n\n return maybePromiseResult;\n }\n\n return withIsolationScope(() => (upsertMonitorConfig?.isolateTrace ? startNewTrace(runCallback) : runCallback()));\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 && debug.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 && debug.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nexport function isInitialized(): boolean {\n return !!getClient();\n}\n\n/** If the SDK is initialized & enabled. */\nexport function isEnabled(): boolean {\n const client = getClient();\n return client?.getOptions().enabled !== false && !!client?.getTransport();\n}\n\n/**\n * Add an event processor.\n * This will be added to the current isolation scope, ensuring any event that is processed in the current execution\n * context will have the processor applied.\n */\nexport function addEventProcessor(callback: EventProcessor): void {\n getIsolationScope().addEventProcessor(callback);\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 isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\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?.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 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\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate(): void {\n const isolationScope = getIsolationScope();\n const client = getClient();\n const session = isolationScope.getSession();\n if (session && client) {\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 { ReportDialogOptions } from './report-dialog';\nimport type { DsnComponents, DsnLike } from './types-hoist/dsn';\nimport type { SdkInfo } from './types-hoist/sdkinfo';\nimport { dsnToString, makeDsn } from './utils/dsn';\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 const params: Record = {\n sentry_version: SENTRY_API_VERSION,\n };\n\n if (dsn.publicKey) {\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n params.sentry_key = dsn.publicKey;\n }\n\n if (sdkInfo) {\n params.sentry_client = `${sdkInfo.name}/${sdkInfo.version}`;\n }\n\n return new URLSearchParams(params).toString();\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(dsn: DsnComponents, tunnel?: string, sdkInfo?: SdkInfo): string {\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(dsnLike: DsnLike, dialogOptions: ReportDialogOptions): 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 type { Client } from './client';\nimport { getClient } from './currentScopes';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Event, EventHint } from './types-hoist/event';\nimport type { Integration, IntegrationFn } from './types-hoist/integration';\nimport type { CoreOptions } from './types-hoist/options';\nimport { debug } from './utils/debug-logger';\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n};\n\ntype IntegrationWithDefaultInstance = Integration & { isDefaultInstance?: true };\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preserve 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: IntegrationWithDefaultInstance) => {\n const { name } = currentInstance;\n\n const existingInstance: IntegrationWithDefaultInstance | undefined = 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.values(integrationsByName);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(\n options: Pick,\n): 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: IntegrationWithDefaultInstance) => {\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 const resolvedUserIntegrations = userIntegrations(defaultIntegrations);\n integrations = Array.isArray(resolvedUserIntegrations) ? resolvedUserIntegrations : [resolvedUserIntegrations];\n } else {\n integrations = defaultIntegrations;\n }\n\n return filterDuplicates(integrations);\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: Integration | undefined) => {\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?.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 && debug.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.includes(integration.name) && typeof integration.setupOnce === 'function') {\n integration.setupOnce();\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 (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 (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 && debug.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current scope's client. */\nexport function addIntegration(integration: Integration): void {\n const client = getClient();\n\n if (!client) {\n DEBUG_BUILD && debug.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\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) => Integration {\n return fn;\n}\n", "import type { DsnComponents } from '../types-hoist/dsn';\nimport type { LogContainerItem, LogEnvelope } from '../types-hoist/envelope';\nimport type { SerializedLog } from '../types-hoist/log';\nimport type { SdkMetadata } from '../types-hoist/sdkmetadata';\nimport { dsnToString } from '../utils/dsn';\nimport { createEnvelope } from '../utils/envelope';\n\n/**\n * Creates a log container envelope item for a list of logs.\n *\n * @param items - The logs to include in the envelope.\n * @returns The created log container envelope item.\n */\nexport function createLogContainerEnvelopeItem(items: Array): LogContainerItem {\n return [\n {\n type: 'log',\n item_count: items.length,\n content_type: 'application/vnd.sentry.items.log+json',\n },\n {\n items,\n },\n ];\n}\n\n/**\n * Creates an envelope for a list of logs.\n *\n * Logs from multiple traces can be included in the same envelope.\n *\n * @param logs - The logs to include in the envelope.\n * @param metadata - The metadata to include in the envelope.\n * @param tunnel - The tunnel to include in the envelope.\n * @param dsn - The DSN to include in the envelope.\n * @returns The created envelope.\n */\nexport function createLogEnvelope(\n logs: Array,\n metadata?: SdkMetadata,\n tunnel?: string,\n dsn?: DsnComponents,\n): LogEnvelope {\n const headers: LogEnvelope[0] = {};\n\n if (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 return createEnvelope(headers, [createLogContainerEnvelopeItem(logs)]);\n}\n", "import { getGlobalSingleton } from '../carrier';\nimport type { Client } from '../client';\nimport { getClient, getCurrentScope, getGlobalScope, getIsolationScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Scope, ScopeData } from '../scope';\nimport type { Integration } from '../types-hoist/integration';\nimport type { Log, SerializedLog, SerializedLogAttributeValue } from '../types-hoist/log';\nimport { mergeScopeData } from '../utils/applyScopeDataToEvent';\nimport { consoleSandbox, debug } from '../utils/debug-logger';\nimport { isParameterizedString } from '../utils/is';\nimport { _getSpanForScope } from '../utils/spanOnScope';\nimport { timestampInSeconds } from '../utils/time';\nimport { _getTraceInfoFromScope } from '../utils/trace-info';\nimport { SEVERITY_TEXT_TO_SEVERITY_NUMBER } from './constants';\nimport { createLogEnvelope } from './envelope';\n\nconst MAX_LOG_BUFFER_SIZE = 100;\n\n/**\n * Converts a log attribute to a serialized log attribute.\n *\n * @param key - The key of the log attribute.\n * @param value - The value of the log attribute.\n * @returns The serialized log attribute.\n */\nexport function logAttributeToSerializedLogAttribute(value: unknown): SerializedLogAttributeValue {\n switch (typeof value) {\n case 'number':\n if (Number.isInteger(value)) {\n return {\n value,\n type: 'integer',\n };\n }\n return {\n value,\n type: 'double',\n };\n case 'boolean':\n return {\n value,\n type: 'boolean',\n };\n case 'string':\n return {\n value,\n type: 'string',\n };\n default: {\n let stringValue = '';\n try {\n stringValue = JSON.stringify(value) ?? '';\n } catch {\n // Do nothing\n }\n return {\n value: stringValue,\n type: 'string',\n };\n }\n }\n}\n\n/**\n * Sets a log attribute if the value exists and the attribute key is not already present.\n *\n * @param logAttributes - The log attributes object to modify.\n * @param key - The attribute key to set.\n * @param value - The value to set (only sets if truthy and key not present).\n * @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.\n */\nfunction setLogAttribute(\n logAttributes: Record,\n key: string,\n value: unknown,\n setEvenIfPresent = true,\n): void {\n if (value && (!logAttributes[key] || setEvenIfPresent)) {\n logAttributes[key] = value;\n }\n}\n\n/**\n * Captures a serialized log event and adds it to the log buffer for the given client.\n *\n * @param client - A client. Uses the current client if not provided.\n * @param serializedLog - The serialized log event to capture.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_captureSerializedLog(client: Client, serializedLog: SerializedLog): void {\n const bufferMap = _getBufferMap();\n const logBuffer = _INTERNAL_getLogBuffer(client);\n\n if (logBuffer === undefined) {\n bufferMap.set(client, [serializedLog]);\n } else {\n if (logBuffer.length >= MAX_LOG_BUFFER_SIZE) {\n _INTERNAL_flushLogsBuffer(client, logBuffer);\n bufferMap.set(client, [serializedLog]);\n } else {\n bufferMap.set(client, [...logBuffer, serializedLog]);\n }\n }\n}\n\n/**\n * Captures a log event and sends it to Sentry.\n *\n * @param log - The log event to capture.\n * @param scope - A scope. Uses the current scope if not provided.\n * @param client - A client. Uses the current client if not provided.\n * @param captureSerializedLog - A function to capture the serialized log.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_captureLog(\n beforeLog: Log,\n currentScope = getCurrentScope(),\n captureSerializedLog: (client: Client, log: SerializedLog) => void = _INTERNAL_captureSerializedLog,\n): void {\n const client = currentScope?.getClient() ?? getClient();\n if (!client) {\n DEBUG_BUILD && debug.warn('No client available to capture log.');\n return;\n }\n\n const { release, environment, enableLogs = false, beforeSendLog } = client.getOptions();\n if (!enableLogs) {\n DEBUG_BUILD && debug.warn('logging option not enabled, log will not be captured.');\n return;\n }\n\n const [, traceContext] = _getTraceInfoFromScope(client, currentScope);\n\n const processedLogAttributes = {\n ...beforeLog.attributes,\n };\n\n const {\n user: { id, email, username },\n } = getMergedScopeData(currentScope);\n setLogAttribute(processedLogAttributes, 'user.id', id, false);\n setLogAttribute(processedLogAttributes, 'user.email', email, false);\n setLogAttribute(processedLogAttributes, 'user.name', username, false);\n\n setLogAttribute(processedLogAttributes, 'sentry.release', release);\n setLogAttribute(processedLogAttributes, 'sentry.environment', environment);\n\n const { name, version } = client.getSdkMetadata()?.sdk ?? {};\n setLogAttribute(processedLogAttributes, 'sentry.sdk.name', name);\n setLogAttribute(processedLogAttributes, 'sentry.sdk.version', version);\n\n const replay = client.getIntegrationByName<\n Integration & {\n getReplayId: (onlyIfSampled?: boolean) => string;\n getRecordingMode: () => 'session' | 'buffer' | undefined;\n }\n >('Replay');\n\n const replayId = replay?.getReplayId(true);\n setLogAttribute(processedLogAttributes, 'sentry.replay_id', replayId);\n\n if (replayId && replay?.getRecordingMode() === 'buffer') {\n // We send this so we can identify cases where the replayId is attached but the replay itself might not have been sent to Sentry\n setLogAttribute(processedLogAttributes, 'sentry._internal.replay_is_buffering', true);\n }\n\n const beforeLogMessage = beforeLog.message;\n if (isParameterizedString(beforeLogMessage)) {\n const { __sentry_template_string__, __sentry_template_values__ = [] } = beforeLogMessage;\n if (__sentry_template_values__?.length) {\n processedLogAttributes['sentry.message.template'] = __sentry_template_string__;\n }\n __sentry_template_values__.forEach((param, index) => {\n processedLogAttributes[`sentry.message.parameter.${index}`] = param;\n });\n }\n\n const span = _getSpanForScope(currentScope);\n // Add the parent span ID to the log attributes for trace context\n setLogAttribute(processedLogAttributes, 'sentry.trace.parent_span_id', span?.spanContext().spanId);\n\n const processedLog = { ...beforeLog, attributes: processedLogAttributes };\n\n client.emit('beforeCaptureLog', processedLog);\n\n // We need to wrap this in `consoleSandbox` to avoid recursive calls to `beforeSendLog`\n const log = beforeSendLog ? consoleSandbox(() => beforeSendLog(processedLog)) : processedLog;\n if (!log) {\n client.recordDroppedEvent('before_send', 'log_item', 1);\n DEBUG_BUILD && debug.warn('beforeSendLog returned null, log will not be captured.');\n return;\n }\n\n const { level, message, attributes = {}, severityNumber } = log;\n\n const serializedLog: SerializedLog = {\n timestamp: timestampInSeconds(),\n level,\n body: message,\n trace_id: traceContext?.trace_id,\n severity_number: severityNumber ?? SEVERITY_TEXT_TO_SEVERITY_NUMBER[level],\n attributes: Object.keys(attributes).reduce(\n (acc, key) => {\n acc[key] = logAttributeToSerializedLogAttribute(attributes[key]);\n return acc;\n },\n {} as Record,\n ),\n };\n\n captureSerializedLog(client, serializedLog);\n\n client.emit('afterCaptureLog', log);\n}\n\n/**\n * Flushes the logs buffer to Sentry.\n *\n * @param client - A client.\n * @param maybeLogBuffer - A log buffer. Uses the log buffer for the given client if not provided.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_flushLogsBuffer(client: Client, maybeLogBuffer?: Array): void {\n const logBuffer = maybeLogBuffer ?? _INTERNAL_getLogBuffer(client) ?? [];\n if (logBuffer.length === 0) {\n return;\n }\n\n const clientOptions = client.getOptions();\n const envelope = createLogEnvelope(logBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn());\n\n // Clear the log buffer after envelopes have been constructed.\n _getBufferMap().set(client, []);\n\n client.emit('flushLogs');\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n client.sendEnvelope(envelope);\n}\n\n/**\n * Returns the log buffer for a given client.\n *\n * Exported for testing purposes.\n *\n * @param client - The client to get the log buffer for.\n * @returns The log buffer for the given client.\n */\nexport function _INTERNAL_getLogBuffer(client: Client): Array | undefined {\n return _getBufferMap().get(client);\n}\n\n/**\n * Get the scope data for the current scope after merging with the\n * global scope and isolation scope.\n *\n * @param currentScope - The current scope.\n * @returns The scope data.\n */\nfunction getMergedScopeData(currentScope: Scope): ScopeData {\n const scopeData = getGlobalScope().getScopeData();\n mergeScopeData(scopeData, getIsolationScope().getScopeData());\n mergeScopeData(scopeData, currentScope.getScopeData());\n return scopeData;\n}\n\nfunction _getBufferMap(): WeakMap> {\n // The reference to the Client <> LogBuffer map is stored on the carrier to ensure it's always the same\n return getGlobalSingleton('clientToLogBufferMap', () => new WeakMap>());\n}\n", "import type { DsnComponents } from '../types-hoist/dsn';\nimport type { MetricContainerItem, MetricEnvelope } from '../types-hoist/envelope';\nimport type { SerializedMetric } from '../types-hoist/metric';\nimport type { SdkMetadata } from '../types-hoist/sdkmetadata';\nimport { dsnToString } from '../utils/dsn';\nimport { createEnvelope } from '../utils/envelope';\n\n/**\n * Creates a metric container envelope item for a list of metrics.\n *\n * @param items - The metrics to include in the envelope.\n * @returns The created metric container envelope item.\n */\nexport function createMetricContainerEnvelopeItem(items: Array): MetricContainerItem {\n return [\n {\n type: 'trace_metric',\n item_count: items.length,\n content_type: 'application/vnd.sentry.items.trace-metric+json',\n } as MetricContainerItem[0],\n {\n items,\n },\n ];\n}\n\n/**\n * Creates an envelope for a list of metrics.\n *\n * Metrics from multiple traces can be included in the same envelope.\n *\n * @param metrics - The metrics to include in the envelope.\n * @param metadata - The metadata to include in the envelope.\n * @param tunnel - The tunnel to include in the envelope.\n * @param dsn - The DSN to include in the envelope.\n * @returns The created envelope.\n */\nexport function createMetricEnvelope(\n metrics: Array,\n metadata?: SdkMetadata,\n tunnel?: string,\n dsn?: DsnComponents,\n): MetricEnvelope {\n const headers: MetricEnvelope[0] = {};\n\n if (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 return createEnvelope(headers, [createMetricContainerEnvelopeItem(metrics)]);\n}\n", "import { getGlobalSingleton } from '../carrier';\nimport type { Client } from '../client';\nimport { getClient, getCurrentScope, getGlobalScope, getIsolationScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Scope, ScopeData } from '../scope';\nimport type { Integration } from '../types-hoist/integration';\nimport type { Metric, SerializedMetric, SerializedMetricAttributeValue } from '../types-hoist/metric';\nimport { mergeScopeData } from '../utils/applyScopeDataToEvent';\nimport { debug } from '../utils/debug-logger';\nimport { _getSpanForScope } from '../utils/spanOnScope';\nimport { timestampInSeconds } from '../utils/time';\nimport { _getTraceInfoFromScope } from '../utils/trace-info';\nimport { createMetricEnvelope } from './envelope';\n\nconst MAX_METRIC_BUFFER_SIZE = 1000;\n\n/**\n * Converts a metric attribute to a serialized metric attribute.\n *\n * @param value - The value of the metric attribute.\n * @returns The serialized metric attribute.\n */\nexport function metricAttributeToSerializedMetricAttribute(value: unknown): SerializedMetricAttributeValue {\n switch (typeof value) {\n case 'number':\n if (Number.isInteger(value)) {\n return {\n value,\n type: 'integer',\n };\n }\n return {\n value,\n type: 'double',\n };\n case 'boolean':\n return {\n value,\n type: 'boolean',\n };\n case 'string':\n return {\n value,\n type: 'string',\n };\n default: {\n let stringValue = '';\n try {\n stringValue = JSON.stringify(value) ?? '';\n } catch {\n // Do nothing\n }\n return {\n value: stringValue,\n type: 'string',\n };\n }\n }\n}\n\n/**\n * Sets a metric attribute if the value exists and the attribute key is not already present.\n *\n * @param metricAttributes - The metric attributes object to modify.\n * @param key - The attribute key to set.\n * @param value - The value to set (only sets if truthy and key not present).\n * @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.\n */\nfunction setMetricAttribute(\n metricAttributes: Record,\n key: string,\n value: unknown,\n setEvenIfPresent = true,\n): void {\n if (value && (setEvenIfPresent || !(key in metricAttributes))) {\n metricAttributes[key] = value;\n }\n}\n\n/**\n * Captures a serialized metric event and adds it to the metric buffer for the given client.\n *\n * @param client - A client. Uses the current client if not provided.\n * @param serializedMetric - The serialized metric event to capture.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_captureSerializedMetric(client: Client, serializedMetric: SerializedMetric): void {\n const bufferMap = _getBufferMap();\n const metricBuffer = _INTERNAL_getMetricBuffer(client);\n\n if (metricBuffer === undefined) {\n bufferMap.set(client, [serializedMetric]);\n } else {\n if (metricBuffer.length >= MAX_METRIC_BUFFER_SIZE) {\n _INTERNAL_flushMetricsBuffer(client, metricBuffer);\n bufferMap.set(client, [serializedMetric]);\n } else {\n bufferMap.set(client, [...metricBuffer, serializedMetric]);\n }\n }\n}\n\n/**\n * Options for capturing a metric internally.\n */\nexport interface InternalCaptureMetricOptions {\n /**\n * The scope to capture the metric with.\n */\n scope?: Scope;\n\n /**\n * A function to capture the serialized metric.\n */\n captureSerializedMetric?: (client: Client, metric: SerializedMetric) => void;\n}\n\n/**\n * Enriches metric with all contextual attributes (user, SDK metadata, replay, etc.)\n */\nfunction _enrichMetricAttributes(beforeMetric: Metric, client: Client, currentScope: Scope): Metric {\n const { release, environment } = client.getOptions();\n\n const processedMetricAttributes = {\n ...beforeMetric.attributes,\n };\n\n // Add user attributes\n const {\n user: { id, email, username },\n } = getMergedScopeData(currentScope);\n setMetricAttribute(processedMetricAttributes, 'user.id', id, false);\n setMetricAttribute(processedMetricAttributes, 'user.email', email, false);\n setMetricAttribute(processedMetricAttributes, 'user.name', username, false);\n\n // Add Sentry metadata\n setMetricAttribute(processedMetricAttributes, 'sentry.release', release);\n setMetricAttribute(processedMetricAttributes, 'sentry.environment', environment);\n\n // Add SDK metadata\n const { name, version } = client.getSdkMetadata()?.sdk ?? {};\n setMetricAttribute(processedMetricAttributes, 'sentry.sdk.name', name);\n setMetricAttribute(processedMetricAttributes, 'sentry.sdk.version', version);\n\n // Add replay metadata\n const replay = client.getIntegrationByName<\n Integration & {\n getReplayId: (onlyIfSampled?: boolean) => string;\n getRecordingMode: () => 'session' | 'buffer' | undefined;\n }\n >('Replay');\n\n const replayId = replay?.getReplayId(true);\n setMetricAttribute(processedMetricAttributes, 'sentry.replay_id', replayId);\n\n if (replayId && replay?.getRecordingMode() === 'buffer') {\n setMetricAttribute(processedMetricAttributes, 'sentry._internal.replay_is_buffering', true);\n }\n\n return {\n ...beforeMetric,\n attributes: processedMetricAttributes,\n };\n}\n\n/**\n * Creates a serialized metric ready to be sent to Sentry.\n */\nfunction _buildSerializedMetric(metric: Metric, client: Client, currentScope: Scope): SerializedMetric {\n // Serialize attributes\n const serializedAttributes: Record = {};\n for (const key in metric.attributes) {\n if (metric.attributes[key] !== undefined) {\n serializedAttributes[key] = metricAttributeToSerializedMetricAttribute(metric.attributes[key]);\n }\n }\n\n // Get trace context\n const [, traceContext] = _getTraceInfoFromScope(client, currentScope);\n const span = _getSpanForScope(currentScope);\n const traceId = span ? span.spanContext().traceId : traceContext?.trace_id;\n const spanId = span ? span.spanContext().spanId : undefined;\n\n return {\n timestamp: timestampInSeconds(),\n trace_id: traceId ?? '',\n span_id: spanId,\n name: metric.name,\n type: metric.type,\n unit: metric.unit,\n value: metric.value,\n attributes: serializedAttributes,\n };\n}\n\n/**\n * Captures a metric event and sends it to Sentry.\n *\n * @param metric - The metric event to capture.\n * @param options - Options for capturing the metric.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_captureMetric(beforeMetric: Metric, options?: InternalCaptureMetricOptions): void {\n const currentScope = options?.scope ?? getCurrentScope();\n const captureSerializedMetric = options?.captureSerializedMetric ?? _INTERNAL_captureSerializedMetric;\n const client = currentScope?.getClient() ?? getClient();\n if (!client) {\n DEBUG_BUILD && debug.warn('No client available to capture metric.');\n return;\n }\n\n const { _experiments, enableMetrics, beforeSendMetric } = client.getOptions();\n\n // todo(v11): Remove the experimental flag\n // eslint-disable-next-line deprecation/deprecation\n const metricsEnabled = enableMetrics ?? _experiments?.enableMetrics ?? true;\n\n if (!metricsEnabled) {\n DEBUG_BUILD && debug.warn('metrics option not enabled, metric will not be captured.');\n return;\n }\n\n // Enrich metric with contextual attributes\n const enrichedMetric = _enrichMetricAttributes(beforeMetric, client, currentScope);\n\n client.emit('processMetric', enrichedMetric);\n\n // todo(v11): Remove the experimental `beforeSendMetric`\n // eslint-disable-next-line deprecation/deprecation\n const beforeSendCallback = beforeSendMetric || _experiments?.beforeSendMetric;\n const processedMetric = beforeSendCallback ? beforeSendCallback(enrichedMetric) : enrichedMetric;\n\n if (!processedMetric) {\n DEBUG_BUILD && debug.log('`beforeSendMetric` returned `null`, will not send metric.');\n return;\n }\n\n const serializedMetric = _buildSerializedMetric(processedMetric, client, currentScope);\n\n DEBUG_BUILD && debug.log('[Metric]', serializedMetric);\n\n captureSerializedMetric(client, serializedMetric);\n\n client.emit('afterCaptureMetric', processedMetric);\n}\n\n/**\n * Flushes the metrics buffer to Sentry.\n *\n * @param client - A client.\n * @param maybeMetricBuffer - A metric buffer. Uses the metric buffer for the given client if not provided.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_flushMetricsBuffer(client: Client, maybeMetricBuffer?: Array): void {\n const metricBuffer = maybeMetricBuffer ?? _INTERNAL_getMetricBuffer(client) ?? [];\n if (metricBuffer.length === 0) {\n return;\n }\n\n const clientOptions = client.getOptions();\n const envelope = createMetricEnvelope(metricBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn());\n\n // Clear the metric buffer after envelopes have been constructed.\n _getBufferMap().set(client, []);\n\n client.emit('flushMetrics');\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n client.sendEnvelope(envelope);\n}\n\n/**\n * Returns the metric buffer for a given client.\n *\n * Exported for testing purposes.\n *\n * @param client - The client to get the metric buffer for.\n * @returns The metric buffer for the given client.\n */\nexport function _INTERNAL_getMetricBuffer(client: Client): Array | undefined {\n return _getBufferMap().get(client);\n}\n\n/**\n * Get the scope data for the current scope after merging with the\n * global scope and isolation scope.\n *\n * @param currentScope - The current scope.\n * @returns The scope data.\n */\nfunction getMergedScopeData(currentScope: Scope): ScopeData {\n const scopeData = getGlobalScope().getScopeData();\n mergeScopeData(scopeData, getIsolationScope().getScopeData());\n mergeScopeData(scopeData, currentScope.getScopeData());\n return scopeData;\n}\n\nfunction _getBufferMap(): WeakMap> {\n // The reference to the Client <> MetricBuffer map is stored on the carrier to ensure it's always the same\n return getGlobalSingleton('clientToMetricBufferMap', () => new WeakMap>());\n}\n", "import { 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 $: PromiseLike[];\n add(taskProducer: () => PromiseLike): PromiseLike;\n drain(timeout?: number): PromiseLike;\n}\n\nexport const SENTRY_BUFFER_FULL_ERROR = Symbol.for('SentryBufferFullError');\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 = 100): PromiseBuffer {\n const buffer: Set> = new Set();\n\n function isReady(): boolean {\n return buffer.size < 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): void {\n buffer.delete(task);\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(SENTRY_BUFFER_FULL_ERROR);\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n buffer.add(task);\n void task.then(\n () => remove(task),\n () => remove(task),\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 if (!buffer.size) {\n return resolvedSyncPromise(true);\n }\n\n // We want to resolve even if one of the promises rejects\n const drainPromise = Promise.allSettled(Array.from(buffer)).then(() => true);\n\n if (!timeout) {\n return drainPromise;\n }\n\n const promises = [drainPromise, new Promise(resolve => setTimeout(() => resolve(false), timeout))];\n\n // Promise.race will resolve to the first promise that resolves or rejects\n // So if the drainPromise resolves, the timeout promise will be ignored\n return Promise.race(promises);\n }\n\n return {\n get $(): PromiseLike[] {\n return Array.from(buffer);\n },\n add,\n drain,\n };\n}\n", "import type { DataCategory } from '../types-hoist/datacategory';\nimport type { TransportMakeRequestResponse } from '../types-hoist/transport';\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?.['x-sentry-rate-limits'];\n const retryAfterHeader = 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) as [string, ...string[]];\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 { DEBUG_BUILD } from '../debug-build';\nimport type { EventDropReason } from '../types-hoist/clientreport';\nimport type { Envelope, EnvelopeItem } from '../types-hoist/envelope';\nimport type {\n InternalBaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequestExecutor,\n} from '../types-hoist/transport';\nimport { debug } from '../utils/debug-logger';\nimport {\n createEnvelope,\n envelopeItemTypeToDataCategory,\n forEachEnvelopeItem,\n serializeEnvelope,\n} from '../utils/envelope';\nimport { makePromiseBuffer, type PromiseBuffer, SENTRY_BUFFER_FULL_ERROR } from '../utils/promisebuffer';\nimport { isRateLimited, type RateLimits, updateRateLimits } from '../utils/ratelimit';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 64;\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 options.recordDroppedEvent('ratelimit_backoff', dataCategory);\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 Promise.resolve({});\n }\n\n const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as (typeof envelope)[1]);\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason: EventDropReason): void => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type));\n });\n };\n\n const requestTask = (): PromiseLike =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope) }).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 && debug.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 DEBUG_BUILD && debug.error('Encountered error running transport request:', error);\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error === SENTRY_BUFFER_FULL_ERROR) {\n DEBUG_BUILD && debug.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return Promise.resolve({});\n } else {\n throw error;\n }\n },\n );\n }\n\n return {\n send,\n flush,\n };\n}\n", "import type { ClientReport } from '../types-hoist/clientreport';\nimport type { ClientReportEnvelope, ClientReportItem } from '../types-hoist/envelope';\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", "import type { Event } from '../types-hoist/event';\n\n/**\n * Get a list of possible event messages from a Sentry event.\n */\nexport function getPossibleEventMessages(event: Event): string[] {\n const possibleMessages: string[] = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n try {\n // @ts-expect-error Try catching to save bundle size\n const lastException = event.exception.values[event.exception.values.length - 1];\n if (lastException?.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n } catch {\n // ignore errors here\n }\n\n return possibleMessages;\n}\n", "import { SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_PROFILE_ID } from '../semanticAttributes';\nimport type { TransactionEvent } from '../types-hoist/event';\nimport type { SpanJSON } from '../types-hoist/span';\n\n/**\n * Converts a transaction event to a span JSON object.\n */\nexport function convertTransactionEventToSpanJson(event: TransactionEvent): SpanJSON {\n const { trace_id, parent_span_id, span_id, status, origin, data, op } = event.contexts?.trace ?? {};\n\n return {\n data: data ?? {},\n description: event.transaction,\n op,\n parent_span_id,\n span_id: span_id ?? '',\n start_timestamp: event.start_timestamp ?? 0,\n status,\n timestamp: event.timestamp,\n trace_id: trace_id ?? '',\n origin,\n profile_id: data?.[SEMANTIC_ATTRIBUTE_PROFILE_ID] as string | undefined,\n exclusive_time: data?.[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME] as number | undefined,\n measurements: event.measurements,\n is_segment: true,\n };\n}\n\n/**\n * Converts a span JSON object to a transaction event.\n */\nexport function convertSpanJsonToTransactionEvent(span: SpanJSON): TransactionEvent {\n return {\n type: 'transaction',\n timestamp: span.timestamp,\n start_timestamp: span.start_timestamp,\n transaction: span.description,\n contexts: {\n trace: {\n trace_id: span.trace_id,\n span_id: span.span_id,\n parent_span_id: span.parent_span_id,\n op: span.op,\n status: span.status,\n origin: span.origin,\n data: {\n ...span.data,\n ...(span.profile_id && { [SEMANTIC_ATTRIBUTE_PROFILE_ID]: span.profile_id }),\n ...(span.exclusive_time && { [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: span.exclusive_time }),\n },\n },\n },\n measurements: span.measurements,\n };\n}\n", "/* eslint-disable max-lines */\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { getCurrentScope, getIsolationScope, getTraceContextFromScope } from './currentScopes';\nimport { DEBUG_BUILD } from './debug-build';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport type { IntegrationIndex } from './integration';\nimport { afterSetupIntegrations, setupIntegration, setupIntegrations } from './integration';\nimport { _INTERNAL_flushLogsBuffer } from './logs/internal';\nimport { _INTERNAL_flushMetricsBuffer } from './metrics/internal';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { getDynamicSamplingContextFromScope } from './tracing/dynamicSamplingContext';\nimport { DEFAULT_TRANSPORT_BUFFER_SIZE } from './transports/base';\nimport type { Breadcrumb, BreadcrumbHint, FetchBreadcrumbHint, XhrBreadcrumbHint } from './types-hoist/breadcrumb';\nimport type { CheckIn, MonitorConfig } from './types-hoist/checkin';\nimport type { EventDropReason, Outcome } from './types-hoist/clientreport';\nimport type { DataCategory } from './types-hoist/datacategory';\nimport type { DsnComponents } from './types-hoist/dsn';\nimport type { DynamicSamplingContext, Envelope } from './types-hoist/envelope';\nimport type { ErrorEvent, Event, EventHint, EventType, TransactionEvent } from './types-hoist/event';\nimport type { EventProcessor } from './types-hoist/eventprocessor';\nimport type { FeedbackEvent } from './types-hoist/feedback';\nimport type { Integration } from './types-hoist/integration';\nimport type { Log } from './types-hoist/log';\nimport type { Metric } from './types-hoist/metric';\nimport type { Primitive } from './types-hoist/misc';\nimport type { ClientOptions } from './types-hoist/options';\nimport type { ParameterizedString } from './types-hoist/parameterize';\nimport type { RequestEventData } from './types-hoist/request';\nimport type { SdkMetadata } from './types-hoist/sdkmetadata';\nimport type { Session, SessionAggregates } from './types-hoist/session';\nimport type { SeverityLevel } from './types-hoist/severity';\nimport type { Span, SpanAttributes, SpanContextData, SpanJSON } from './types-hoist/span';\nimport type { StartSpanOptions } from './types-hoist/startSpanOptions';\nimport type { Transport, TransportMakeRequestResponse } from './types-hoist/transport';\nimport { createClientReportEnvelope } from './utils/clientreport';\nimport { debug } from './utils/debug-logger';\nimport { dsnToString, makeDsn } from './utils/dsn';\nimport { addItemToEnvelope, createAttachmentEnvelopeItem } from './utils/envelope';\nimport { getPossibleEventMessages } from './utils/eventUtils';\nimport { isParameterizedString, isPlainObject, isPrimitive, isThenable } from './utils/is';\nimport { merge } from './utils/merge';\nimport { checkOrSetAlreadyCaught, uuid4 } from './utils/misc';\nimport { parseSampleRate } from './utils/parseSampleRate';\nimport { prepareEvent } from './utils/prepareEvent';\nimport { makePromiseBuffer, type PromiseBuffer, SENTRY_BUFFER_FULL_ERROR } from './utils/promisebuffer';\nimport { reparentChildSpans, shouldIgnoreSpan } from './utils/should-ignore-span';\nimport { showSpanDropWarning } from './utils/spanUtils';\nimport { rejectedSyncPromise } from './utils/syncpromise';\nimport { convertSpanJsonToTransactionEvent, convertTransactionEventToSpanJson } from './utils/transactionEvent';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\nconst MISSING_RELEASE_FOR_SESSION_ERROR = 'Discarded session because of missing or non-string release';\n\nconst INTERNAL_ERROR_SYMBOL = Symbol.for('SentryInternalError');\nconst DO_NOT_SEND_EVENT_SYMBOL = Symbol.for('SentryDoNotSendEventError');\n\n// Default interval for flushing logs and metrics (5 seconds)\nconst DEFAULT_FLUSH_INTERVAL = 5000;\n\ninterface InternalError {\n message: string;\n [INTERNAL_ERROR_SYMBOL]: true;\n}\n\ninterface DoNotSendEventError {\n message: string;\n [DO_NOT_SEND_EVENT_SYMBOL]: true;\n}\n\nfunction _makeInternalError(message: string): InternalError {\n return {\n message,\n [INTERNAL_ERROR_SYMBOL]: true,\n };\n}\n\nfunction _makeDoNotSendEventError(message: string): DoNotSendEventError {\n return {\n message,\n [DO_NOT_SEND_EVENT_SYMBOL]: true,\n };\n}\n\nfunction _isInternalError(error: unknown): error is InternalError {\n return !!error && typeof error === 'object' && INTERNAL_ERROR_SYMBOL in error;\n}\n\nfunction _isDoNotSendEventError(error: unknown): error is DoNotSendEventError {\n return !!error && typeof error === 'object' && DO_NOT_SEND_EVENT_SYMBOL in error;\n}\n\n/**\n * Sets up weight-based flushing for logs or metrics.\n * This helper function encapsulates the common pattern of:\n * 1. Tracking accumulated weight of items\n * 2. Flushing when weight exceeds threshold (800KB)\n * 3. Flushing after timeout period from the first item\n *\n * Uses closure variables to track weight and timeout state.\n */\nfunction setupWeightBasedFlushing<\n T,\n AfterCaptureHook extends 'afterCaptureLog' | 'afterCaptureMetric',\n FlushHook extends 'flushLogs' | 'flushMetrics',\n>(\n client: Client,\n afterCaptureHook: AfterCaptureHook,\n flushHook: FlushHook,\n estimateSizeFn: (item: T) => number,\n flushFn: (client: Client) => void,\n): void {\n // Track weight and timeout in closure variables\n let weight = 0;\n let flushTimeout: ReturnType | undefined;\n let isTimerActive = false;\n\n // @ts-expect-error - TypeScript can't narrow generic hook types to match specific overloads, but we know this is type-safe\n client.on(flushHook, () => {\n weight = 0;\n clearTimeout(flushTimeout);\n isTimerActive = false;\n });\n\n // @ts-expect-error - TypeScript can't narrow generic hook types to match specific overloads, but we know this is type-safe\n client.on(afterCaptureHook, (item: T) => {\n weight += estimateSizeFn(item);\n\n // We flush the buffer if it exceeds 0.8 MB\n // The weight is a rough estimate, so we flush way before the payload gets too big.\n if (weight >= 800_000) {\n flushFn(client);\n } else if (!isTimerActive) {\n // Only start timer if one isn't already running.\n // This prevents flushing being delayed by items that arrive close to the timeout limit\n // and thus resetting the flushing timeout and delaying items being flushed.\n isTimerActive = true;\n flushTimeout = setTimeout(() => {\n flushFn(client);\n // Note: isTimerActive is reset by the flushHook handler above, not here,\n // to avoid race conditions when new items arrive during the flush.\n }, DEFAULT_FLUSH_INTERVAL);\n }\n });\n\n client.on('flush', () => {\n flushFn(client);\n });\n}\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 Client._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 Client {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class Client {\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 /** 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 private _promiseBuffer: PromiseBuffer;\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._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n this._eventProcessors = [];\n this._promiseBuffer = makePromiseBuffer(options.transportOptions?.bufferSize ?? DEFAULT_TRANSPORT_BUFFER_SIZE);\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n DEBUG_BUILD && debug.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(\n this._dsn,\n options.tunnel,\n options._metadata ? options._metadata.sdk : undefined,\n );\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 // Backfill enableLogs option from _experiments.enableLogs\n // TODO(v11): Remove or change default value\n // eslint-disable-next-line deprecation/deprecation\n this._options.enableLogs = this._options.enableLogs ?? this._options._experiments?.enableLogs;\n\n // Setup log flushing with weight and timeout tracking\n if (this._options.enableLogs) {\n setupWeightBasedFlushing(this, 'afterCaptureLog', 'flushLogs', estimateLogSizeInBytes, _INTERNAL_flushLogsBuffer);\n }\n\n // todo(v11): Remove the experimental flag\n // eslint-disable-next-line deprecation/deprecation\n const enableMetrics = this._options.enableMetrics ?? this._options._experiments?.enableMetrics ?? true;\n\n // Setup metric flushing with weight and timeout tracking\n if (enableMetrics) {\n setupWeightBasedFlushing(\n this,\n 'afterCaptureMetric',\n 'flushMetrics',\n estimateMetricSizeInBytes,\n _INTERNAL_flushMetricsBuffer,\n );\n }\n }\n\n /**\n * Captures an exception event and sends it to Sentry.\n *\n * Unlike `captureException` exported from every SDK, this method requires that you pass it the current scope.\n */\n public captureException(exception: unknown, hint?: EventHint, scope?: Scope): string {\n const eventId = uuid4();\n\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n DEBUG_BUILD && debug.log(ALREADY_SEEN_ERROR);\n return eventId;\n }\n\n const hintWithEventId = {\n event_id: eventId,\n ...hint,\n };\n\n this._process(\n () =>\n this.eventFromException(exception, hintWithEventId)\n .then(event => this._captureEvent(event, hintWithEventId, scope))\n .then(res => res),\n 'error',\n );\n\n return hintWithEventId.event_id;\n }\n\n /**\n * Captures a message event and sends it to Sentry.\n *\n * Unlike `captureMessage` exported from every SDK, this method requires that you pass it the current scope.\n */\n public captureMessage(\n message: ParameterizedString,\n level?: SeverityLevel,\n hint?: EventHint,\n currentScope?: Scope,\n ): string {\n const hintWithEventId = {\n event_id: uuid4(),\n ...hint,\n };\n\n const eventMessage = isParameterizedString(message) ? message : String(message);\n const isMessage = isPrimitive(message);\n const promisedEvent = isMessage\n ? this.eventFromMessage(eventMessage, level, hintWithEventId)\n : this.eventFromException(message, hintWithEventId);\n\n this._process(\n () => promisedEvent.then(event => this._captureEvent(event, hintWithEventId, currentScope)),\n isMessage ? 'unknown' : 'error',\n );\n\n return hintWithEventId.event_id;\n }\n\n /**\n * Captures a manually created event and sends it to Sentry.\n *\n * Unlike `captureEvent` exported from every SDK, this method requires that you pass it the current scope.\n */\n public captureEvent(event: Event, hint?: EventHint, currentScope?: Scope): string {\n const eventId = uuid4();\n\n // ensure we haven't captured this very object before\n if (hint?.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n DEBUG_BUILD && debug.log(ALREADY_SEEN_ERROR);\n return eventId;\n }\n\n const hintWithEventId = {\n event_id: eventId,\n ...hint,\n };\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanScope: Scope | undefined = sdkProcessingMetadata.capturedSpanScope;\n const capturedSpanIsolationScope: Scope | undefined = sdkProcessingMetadata.capturedSpanIsolationScope;\n const dataCategory = getDataCategoryByType(event.type);\n\n this._process(\n () => this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope, capturedSpanIsolationScope),\n dataCategory,\n );\n\n return hintWithEventId.event_id;\n }\n\n /**\n * Captures a session.\n */\n public captureSession(session: Session): void {\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 * Create a cron monitor check in and send it to Sentry. This method is not available on all clients.\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 * @param scope An optional scope containing event metadata.\n * @returns A string representing the id of the check in.\n */\n public captureCheckIn?(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string;\n\n /**\n * Get the current Dsn.\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * Get the current options.\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * Get the SDK metadata.\n * @see SdkMetadata\n */\n public getSdkMetadata(): SdkMetadata | undefined {\n return this._options._metadata;\n }\n\n /**\n * Returns the transport that is used by the client.\n * Please note that the transport gets lazy initialized so it will only be there once the first event has been sent.\n */\n public getTransport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * Wait for all events to be sent or the timeout to expire, whichever comes first.\n *\n * @param timeout Maximum time in ms the client should wait for events to be flushed. Omitting this parameter will\n * cause the client to wait until all events are sent before resolving the promise.\n * @returns A promise that will resolve with `true` if all events are sent before the timeout, or `false` if there are\n * still events in the queue when the timeout is reached.\n */\n // @ts-expect-error - PromiseLike is a subset of Promise\n public async flush(timeout?: number): PromiseLike {\n const transport = this._transport;\n if (!transport) {\n return true;\n }\n\n this.emit('flush');\n\n const clientFinished = await this._isClientDoneProcessing(timeout);\n const transportFlushed = await transport.flush(timeout);\n\n return clientFinished && transportFlushed;\n }\n\n /**\n * Flush the event queue and set the client to `enabled = false`. See {@link Client.flush}.\n *\n * @param {number} timeout Maximum time in ms the client should wait before shutting down. Omitting this parameter will cause\n * the client to wait until all events are sent before disabling itself.\n * @returns {Promise} A promise which resolves to `true` if the flush completes successfully before the timeout, or `false` if\n * it doesn't.\n */\n // @ts-expect-error - PromiseLike is a subset of Promise\n public async close(timeout?: number): PromiseLike {\n const result = await this.flush(timeout);\n this.getOptions().enabled = false;\n this.emit('close');\n return result;\n }\n\n /**\n * Get all installed event processors.\n */\n public getEventProcessors(): EventProcessor[] {\n return this._eventProcessors;\n }\n\n /**\n * Adds an event processor that applies to any event processed by this client.\n */\n public addEventProcessor(eventProcessor: EventProcessor): void {\n this._eventProcessors.push(eventProcessor);\n }\n\n /**\n * Initialize this client.\n * Call this after the client was set on a scope.\n */\n public init(): void {\n if (\n this._isEnabled() ||\n // Force integrations to be setup even if no DSN was set when we have\n // Spotlight enabled. This is particularly important for browser as we\n // don't support the `spotlight` option there and rely on the users\n // adding the `spotlightBrowserIntegration()` to their integrations which\n // wouldn't get initialized with the check below when there's no DSN set.\n this._options.integrations.some(({ name }) => name.startsWith('Spotlight'))\n ) {\n this._setupIntegrations();\n }\n }\n\n /**\n * Gets an installed integration by its name.\n *\n * @returns {Integration|undefined} 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 * Add an integration to the client.\n * This can be used to e.g. lazy load integrations.\n * In most cases, this should not be necessary,\n * and you're better off just passing the integrations via `integrations: []` at initialization time.\n * However, if you find the need to conditionally load & add an integration, you can use `addIntegration` to do so.\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 * Send a fully prepared event to Sentry.\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(env, createAttachmentEnvelopeItem(attachment));\n }\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(env).then(sendResponse => this.emit('afterSendEvent', event, sendResponse));\n }\n\n /**\n * Send a session or session aggregrates to Sentry.\n */\n public sendSession(session: Session | SessionAggregates): void {\n // Backfill release and environment on session\n const { release: clientReleaseOption, environment: clientEnvironmentOption = DEFAULT_ENVIRONMENT } = this._options;\n if ('aggregates' in session) {\n const sessionAttrs = session.attrs || {};\n if (!sessionAttrs.release && !clientReleaseOption) {\n DEBUG_BUILD && debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR);\n return;\n }\n sessionAttrs.release = sessionAttrs.release || clientReleaseOption;\n sessionAttrs.environment = sessionAttrs.environment || clientEnvironmentOption;\n session.attrs = sessionAttrs;\n } else {\n if (!session.release && !clientReleaseOption) {\n DEBUG_BUILD && debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR);\n return;\n }\n session.release = session.release || clientReleaseOption;\n session.environment = session.environment || clientEnvironmentOption;\n }\n\n this.emit('beforeSendSession', session);\n\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 * Record on the client that an event got dropped (ie, an event that will not be sent to Sentry).\n */\n public recordDroppedEvent(reason: EventDropReason, category: DataCategory, count: number = 1): void {\n if (this._options.sendClientReports) {\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 && debug.log(`Recording outcome: \"${key}\"${count > 1 ? ` (${count} times)` : ''}`);\n this._outcomes[key] = (this._outcomes[key] || 0) + count;\n }\n }\n\n /* eslint-disable @typescript-eslint/unified-signatures */\n /**\n * Register a callback for whenever a span is started.\n * Receives the span as argument.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'spanStart', callback: (span: Span) => void): () => void;\n\n /**\n * Register a callback before span sampling runs. Receives a `samplingDecision` object argument with a `decision`\n * property that can be used to make a sampling decision that will be enforced, before any span sampling runs.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(\n hook: 'beforeSampling',\n callback: (\n samplingData: {\n spanAttributes: SpanAttributes;\n spanName: string;\n parentSampled?: boolean;\n parentSampleRate?: number;\n parentContext?: SpanContextData;\n },\n samplingDecision: { decision: boolean },\n ) => void,\n ): void;\n\n /**\n * Register a callback for after a span is ended.\n * NOTE: The span cannot be mutated anymore in this callback.\n * Receives the span as argument.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'spanEnd', callback: (span: Span) => void): () => void;\n\n /**\n * Register a callback for when an idle span is allowed to auto-finish.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'idleSpanEnableAutoFinish', callback: (span: Span) => void): () => void;\n\n /**\n * Register a callback for transaction start and finish.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): () => void;\n\n /**\n * Register a callback that runs when stack frame metadata should be applied to an event.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'applyFrameMetadata', callback: (event: Event) => void): () => void;\n\n /**\n * Register a callback for before sending an event.\n * This is called right before an event is sent and should not be used to mutate the event.\n * Receives an Event & EventHint as arguments.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'beforeSendEvent', callback: (event: Event, hint?: EventHint | undefined) => void): () => void;\n\n /**\n * Register a callback for before sending a session or session aggregrates..\n * Receives the session/aggregate as second argument.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'beforeSendSession', callback: (session: Session | SessionAggregates) => void): () => void;\n\n /**\n * Register a callback for preprocessing an event,\n * before it is passed to (global) event processors.\n * Receives an Event & EventHint as arguments.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'preprocessEvent', callback: (event: Event, hint?: EventHint | undefined) => void): () => void;\n\n /**\n * Register a callback for postprocessing an event,\n * after it was passed to (global) event processors, before it is being sent.\n * Receives an Event & EventHint as arguments.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'postprocessEvent', callback: (event: Event, hint?: EventHint | undefined) => void): () => void;\n\n /**\n * Register a callback for when an event has been sent.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(\n hook: 'afterSendEvent',\n callback: (event: Event, sendResponse: TransportMakeRequestResponse) => void,\n ): () => void;\n\n /**\n * Register a callback before a breadcrumb is added.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): () => void;\n\n /**\n * Register a callback when a DSC (Dynamic Sampling Context) is created.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): () => void;\n\n /**\n * Register a callback when a Feedback event has been prepared.\n * This should be used to mutate the event. The options argument can hint\n * about what kind of mutation it expects.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(\n hook: 'beforeSendFeedback',\n callback: (feedback: FeedbackEvent, options?: { includeReplay?: boolean }) => void,\n ): () => void;\n\n /**\n * Register a callback when the feedback widget is opened in a user's browser\n */\n public on(hook: 'openFeedbackWidget', callback: () => void): () => void;\n\n /**\n * A hook for the browser tracing integrations to trigger a span start for a page load.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(\n hook: 'startPageLoadSpan',\n callback: (\n options: StartSpanOptions,\n traceOptions?: { sentryTrace?: string | undefined; baggage?: string | undefined },\n ) => void,\n ): () => void;\n\n /**\n * A hook for the browser tracing integrations to trigger the end of a page load span.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'endPageloadSpan', callback: () => void): () => void;\n\n /**\n * A hook for the browser tracing integrations to trigger after the pageload span was started.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'afterStartPageLoadSpan', callback: (span: Span) => void): () => void;\n\n /**\n * A hook for triggering right before a navigation span is started.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(\n hook: 'beforeStartNavigationSpan',\n callback: (options: StartSpanOptions, navigationOptions?: { isRedirect?: boolean }) => void,\n ): () => void;\n\n /**\n * A hook for browser tracing integrations to trigger a span for a navigation.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(\n hook: 'startNavigationSpan',\n callback: (options: StartSpanOptions, navigationOptions?: { isRedirect?: boolean }) => void,\n ): () => void;\n\n /**\n * A hook for GraphQL client integration to enhance a span with request data.\n * @returns A function that, when executed, removes the registered callback.\n */\n public on(\n hook: 'beforeOutgoingRequestSpan',\n callback: (span: Span, hint: XhrBreadcrumbHint | FetchBreadcrumbHint) => void,\n ): () => void;\n\n /**\n * A hook for GraphQL client integration to enhance a breadcrumb with request data.\n * @returns A function that, when executed, removes the registered callback.\n */\n public on(\n hook: 'beforeOutgoingRequestBreadcrumb',\n callback: (breadcrumb: Breadcrumb, hint: XhrBreadcrumbHint | FetchBreadcrumbHint) => void,\n ): () => void;\n\n /**\n * A hook that is called when the client is flushing\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'flush', callback: () => void): () => void;\n\n /**\n * A hook that is called when the client is closing\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'close', callback: () => void): () => void;\n\n /**\n * A hook that is called before a log is captured. This hooks runs before `beforeSendLog` is fired.\n *\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'beforeCaptureLog', callback: (log: Log) => void): () => void;\n\n /**\n * A hook that is called after a log is captured\n *\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'afterCaptureLog', callback: (log: Log) => void): () => void;\n\n /**\n * A hook that is called when the client is flushing logs\n *\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'flushLogs', callback: () => void): () => void;\n\n /**\n * A hook that is called after capturing a metric. This hooks runs after `beforeSendMetric` is fired.\n *\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'afterCaptureMetric', callback: (metric: Metric) => void): () => void;\n\n /**\n * A hook that is called when the client is flushing metrics\n *\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'flushMetrics', callback: () => void): () => void;\n\n /**\n * A hook that is called when a metric is processed before it is captured and before the `beforeSendMetric` callback is fired.\n *\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'processMetric', callback: (metric: Metric) => void): () => void;\n\n /**\n * A hook that is called when a http server request is started.\n * This hook is called after request isolation, but before the request is processed.\n *\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(\n hook: 'httpServerRequest',\n callback: (request: unknown, response: unknown, normalizedRequest: RequestEventData) => void,\n ): () => void;\n\n /**\n * A hook that is called when the UI Profiler should start profiling.\n *\n * This hook is called when running `Sentry.uiProfiler.startProfiler()`.\n *\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'startUIProfiler', callback: () => void): () => void;\n\n /**\n * A hook that is called when the UI Profiler should stop profiling.\n *\n * This hook is called when running `Sentry.uiProfiler.stopProfiler()`.\n *\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n public on(hook: 'stopUIProfiler', callback: () => void): () => void;\n\n /**\n * Register a hook on this client.\n */\n public on(hook: string, callback: unknown): () => void {\n const hookCallbacks = (this._hooks[hook] = this._hooks[hook] || new Set());\n\n // Wrap the callback in a function so that registering the same callback instance multiple\n // times results in the callback being called multiple times.\n // @ts-expect-error - The `callback` type is correct and must be a function due to the\n // individual, specific overloads of this function.\n // eslint-disable-next-line @typescript-eslint/ban-types\n const uniqueCallback: Function = (...args: unknown[]) => callback(...args);\n\n hookCallbacks.add(uniqueCallback);\n\n // This function returns a callback execution handler that, when invoked,\n // deregisters a callback. This is crucial for managing instances where callbacks\n // need to be unregistered to prevent self-referencing in callback closures,\n // ensuring proper garbage collection.\n return () => {\n hookCallbacks.delete(uniqueCallback);\n };\n }\n\n /** Fire a hook whenever a span starts. */\n public emit(hook: 'spanStart', span: Span): void;\n\n /** A hook that is called every time before a span is sampled. */\n public emit(\n hook: 'beforeSampling',\n samplingData: {\n spanAttributes: SpanAttributes;\n spanName: string;\n parentSampled?: boolean;\n parentSampleRate?: number;\n parentContext?: SpanContextData;\n },\n samplingDecision: { decision: boolean },\n ): void;\n\n /** Fire a hook whenever a span ends. */\n public emit(hook: 'spanEnd', span: Span): void;\n\n /**\n * Fire a hook indicating that an idle span is allowed to auto finish.\n */\n public emit(hook: 'idleSpanEnableAutoFinish', span: Span): void;\n\n /**\n * Fire a hook event for envelope creation and sending. Expects to be given an envelope as the\n * second argument.\n */\n public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n /**\n * Fire a hook indicating that stack frame metadata should be applied to the event passed to the hook.\n */\n public emit(hook: 'applyFrameMetadata', event: Event): void;\n\n /**\n * Fire a hook event before sending an event.\n * This is called right before an event is sent and should not be used to mutate the event.\n * Expects to be given an Event & EventHint as the second/third argument.\n */\n public emit(hook: 'beforeSendEvent', event: Event, hint?: EventHint): void;\n\n /**\n * Fire a hook event before sending a session/aggregates.\n * Expects to be given the prepared session/aggregates as second argument.\n */\n public emit(hook: 'beforeSendSession', session: Session | SessionAggregates): void;\n\n /**\n * Fire a hook event to process events before they are passed to (global) event processors.\n * Expects to be given an Event & EventHint as the second/third argument.\n */\n public emit(hook: 'preprocessEvent', event: Event, hint?: EventHint): void;\n\n /**\n * Fire a hook event to process a user on an event before it is sent to Sentry, after all other processors have run.\n * Expects to be given an Event & EventHint as the second/third argument.\n */\n public emit(hook: 'postprocessEvent', event: Event, hint?: EventHint): void;\n\n /**\n * Fire a hook event after sending an event. Expects to be given an Event as the\n * second argument.\n */\n public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse): void;\n\n /**\n * Fire a hook for when a breadcrumb is added. Expects the breadcrumb as second argument.\n */\n public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n /**\n * Fire a hook for when a DSC (Dynamic Sampling Context) is created. Expects the DSC as second argument.\n */\n public emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;\n\n /**\n * Fire a hook event for after preparing a feedback event. Events to be given\n * a feedback event as the second argument, and an optional options object as\n * third argument.\n */\n public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay?: boolean }): void;\n\n /**\n * Fire a hook event for when the feedback widget is opened in a user's browser\n */\n public emit(hook: 'openFeedbackWidget'): void;\n\n /**\n * Emit a hook event for browser tracing integrations to trigger a span start for a page load.\n */\n public emit(\n hook: 'startPageLoadSpan',\n options: StartSpanOptions,\n traceOptions?: { sentryTrace?: string | undefined; baggage?: string | undefined },\n ): void;\n\n /**\n * Emit a hook event for browser tracing integrations to trigger the end of a page load span.\n */\n public emit(hook: 'endPageloadSpan'): void;\n\n /**\n * Emit a hook event for browser tracing integrations to trigger aafter the pageload span was started.\n */\n public emit(hook: 'afterStartPageLoadSpan', span: Span): void;\n\n /**\n * Emit a hook event for triggering right before a navigation span is started.\n */\n public emit(\n hook: 'beforeStartNavigationSpan',\n options: StartSpanOptions,\n navigationOptions?: { isRedirect?: boolean },\n ): void;\n\n /**\n * Emit a hook event for browser tracing integrations to trigger a span for a navigation.\n */\n public emit(\n hook: 'startNavigationSpan',\n options: StartSpanOptions,\n navigationOptions?: { isRedirect?: boolean },\n ): void;\n\n /**\n * Emit a hook event for GraphQL client integration to enhance a span with request data.\n */\n public emit(hook: 'beforeOutgoingRequestSpan', span: Span, hint: XhrBreadcrumbHint | FetchBreadcrumbHint): void;\n\n /**\n * Emit a hook event for GraphQL client integration to enhance a breadcrumb with request data.\n */\n public emit(\n hook: 'beforeOutgoingRequestBreadcrumb',\n breadcrumb: Breadcrumb,\n hint: XhrBreadcrumbHint | FetchBreadcrumbHint,\n ): void;\n\n /**\n * Emit a hook event for client flush\n */\n public emit(hook: 'flush'): void;\n\n /**\n * Emit a hook event for client close\n */\n public emit(hook: 'close'): void;\n\n /**\n * Emit a hook event for client before capturing a log. This hooks runs before `beforeSendLog` is fired.\n */\n public emit(hook: 'beforeCaptureLog', log: Log): void;\n\n /**\n * Emit a hook event for client after capturing a log.\n */\n public emit(hook: 'afterCaptureLog', log: Log): void;\n\n /**\n * Emit a hook event for client flush logs\n */\n public emit(hook: 'flushLogs'): void;\n\n /**\n * Emit a hook event for client after capturing a metric.\n */\n public emit(hook: 'afterCaptureMetric', metric: Metric): void;\n\n /**\n * Emit a hook event for client flush metrics\n */\n public emit(hook: 'flushMetrics'): void;\n\n /**\n *\n * Emit a hook event for client to process a metric before it is captured.\n * This hook is called before the `beforeSendMetric` callback is fired.\n */\n public emit(hook: 'processMetric', metric: Metric): void;\n\n /**\n * Emit a hook event for client when a http server request is started.\n * This hook is called after request isolation, but before the request is processed.\n */\n public emit(\n hook: 'httpServerRequest',\n request: unknown,\n response: unknown,\n normalizedRequest: RequestEventData,\n ): void;\n\n /**\n * Emit a hook event for starting the UI Profiler.\n */\n public emit(hook: 'startUIProfiler'): void;\n\n /**\n * Emit a hook event for stopping the UI Profiler.\n */\n public emit(hook: 'stopUIProfiler'): void;\n\n /**\n * Emit a hook that was previously registered via `on()`.\n */\n public emit(hook: string, ...rest: unknown[]): void {\n const callbacks = this._hooks[hook];\n if (callbacks) {\n callbacks.forEach(callback => callback(...rest));\n }\n }\n\n /**\n * Send an envelope to Sentry.\n */\n // @ts-expect-error - PromiseLike is a subset of Promise\n public async sendEnvelope(envelope: Envelope): PromiseLike {\n this.emit('beforeEnvelope', envelope);\n\n if (this._isEnabled() && this._transport) {\n try {\n return await this._transport.send(envelope);\n } catch (reason) {\n DEBUG_BUILD && debug.error('Error while sending envelope:', reason);\n return {};\n }\n }\n\n DEBUG_BUILD && debug.error('Transport disabled');\n return {};\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\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n // initially, set `crashed` based on the event level and update from exceptions if there are any later on\n let crashed = event.level === 'fatal';\n let errored = false;\n const exceptions = event.exception?.values;\n\n if (exceptions) {\n errored = true;\n // reset crashed to false if there are exceptions, to ensure `mechanism.handled` is respected.\n crashed = false;\n\n for (const ex of exceptions) {\n if (ex.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 async _isClientDoneProcessing(timeout?: number): Promise {\n let ticked = 0;\n\n // if no timeout is provided, we wait \"forever\" until everything is processed\n while (!timeout || ticked < timeout) {\n await new Promise(resolve => setTimeout(resolve, 1));\n\n if (!this._numProcessing) {\n return true;\n }\n ticked++;\n }\n\n return false;\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 currentScope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n currentScope: Scope,\n isolationScope: Scope,\n ): PromiseLike {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations?.length) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n if (!event.type) {\n isolationScope.setLastEventId(event.event_id || hint.event_id);\n }\n\n return prepareEvent(options, event, hint, currentScope, this, isolationScope).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n this.emit('postprocessEvent', evt, hint);\n\n evt.contexts = {\n trace: getTraceContextFromScope(currentScope),\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = getDynamicSamplingContextFromScope(this, currentScope);\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(\n event: Event,\n hint: EventHint = {},\n currentScope = getCurrentScope(),\n isolationScope = getIsolationScope(),\n ): PromiseLike {\n if (DEBUG_BUILD && isErrorEvent(event)) {\n debug.log(`Captured error event \\`${getPossibleEventMessages(event)[0] || ''}\\``);\n }\n\n return this._processEvent(event, hint, currentScope, isolationScope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (DEBUG_BUILD) {\n if (_isDoNotSendEventError(reason)) {\n debug.log(reason.message);\n } else if (_isInternalError(reason)) {\n debug.warn(reason.message);\n } else {\n debug.warn(reason);\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 currentScope 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(\n event: Event,\n hint: EventHint,\n currentScope: Scope,\n isolationScope: Scope,\n ): 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 const parsedSampleRate = typeof sampleRate === 'undefined' ? undefined : parseSampleRate(sampleRate);\n if (isError && typeof parsedSampleRate === 'number' && Math.random() > parsedSampleRate) {\n this.recordDroppedEvent('sample_rate', 'error');\n return rejectedSyncPromise(\n _makeDoNotSendEventError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n ),\n );\n }\n\n const dataCategory = getDataCategoryByType(event.type);\n\n return this._prepareEvent(event, hint, currentScope, isolationScope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory);\n throw _makeDoNotSendEventError('An event processor returned `null`, will not send event.');\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(this, options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory);\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 _makeDoNotSendEventError(`${beforeSendLabel} returned \\`null\\`, will not send event.`);\n }\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (isError && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n if (isTransaction) {\n const spanCountBefore = processedEvent.sdkProcessingMetadata?.spanCountBeforeProcessing || 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 (_isDoNotSendEventError(reason) || _isInternalError(reason)) {\n throw reason;\n }\n\n this.captureException(reason, {\n mechanism: {\n handled: false,\n type: 'internal',\n },\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw _makeInternalError(\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(taskProducer: () => PromiseLike, dataCategory: DataCategory): void {\n this._numProcessing++;\n\n void this._promiseBuffer.add(taskProducer).then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n\n if (reason === SENTRY_BUFFER_FULL_ERROR) {\n this.recordDroppedEvent('queue_overflow', dataCategory);\n }\n\n return reason;\n },\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.entries(outcomes).map(([key, quantity]) => {\n const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n return {\n reason,\n category,\n quantity,\n };\n });\n }\n\n /**\n * Sends client reports as an envelope.\n */\n protected _flushOutcomes(): void {\n DEBUG_BUILD && debug.log('Flushing outcomes...');\n\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n DEBUG_BUILD && debug.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 && debug.log('No dsn provided, will not send outcomes');\n return;\n }\n\n DEBUG_BUILD && debug.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 /**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n */\n public abstract eventFromException(_exception: unknown, _hint?: EventHint): PromiseLike;\n\n /**\n * Creates an {@link Event} from primitive inputs to `captureMessage`.\n */\n public abstract eventFromMessage(\n _message: ParameterizedString,\n _level?: SeverityLevel,\n _hint?: EventHint,\n ): PromiseLike;\n}\n\nfunction getDataCategoryByType(type: EventType | 'replay_event' | undefined): DataCategory {\n return type === 'replay_event' ? 'replay' : type || 'error';\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 _makeInternalError(invalidValueError);\n }\n return event;\n },\n e => {\n throw _makeInternalError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw _makeInternalError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n client: Client,\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n): PromiseLike | Event | null {\n const { beforeSend, beforeSendTransaction, beforeSendSpan, ignoreSpans } = options;\n let processedEvent = event;\n\n if (isErrorEvent(processedEvent) && beforeSend) {\n return beforeSend(processedEvent, hint);\n }\n\n if (isTransactionEvent(processedEvent)) {\n // Avoid processing if we don't have to\n if (beforeSendSpan || ignoreSpans) {\n // 1. Process root span\n const rootSpanJson = convertTransactionEventToSpanJson(processedEvent);\n\n // 1.1 If the root span should be ignored, drop the whole transaction\n if (ignoreSpans?.length && shouldIgnoreSpan(rootSpanJson, ignoreSpans)) {\n // dropping the whole transaction!\n return null;\n }\n\n // 1.2 If a `beforeSendSpan` callback is defined, process the root span\n if (beforeSendSpan) {\n const processedRootSpanJson = beforeSendSpan(rootSpanJson);\n if (!processedRootSpanJson) {\n showSpanDropWarning();\n } else {\n // update event with processed root span values\n processedEvent = merge(event, convertSpanJsonToTransactionEvent(processedRootSpanJson));\n }\n }\n\n // 2. Process child spans\n if (processedEvent.spans) {\n const processedSpans: SpanJSON[] = [];\n\n const initialSpans = processedEvent.spans;\n\n for (const span of initialSpans) {\n // 2.a If the child span should be ignored, reparent it to the root span\n if (ignoreSpans?.length && shouldIgnoreSpan(span, ignoreSpans)) {\n reparentChildSpans(initialSpans, span);\n continue;\n }\n\n // 2.b If a `beforeSendSpan` callback is defined, process the child span\n if (beforeSendSpan) {\n const processedSpan = beforeSendSpan(span);\n if (!processedSpan) {\n showSpanDropWarning();\n processedSpans.push(span);\n } else {\n processedSpans.push(processedSpan);\n }\n } else {\n processedSpans.push(span);\n }\n }\n\n const droppedSpans = processedEvent.spans.length - processedSpans.length;\n if (droppedSpans) {\n client.recordDroppedEvent('before_send', 'span', droppedSpans);\n }\n\n processedEvent.spans = processedSpans;\n }\n }\n\n if (beforeSendTransaction) {\n if (processedEvent.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 = processedEvent.spans.length;\n processedEvent.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n spanCountBeforeProcessing: spanCountBefore,\n };\n }\n return beforeSendTransaction(processedEvent as TransactionEvent, hint);\n }\n }\n\n return processedEvent;\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 * Estimate the size of a metric in bytes.\n *\n * @param metric - The metric to estimate the size of.\n * @returns The estimated size of the metric in bytes.\n */\nfunction estimateMetricSizeInBytes(metric: Metric): number {\n let weight = 0;\n\n // Estimate byte size of 2 bytes per character. This is a rough estimate JS strings are stored as UTF-16.\n if (metric.name) {\n weight += metric.name.length * 2;\n }\n\n // Add weight for number\n weight += 8;\n\n return weight + estimateAttributesSizeInBytes(metric.attributes);\n}\n\n/**\n * Estimate the size of a log in bytes.\n *\n * @param log - The log to estimate the size of.\n * @returns The estimated size of the log in bytes.\n */\nfunction estimateLogSizeInBytes(log: Log): number {\n let weight = 0;\n\n // Estimate byte size of 2 bytes per character. This is a rough estimate JS strings are stored as UTF-16.\n if (log.message) {\n weight += log.message.length * 2;\n }\n\n return weight + estimateAttributesSizeInBytes(log.attributes);\n}\n\n/**\n * Estimate the size of attributes in bytes.\n *\n * @param attributes - The attributes object to estimate the size of.\n * @returns The estimated size of the attributes in bytes.\n */\nfunction estimateAttributesSizeInBytes(attributes: Record | undefined): number {\n if (!attributes) {\n return 0;\n }\n\n let weight = 0;\n\n Object.values(attributes).forEach(value => {\n if (Array.isArray(value)) {\n weight += value.length * estimatePrimitiveSizeInBytes(value[0]);\n } else if (isPrimitive(value)) {\n weight += estimatePrimitiveSizeInBytes(value);\n } else {\n // For objects values, we estimate the size of the object as 100 bytes\n weight += 100;\n }\n });\n\n return weight;\n}\n\nfunction estimatePrimitiveSizeInBytes(value: Primitive): number {\n if (typeof value === 'string') {\n return value.length * 2;\n } else if (typeof value === 'number') {\n return 8;\n } else if (typeof value === 'boolean') {\n return 4;\n }\n\n return 0;\n}\n", "import type { Client } from './client';\nimport { getCurrentScope } from './currentScopes';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ClientOptions } from './types-hoist/options';\nimport { consoleSandbox, debug } from './utils/debug-logger';\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): Client {\n if (options.debug === true) {\n if (DEBUG_BUILD) {\n debug.enable();\n } else {\n // use `console.warn` rather than `debug.warn` since by non-debug bundles have all `debug.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 client.init();\n return client;\n}\n\n/**\n * Make the given client the current client.\n */\nexport function setCurrentClient(client: Client): void {\n getCurrentScope().setClient(client);\n}\n", "import {\n SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n SEMANTIC_ATTRIBUTE_URL_FULL,\n} from '../semanticAttributes';\nimport type { SpanAttributes } from '../types-hoist/span';\n\ntype PartialURL = {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n search?: string;\n hash?: string;\n};\n\ninterface URLwithCanParse extends URL {\n canParse: (url: string, base?: string | URL | undefined) => boolean;\n}\n\n// A subset of the URL object that is valid for relative URLs\n// The URL object cannot handle relative URLs, so we need to handle them separately\ntype RelativeURL = {\n isRelative: true;\n pathname: URL['pathname'];\n search: URL['search'];\n hash: URL['hash'];\n};\n\ntype URLObject = RelativeURL | URL;\n\n// Curious about `thismessage:/`? See: https://www.rfc-editor.org/rfc/rfc2557.html\n// > When the methods above do not yield an absolute URI, a base URL\n// > of \"thismessage:/\" MUST be employed. This base URL has been\n// > defined for the sole purpose of resolving relative references\n// > within a multipart/related structure when no other base URI is\n// > specified.\n//\n// We need to provide a base URL to `parseStringToURLObject` because the fetch API gives us a\n// relative URL sometimes.\n//\n// This is the only case where we need to provide a base URL to `parseStringToURLObject`\n// because the relative URL is not valid on its own.\nconst DEFAULT_BASE_URL = 'thismessage:/';\n\n/**\n * Checks if the URL object is relative\n *\n * @param url - The URL object to check\n * @returns True if the URL object is relative, false otherwise\n */\nexport function isURLObjectRelative(url: URLObject): url is RelativeURL {\n return 'isRelative' in url;\n}\n\n/**\n * Parses string to a URL object\n *\n * @param url - The URL to parse\n * @returns The parsed URL object or undefined if the URL is invalid\n */\nexport function parseStringToURLObject(url: string, urlBase?: string | URL | undefined): URLObject | undefined {\n const isRelative = url.indexOf('://') <= 0 && url.indexOf('//') !== 0;\n const base = urlBase ?? (isRelative ? DEFAULT_BASE_URL : undefined);\n try {\n // Use `canParse` to short-circuit the URL constructor if it's not a valid URL\n // This is faster than trying to construct the URL and catching the error\n // Node 20+, Chrome 120+, Firefox 115+, Safari 17+\n if ('canParse' in URL && !(URL as unknown as URLwithCanParse).canParse(url, base)) {\n return undefined;\n }\n\n const fullUrlObject = new URL(url, base);\n if (isRelative) {\n // Because we used a fake base URL, we need to return a relative URL object.\n // We cannot return anything about the origin, host, etc. because it will refer to the fake base URL.\n return {\n isRelative,\n pathname: fullUrlObject.pathname,\n search: fullUrlObject.search,\n hash: fullUrlObject.hash,\n };\n }\n return fullUrlObject;\n } catch {\n // empty body\n }\n\n return undefined;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span name\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlStringFromUrlObject(url: URLObject): string {\n if (isURLObjectRelative(url)) {\n return url.pathname;\n }\n\n const newUrl = new URL(url);\n newUrl.search = '';\n newUrl.hash = '';\n if (['80', '443'].includes(newUrl.port)) {\n newUrl.port = '';\n }\n if (newUrl.password) {\n newUrl.password = '%filtered%';\n }\n if (newUrl.username) {\n newUrl.username = '%filtered%';\n }\n\n return newUrl.toString();\n}\n\ntype PartialRequest = {\n method?: string;\n};\n\nfunction getHttpSpanNameFromUrlObject(\n urlObject: URLObject | undefined,\n kind: 'server' | 'client',\n request?: PartialRequest,\n routeName?: string,\n): string {\n const method = request?.method?.toUpperCase() ?? 'GET';\n const route = routeName\n ? routeName\n : urlObject\n ? kind === 'client'\n ? getSanitizedUrlStringFromUrlObject(urlObject)\n : urlObject.pathname\n : '/';\n\n return `${method} ${route}`;\n}\n\n/**\n * Takes a parsed URL object and returns a set of attributes for the span\n * that represents the HTTP request for that url. This is used for both server\n * and client http spans.\n *\n * Follows https://opentelemetry.io/docs/specs/semconv/http/.\n *\n * @param urlObject - see {@link parseStringToURLObject}\n * @param kind - The type of HTTP operation (server or client)\n * @param spanOrigin - The origin of the span\n * @param request - The request object, see {@link PartialRequest}\n * @param routeName - The name of the route, must be low cardinality\n * @returns The span name and attributes for the HTTP operation\n */\nexport function getHttpSpanDetailsFromUrlObject(\n urlObject: URLObject | undefined,\n kind: 'server' | 'client',\n spanOrigin: string,\n request?: PartialRequest,\n routeName?: string,\n): [name: string, attributes: SpanAttributes] {\n const attributes: SpanAttributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n };\n\n if (routeName) {\n // This is based on https://opentelemetry.io/docs/specs/semconv/http/http-spans/#name\n attributes[kind === 'server' ? 'http.route' : 'url.template'] = routeName;\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';\n }\n\n if (request?.method) {\n attributes[SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD] = request.method.toUpperCase();\n }\n\n if (urlObject) {\n if (urlObject.search) {\n attributes['url.query'] = urlObject.search;\n }\n if (urlObject.hash) {\n attributes['url.fragment'] = urlObject.hash;\n }\n if (urlObject.pathname) {\n attributes['url.path'] = urlObject.pathname;\n if (urlObject.pathname === '/') {\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';\n }\n }\n\n if (!isURLObjectRelative(urlObject)) {\n attributes[SEMANTIC_ATTRIBUTE_URL_FULL] = urlObject.href;\n if (urlObject.port) {\n attributes['url.port'] = urlObject.port;\n }\n if (urlObject.protocol) {\n attributes['url.scheme'] = urlObject.protocol;\n }\n if (urlObject.hostname) {\n attributes[kind === 'server' ? 'server.address' : 'url.domain'] = urlObject.hostname;\n }\n }\n }\n\n return [getHttpSpanNameFromUrlObject(urlObject, kind, request, routeName), attributes];\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 return (urlPath.split(/[?#]/, 1) as [string, ...string[]])[0];\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span name\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 // 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 return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n", "import type { Client } from '../client';\nimport type { DsnComponents } from '../types-hoist/dsn';\nimport { isURLObjectRelative, parseStringToURLObject } from './url';\n\n/**\n * Checks whether given url points to Sentry server\n *\n * @param url url to verify\n */\nexport function isSentryRequestUrl(url: string, client: Client | undefined): boolean {\n const dsn = client?.getDsn();\n const tunnel = client?.getOptions().tunnel;\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 // Requests to Sentry's ingest endpoint must have a `sentry_key` in the query string\n // This is equivalent to the public_key which is required in the DSN\n // see https://develop.sentry.dev/sdk/overview/#parsing-the-dsn\n // Therefore, a request to the same host and with a `sentry_key` in the query string\n // can be considered a request to the ingest endpoint.\n const urlParts = parseStringToURLObject(url);\n if (!urlParts || isURLObjectRelative(urlParts)) {\n return false;\n }\n\n return dsn ? urlParts.host.includes(dsn.host) && /(^|&|\\?)sentry_key=/.test(urlParts.search) : false;\n}\n\nfunction removeTrailingSlash(str: string): string {\n return str[str.length - 1] === '/' ? str.slice(0, -1) : str;\n}\n", "import type { Session, SessionAggregates } from '../types-hoist/session';\nimport type { User } from '../types-hoist/user';\n\n// By default, we want to infer the IP address, unless this is explicitly set to `null`\n// We do this after all other processing is done\n// If `ip_address` is explicitly set to `null` or a value, we leave it as is\n\n/**\n * @internal\n * @deprecated -- set ip inferral via via SDK metadata options on client instead.\n */\nexport function addAutoIpAddressToUser(objWithMaybeUser: { user?: User | null }): void {\n if (objWithMaybeUser.user?.ip_address === undefined) {\n objWithMaybeUser.user = {\n ...objWithMaybeUser.user,\n ip_address: '{{auto}}',\n };\n }\n}\n\n/**\n * @internal\n */\nexport function addAutoIpAddressToSession(session: Session | SessionAggregates): void {\n if ('aggregates' in session) {\n if (session.attrs?.['ip_address'] === undefined) {\n session.attrs = {\n ...session.attrs,\n ip_address: '{{auto}}',\n };\n }\n } else {\n if (session.ipAddress === undefined) {\n session.ipAddress = '{{auto}}';\n }\n }\n}\n", "import type { CoreOptions } from '../types-hoist/options';\nimport { SDK_VERSION } from '../utils/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: CoreOptions, 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 { getAsyncContextStrategy } from '../asyncContext';\nimport { getMainCarrier } from '../carrier';\nimport type { Client } from '../client';\nimport { getClient, getCurrentScope } from '../currentScopes';\nimport { isEnabled } from '../exports';\nimport type { Scope } from '../scope';\nimport { getDynamicSamplingContextFromScope, getDynamicSamplingContextFromSpan } from '../tracing';\nimport type { Span } from '../types-hoist/span';\nimport type { SerializedTraceData } from '../types-hoist/tracing';\nimport { dynamicSamplingContextToSentryBaggageHeader } from './baggage';\nimport { debug } from './debug-logger';\nimport { getActiveSpan, spanToTraceHeader, spanToTraceparentHeader } from './spanUtils';\nimport { generateSentryTraceHeader, generateTraceparentHeader, TRACEPARENT_REGEXP } from './tracing';\n\n/**\n * Extracts trace propagation data from the current span or from the client's scope (via transaction or propagation\n * context) and serializes it to `sentry-trace` and `baggage` values. These values can be used to propagate\n * a trace via our tracing Http headers or Html `` tags.\n *\n * This function also applies some validation to the generated sentry-trace and baggage values to ensure that\n * only valid strings are returned.\n *\n * If (@param options.propagateTraceparent) is `true`, the function will also generate a `traceparent` value,\n * following the W3C traceparent header format.\n *\n * @returns an object with the tracing data values. The object keys are the name of the tracing key to be used as header\n * or meta tag name.\n */\nexport function getTraceData(\n options: { span?: Span; scope?: Scope; client?: Client; propagateTraceparent?: boolean } = {},\n): SerializedTraceData {\n const client = options.client || getClient();\n if (!isEnabled() || !client) {\n return {};\n }\n\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n if (acs.getTraceData) {\n return acs.getTraceData(options);\n }\n\n const scope = options.scope || getCurrentScope();\n const span = options.span || getActiveSpan();\n const sentryTrace = span ? spanToTraceHeader(span) : scopeToTraceHeader(scope);\n const dsc = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope);\n const baggage = dynamicSamplingContextToSentryBaggageHeader(dsc);\n\n const isValidSentryTraceHeader = TRACEPARENT_REGEXP.test(sentryTrace);\n if (!isValidSentryTraceHeader) {\n debug.warn('Invalid sentry-trace data. Cannot generate trace data');\n return {};\n }\n\n const traceData: SerializedTraceData = {\n 'sentry-trace': sentryTrace,\n baggage,\n };\n\n if (options.propagateTraceparent) {\n const traceparent = span ? spanToTraceparentHeader(span) : scopeToTraceparentHeader(scope);\n if (traceparent) {\n traceData.traceparent = traceparent;\n }\n }\n\n return traceData;\n}\n\n/**\n * Get a sentry-trace header value for the given scope.\n */\nfunction scopeToTraceHeader(scope: Scope): string {\n const { traceId, sampled, propagationSpanId } = scope.getPropagationContext();\n return generateSentryTraceHeader(traceId, propagationSpanId, sampled);\n}\n\nfunction scopeToTraceparentHeader(scope: Scope): string {\n const { traceId, sampled, propagationSpanId } = scope.getPropagationContext();\n return generateTraceparentHeader(traceId, propagationSpanId, sampled);\n}\n", "type DebouncedCallback = {\n (): void | unknown;\n flush: () => void | unknown;\n cancel: () => void;\n};\ntype CallbackFunction = () => unknown;\ntype DebounceOptions = {\n /** The max. time in ms to wait for the callback to be invoked. */\n maxWait?: number;\n /** This can be overwritten to use a different setTimeout implementation, e.g. to avoid triggering change detection in Angular */\n setTimeoutImpl?: typeof setTimeout;\n};\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?.maxWait ? Math.max(options.maxWait, wait) : 0;\n const setTimeoutImpl = options?.setTimeoutImpl || setTimeout;\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 = setTimeoutImpl(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeoutImpl(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n}\n", "import { getClient, getIsolationScope } from './currentScopes';\nimport type { Breadcrumb, BreadcrumbHint } from './types-hoist/breadcrumb';\nimport { consoleSandbox } from './utils/debug-logger';\nimport { dateTimestampInSeconds } from './utils/time';\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\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 */\nexport function addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n const client = getClient();\n const isolationScope = getIsolationScope();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = 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))\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n}\n", "import type { Client } from '../client';\nimport { getClient } from '../currentScopes';\nimport { defineIntegration } from '../integration';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport type { WrappedFunction } from '../types-hoist/wrappedfunction';\nimport { getOriginalFunction } from '../utils/object';\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 Function.prototype.toString = function (this: WrappedFunction, ...args: unknown[]): 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", "import { DEBUG_BUILD } from '../debug-build';\nimport { defineIntegration } from '../integration';\nimport type { Event } from '../types-hoist/event';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport type { StackFrame } from '../types-hoist/stackframe';\nimport { debug } from '../utils/debug-logger';\nimport { getPossibleEventMessages } from '../utils/eventUtils';\nimport { getEventDescription } from '../utils/misc';\nimport { stringMatchesSomePattern } from '../utils/string';\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.$/, // The browser logs this when a ResizeObserver handler takes a bit longer. Usually this is not an actual issue though. It indicates slowness.\n /^Cannot redefine property: googletag$/, // This is thrown when google tag manager is used in combination with an ad blocker\n /^Can't find variable: gmo$/, // Error from Google Search App https://issuetracker.google.com/issues/396043331\n /^undefined is not an object \\(evaluating 'a\\.[A-Z]'\\)$/, // Random error that happens but not actionable or noticeable to end-users.\n 'can\\'t redefine non-configurable property \"solana\"', // Probably a browser extension or custom browser (Brave) throwing this error\n \"vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)\", // Error thrown by GTM, seemingly not affecting end-users\n \"Can't find variable: _AutofillCallbackHandler\", // Unactionable error in instagram webview https://developers.facebook.com/community/threads/320013549791141/\n /^Non-Error promise rejection captured with value: Object Not Found Matching Id:\\d+, MethodName:simulateEvent, ParamCount:\\d+$/, // unactionable error from CEFSharp, a .NET library that embeds chromium in .NET apps\n /^Java exception was raised during method invocation$/, // error from Facebook Mobile browser (https://github.com/getsentry/sentry-javascript/issues/15065)\n];\n\n/** Options for the EventFilters integration */\nexport interface EventFiltersOptions {\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n}\n\nconst INTEGRATION_NAME = 'EventFilters';\n\n/**\n * An integration that filters out events (errors and transactions) based on:\n *\n * - (Errors) A curated list of known low-value or irrelevant errors (see {@link DEFAULT_IGNORE_ERRORS})\n * - (Errors) A list of error messages or urls/filenames passed in via\n * - Top level Sentry.init options (`ignoreErrors`, `denyUrls`, `allowUrls`)\n * - The same options passed to the integration directly via @param options\n * - (Transactions/Spans) A list of root span (transaction) names passed in via\n * - Top level Sentry.init option (`ignoreTransactions`)\n * - The same option passed to the integration directly via @param options\n *\n * Events filtered by this integration will not be sent to Sentry.\n */\nexport const eventFiltersIntegration = defineIntegration((options: Partial = {}) => {\n let mergedOptions: Partial | undefined;\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n const clientOptions = client.getOptions();\n mergedOptions = _mergeOptions(options, clientOptions);\n },\n processEvent(event, _hint, client) {\n if (!mergedOptions) {\n const clientOptions = client.getOptions();\n mergedOptions = _mergeOptions(options, clientOptions);\n }\n return _shouldDropEvent(event, mergedOptions) ? null : event;\n },\n };\n});\n\n/**\n * An integration that filters out events (errors and transactions) based on:\n *\n * - (Errors) A curated list of known low-value or irrelevant errors (see {@link DEFAULT_IGNORE_ERRORS})\n * - (Errors) A list of error messages or urls/filenames passed in via\n * - Top level Sentry.init options (`ignoreErrors`, `denyUrls`, `allowUrls`)\n * - The same options passed to the integration directly via @param options\n * - (Transactions/Spans) A list of root span (transaction) names passed in via\n * - Top level Sentry.init option (`ignoreTransactions`)\n * - The same option passed to the integration directly via @param options\n *\n * Events filtered by this integration will not be sent to Sentry.\n *\n * @deprecated this integration was renamed and will be removed in a future major version.\n * Use `eventFiltersIntegration` instead.\n */\nexport const inboundFiltersIntegration = defineIntegration(((options: Partial = {}) => {\n return {\n ...eventFiltersIntegration(options),\n name: 'InboundFilters',\n };\n}) satisfies IntegrationFn);\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: [...(internalOptions.ignoreTransactions || []), ...(clientOptions.ignoreTransactions || [])],\n };\n}\n\nfunction _shouldDropEvent(event: Event, options: Partial): boolean {\n if (!event.type) {\n // Filter errors\n if (_isIgnoredError(event, options.ignoreErrors)) {\n DEBUG_BUILD &&\n debug.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isUselessError(event)) {\n DEBUG_BUILD &&\n debug.warn(\n `Event dropped due to not having an error message, error type or stacktrace.\\nEvent: ${getEventDescription(\n event,\n )}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n DEBUG_BUILD &&\n debug.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 debug.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 } else if (event.type === 'transaction') {\n // Filter transactions\n\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n DEBUG_BUILD &&\n debug.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n }\n return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array): boolean {\n if (!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 (!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 if (!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 if (!allowUrls?.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\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 // If there are linked exceptions or exception aggregates we only want to match against the top frame of the \"root\" (the main exception)\n // The root always comes last in linked exceptions\n const rootException = [...(event.exception?.values ?? [])]\n .reverse()\n .find(value => value.mechanism?.parent_id === undefined && value.stacktrace?.frames?.length);\n const frames = rootException?.stacktrace?.frames;\n return frames ? _getLastValidUrl(frames) : null;\n } catch {\n DEBUG_BUILD && debug.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n\nfunction _isUselessError(event: Event): boolean {\n // We only want to consider events for dropping that actually have recorded exception values.\n if (!event.exception?.values?.length) {\n return false;\n }\n\n return (\n // No top-level message\n !event.message &&\n // There are no exception values that have a stacktrace, a non-generic-Error type or value\n !event.exception.values.some(value => value.stacktrace || (value.type && value.type !== 'Error') || value.value)\n );\n}\n", "import type { ExtendedError } from '../types-hoist/error';\nimport type { Event, EventHint } from '../types-hoist/event';\nimport type { Exception } from '../types-hoist/exception';\nimport type { StackParser } from '../types-hoist/stacktrace';\nimport { isInstanceOf } from './is';\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 key: string,\n limit: number,\n event: Event,\n hint?: EventHint,\n): void {\n if (!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 = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException as ExtendedError,\n key,\n event.exception.values,\n originalException,\n 0,\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 exception.mechanism = {\n handled: true,\n type: 'auto.core.linked_errors',\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 exception.mechanism = {\n handled: true,\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { ConsoleLevel, HandlerDataConsole } from '../types-hoist/instrument';\nimport { CONSOLE_LEVELS, originalConsoleMethods } from '../utils/debug-logger';\nimport { fill } from '../utils/object';\nimport { GLOBAL_OBJ } from '../utils/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?.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n", "import type { SeverityLevel } from '../types-hoist/severity';\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 (\n level === 'warn' ? 'warning' : ['fatal', 'error', 'warning', 'log', 'info', 'debug'].includes(level) ? level : 'log'\n ) as SeverityLevel;\n}\n", "import { DEBUG_BUILD } from '../debug-build';\nimport { defineIntegration } from '../integration';\nimport type { Event } from '../types-hoist/event';\nimport type { Exception } from '../types-hoist/exception';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport type { StackFrame } from '../types-hoist/stackframe';\nimport { debug } from '../utils/debug-logger';\nimport { getFramesFromEvent } from '../utils/stacktrace';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() => {\n let previousEvent: Event | undefined;\n\n return {\n name: INTEGRATION_NAME,\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 && debug.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch {} // eslint-disable-line no-empty\n\n return (previousEvent = currentEvent);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Deduplication filter.\n */\nexport const dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/** only exported for tests. */\nexport function _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 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const frameA = previousFrames[i]!;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\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 {\n return false;\n }\n}\n\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception?.values?.[0];\n}\n", "import { getClient } from './currentScopes';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from './semanticAttributes';\nimport { setHttpStatus, SPAN_STATUS_ERROR, startInactiveSpan } from './tracing';\nimport { SentryNonRecordingSpan } from './tracing/sentryNonRecordingSpan';\nimport type { FetchBreadcrumbHint } from './types-hoist/breadcrumb';\nimport type { HandlerDataFetch } from './types-hoist/instrument';\nimport type { ResponseHookInfo } from './types-hoist/request';\nimport type { Span, SpanAttributes, SpanOrigin } from './types-hoist/span';\nimport { SENTRY_BAGGAGE_KEY_PREFIX } from './utils/baggage';\nimport { hasSpansEnabled } from './utils/hasSpansEnabled';\nimport { isInstanceOf, isRequest } from './utils/is';\nimport { getActiveSpan } from './utils/spanUtils';\nimport { getTraceData } from './utils/traceData';\nimport { getSanitizedUrlStringFromUrlObject, isURLObjectRelative, parseStringToURLObject } from './utils/url';\n\ntype PolymorphicRequestHeaders =\n | Record\n | Array<[string, string]>\n // the below is not precisely the Header type used in Request, but it'll pass duck-typing\n | {\n append: (key: string, value: string) => void;\n get: (key: string) => string | null | undefined;\n };\n\ninterface InstrumentFetchRequestOptions {\n spanOrigin?: SpanOrigin;\n propagateTraceparent?: boolean;\n onRequestSpanEnd?: (span: Span, responseInformation: ResponseHookInfo) => void;\n}\n\n/**\n * Create and track fetch request spans for usage in combination with `addFetchInstrumentationHandler`.\n *\n * @deprecated pass an options object instead of the spanOrigin parameter\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,\n): Span | undefined;\n/**\n * Create and track fetch request spans for usage in combination with `addFetchInstrumentationHandler`.\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 // eslint-disable-next-line @typescript-eslint/unified-signatures -- needed because the other overload is deprecated\n instrumentFetchRequestOptions: InstrumentFetchRequestOptions,\n): Span | undefined;\n\n/**\n * Create and track fetch request spans for usage in combination with `addFetchInstrumentationHandler`.\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 spanOriginOrOptions?: SpanOrigin | InstrumentFetchRequestOptions,\n): Span | undefined {\n if (!handlerData.fetchData) {\n return undefined;\n }\n\n const { method, url } = handlerData.fetchData;\n\n const shouldCreateSpanResult = hasSpansEnabled() && shouldCreateSpan(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\n _callOnRequestSpanEnd(span, handlerData, spanOriginOrOptions);\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n // Backwards-compatible with the old signature. Needed to introduce the combined optional parameter\n // to avoid API breakage for anyone calling this function with the optional spanOrigin parameter\n // TODO (v11): remove this backwards-compatible code and only accept the options parameter\n const { spanOrigin = 'auto.http.browser', propagateTraceparent = false } =\n typeof spanOriginOrOptions === 'object' ? spanOriginOrOptions : { spanOrigin: spanOriginOrOptions };\n\n const hasParent = !!getActiveSpan();\n\n const span =\n shouldCreateSpanResult && hasParent\n ? startInactiveSpan(getSpanStartOptions(url, method, spanOrigin))\n : new SentryNonRecordingSpan();\n\n handlerData.fetchData.__span = span.spanContext().spanId;\n spans[span.spanContext().spanId] = span;\n\n if (shouldAttachHeaders(handlerData.fetchData.url)) {\n const request: string | Request = handlerData.args[0];\n\n const options: { [key: string]: unknown } = handlerData.args[1] || {};\n\n const headers = _addTracingHeadersToFetchRequest(\n request,\n options,\n // If performance is disabled (TWP) or there's no active root span (pageload/navigation/interaction),\n // we do not want to use the span as base for the trace headers,\n // which means that the headers will be generated from the scope and the sampling decision is deferred\n hasSpansEnabled() && hasParent ? span : undefined,\n propagateTraceparent,\n );\n if (headers) {\n // Ensure this is actually set, if no options have been passed previously\n handlerData.args[1] = options;\n options.headers = headers;\n }\n }\n\n const client = getClient();\n\n if (client) {\n const fetchHint = {\n input: handlerData.args,\n response: handlerData.response,\n startTimestamp: handlerData.startTimestamp,\n endTimestamp: handlerData.endTimestamp,\n } satisfies FetchBreadcrumbHint;\n\n client.emit('beforeOutgoingRequestSpan', span, fetchHint);\n }\n\n return span;\n}\n\n/**\n * Calls the onRequestSpanEnd callback if it is defined.\n */\nexport function _callOnRequestSpanEnd(\n span: Span,\n handlerData: HandlerDataFetch,\n spanOriginOrOptions?: SpanOrigin | InstrumentFetchRequestOptions,\n): void {\n const onRequestSpanEnd =\n typeof spanOriginOrOptions === 'object' && spanOriginOrOptions !== null\n ? spanOriginOrOptions.onRequestSpanEnd\n : undefined;\n\n onRequestSpanEnd?.(span, {\n headers: handlerData.response?.headers,\n error: handlerData.error,\n });\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers.\n * exported only for testing purposes\n *\n * When we determine if we should add a baggage header, there are 3 cases:\n * 1. No previous baggage header -> add baggage\n * 2. Previous baggage header has no sentry baggage values -> add our baggage\n * 3. Previous baggage header has sentry baggage values -> do nothing (might have been added manually by users)\n */\n// eslint-disable-next-line complexity -- yup it's this complicated :(\nexport function _addTracingHeadersToFetchRequest(\n request: string | Request,\n fetchOptionsObj: {\n headers?:\n | {\n [key: string]: string[] | string | undefined;\n }\n | PolymorphicRequestHeaders;\n },\n span?: Span,\n propagateTraceparent?: boolean,\n): PolymorphicRequestHeaders | undefined {\n const traceHeaders = getTraceData({ span, propagateTraceparent });\n const sentryTrace = traceHeaders['sentry-trace'];\n const baggage = traceHeaders.baggage;\n const traceparent = traceHeaders.traceparent;\n\n // Nothing to do, when we return undefined here, the original headers will be used\n if (!sentryTrace) {\n return undefined;\n }\n\n const originalHeaders = fetchOptionsObj.headers || (isRequest(request) ? request.headers : undefined);\n\n if (!originalHeaders) {\n return { ...traceHeaders };\n } else if (isHeaders(originalHeaders)) {\n const newHeaders = new Headers(originalHeaders);\n\n // We don't want to override manually added sentry headers\n if (!newHeaders.get('sentry-trace')) {\n newHeaders.set('sentry-trace', sentryTrace);\n }\n\n if (propagateTraceparent && traceparent && !newHeaders.get('traceparent')) {\n newHeaders.set('traceparent', traceparent);\n }\n\n if (baggage) {\n const prevBaggageHeader = newHeaders.get('baggage');\n\n if (!prevBaggageHeader) {\n newHeaders.set('baggage', baggage);\n } else if (!baggageHeaderHasSentryBaggageValues(prevBaggageHeader)) {\n newHeaders.set('baggage', `${prevBaggageHeader},${baggage}`);\n }\n }\n\n return newHeaders;\n } else if (Array.isArray(originalHeaders)) {\n const newHeaders = [...originalHeaders];\n\n if (!originalHeaders.find(header => header[0] === 'sentry-trace')) {\n newHeaders.push(['sentry-trace', sentryTrace]);\n }\n\n if (propagateTraceparent && traceparent && !originalHeaders.find(header => header[0] === 'traceparent')) {\n newHeaders.push(['traceparent', traceparent]);\n }\n\n const prevBaggageHeaderWithSentryValues = originalHeaders.find(\n header => header[0] === 'baggage' && baggageHeaderHasSentryBaggageValues(header[1]),\n );\n\n if (baggage && !prevBaggageHeaderWithSentryValues) {\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', baggage]);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else {\n const existingSentryTraceHeader = 'sentry-trace' in originalHeaders ? originalHeaders['sentry-trace'] : undefined;\n const existingTraceparentHeader = 'traceparent' in originalHeaders ? originalHeaders.traceparent : undefined;\n const existingBaggageHeader = 'baggage' in originalHeaders ? originalHeaders.baggage : undefined;\n\n const newBaggageHeaders: string[] = existingBaggageHeader\n ? Array.isArray(existingBaggageHeader)\n ? [...existingBaggageHeader]\n : [existingBaggageHeader]\n : [];\n\n const prevBaggageHeaderWithSentryValues =\n existingBaggageHeader &&\n (Array.isArray(existingBaggageHeader)\n ? existingBaggageHeader.find(headerItem => baggageHeaderHasSentryBaggageValues(headerItem))\n : baggageHeaderHasSentryBaggageValues(existingBaggageHeader));\n\n if (baggage && !prevBaggageHeaderWithSentryValues) {\n newBaggageHeaders.push(baggage);\n }\n\n const newHeaders: {\n 'sentry-trace': string;\n baggage: string | undefined;\n traceparent?: string;\n } = {\n ...originalHeaders,\n 'sentry-trace': (existingSentryTraceHeader as string | undefined) ?? sentryTrace,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n\n if (propagateTraceparent && traceparent && !existingTraceparentHeader) {\n newHeaders.traceparent = traceparent;\n }\n\n return newHeaders;\n }\n}\n\nfunction endSpan(span: Span, handlerData: HandlerDataFetch): void {\n if (handlerData.response) {\n setHttpStatus(span, handlerData.response.status);\n\n const contentLength = 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({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n span.end();\n}\n\nfunction baggageHeaderHasSentryBaggageValues(baggageHeader: string): boolean {\n return baggageHeader.split(',').some(baggageEntry => baggageEntry.trim().startsWith(SENTRY_BAGGAGE_KEY_PREFIX));\n}\n\nfunction isHeaders(headers: unknown): headers is Headers {\n return typeof Headers !== 'undefined' && isInstanceOf(headers, Headers);\n}\n\nfunction getSpanStartOptions(\n url: string,\n method: string,\n spanOrigin: SpanOrigin,\n): Parameters[0] {\n const parsedUrl = parseStringToURLObject(url);\n return {\n name: parsedUrl ? `${method} ${getSanitizedUrlStringFromUrlObject(parsedUrl)}` : method,\n attributes: getFetchSpanAttributes(url, parsedUrl, method, spanOrigin),\n };\n}\n\nfunction getFetchSpanAttributes(\n url: string,\n parsedUrl: ReturnType,\n method: string,\n spanOrigin: SpanOrigin,\n): SpanAttributes {\n const attributes: SpanAttributes = {\n url,\n type: 'fetch',\n 'http.method': method,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.client',\n };\n if (parsedUrl) {\n if (!isURLObjectRelative(parsedUrl)) {\n attributes['http.url'] = parsedUrl.href;\n attributes['server.address'] = parsedUrl.host;\n }\n if (parsedUrl.search) {\n attributes['http.query'] = parsedUrl.search;\n }\n if (parsedUrl.hash) {\n attributes['http.fragment'] = parsedUrl.hash;\n }\n }\n return attributes;\n}\n", "import type { SeverityLevel } from '../types-hoist/severity';\n\n/**\n * Determine a breadcrumb's log level (only `warning` or `error`) based on an HTTP status code.\n */\nexport function getBreadcrumbLogLevelFromHttpStatusCode(statusCode: number | undefined): SeverityLevel | undefined {\n // NOTE: undefined defaults to 'info' in Sentry\n if (statusCode === undefined) {\n return undefined;\n } else if (statusCode >= 400 && statusCode < 500) {\n return 'warning';\n } else if (statusCode >= 500) {\n return 'error';\n } else {\n return undefined;\n }\n}\n", "import { DEBUG_BUILD } from '../debug-build';\nimport { debug } from './debug-logger';\nimport { GLOBAL_OBJ } from './worldwide';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\ndeclare const EdgeRuntime: string | undefined;\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 {\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 {\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 {\n return false;\n }\n}\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 return 'history' in WINDOW && !!WINDOW.history;\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n * @deprecated This is no longer used and will be removed in a future major version.\n */\nexport const supportsFetch = _isFetchSupported;\n\nfunction _isFetchSupported(): boolean {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n // Deno requires a valid URL so '' cannot be used as an argument\n new Request('data:,');\n new Response();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * isNative checks if the given function is a native implementation\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFunction(func: Function): boolean {\n return func && /^function\\s+\\w+\\(\\)\\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 (!_isFetchSupported()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFunction(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?.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFunction(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n DEBUG_BUILD && debug.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 * @deprecated This is no longer used and will be removed in a future major version.\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 (!_isFetchSupported()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch {\n return false;\n }\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { HandlerDataFetch } from '../types-hoist/instrument';\nimport type { WebFetchHeaders } from '../types-hoist/webfetchapi';\nimport { isError, isRequest } from '../utils/is';\nimport { addNonEnumerableProperty, fill } from '../utils/object';\nimport { supportsNativeFetch } from '../utils/supports';\nimport { timestampInSeconds } from '../utils/time';\nimport { GLOBAL_OBJ } from '../utils/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(\n handler: (data: HandlerDataFetch) => void,\n skipNativeFetchCheck?: boolean,\n): void {\n const type = 'fetch';\n addHandler(type, handler);\n maybeInstrument(type, () => instrumentFetch(undefined, skipNativeFetchCheck));\n}\n\n/**\n * Add an instrumentation handler for long-lived fetch requests, like consuming server-sent events (SSE) via fetch.\n * The handler will resolve the request body and emit the actual `endTimestamp`, so that the\n * span can be updated accordingly.\n *\n * Only used internally\n * @hidden\n */\nexport function addFetchEndInstrumentationHandler(handler: (data: HandlerDataFetch) => void): void {\n const type = 'fetch-body-resolved';\n addHandler(type, handler);\n maybeInstrument(type, () => instrumentFetch(streamHandler));\n}\n\nfunction instrumentFetch(onFetchResolved?: (response: Response) => void, skipNativeFetchCheck: boolean = false): void {\n if (skipNativeFetchCheck && !supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n // We capture the error right here and not in the Promise error callback because Safari (and probably other\n // browsers too) will wipe the stack trace up to this point, only leaving us with this file which is useless.\n\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your fetch call did not\n // have a stack trace, so the SDK backfilled the stack trace so\n // you can see which fetch call failed.\n const virtualError = new Error();\n\n const { method, url } = parseFetchArgs(args);\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: timestampInSeconds() * 1000,\n // // Adding the error to be able to fingerprint the failed fetch event in HttpClient instrumentation\n virtualError,\n headers: getHeadersFromFetchArgs(args),\n };\n\n // if there is no callback, fetch is instrumented directly\n if (!onFetchResolved) {\n triggerHandlers('fetch', {\n ...handlerData,\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n async (response: Response) => {\n if (onFetchResolved) {\n onFetchResolved(response);\n } else {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: timestampInSeconds() * 1000,\n response,\n });\n }\n\n return response;\n },\n (error: Error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: timestampInSeconds() * 1000,\n error,\n });\n\n if (isError(error) && error.stack === undefined) {\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your fetch call did not\n // have a stack trace, so the SDK backfilled the stack trace so\n // you can see which fetch call failed.\n error.stack = virtualError.stack;\n addNonEnumerableProperty(error, 'framesToPop', 1);\n }\n\n // We enhance the not-so-helpful \"Failed to fetch\" error messages with the host\n // Possible messages we handle here:\n // * \"Failed to fetch\" (chromium)\n // * \"Load failed\" (webkit)\n // * \"NetworkError when attempting to fetch resource.\" (firefox)\n if (\n error instanceof TypeError &&\n (error.message === 'Failed to fetch' ||\n error.message === 'Load failed' ||\n error.message === 'NetworkError when attempting to fetch resource.')\n ) {\n try {\n const url = new URL(handlerData.fetchData.url);\n error.message = `${error.message} (${url.host})`;\n } catch {\n // ignore it if errors happen here\n }\n }\n\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\nasync function resolveResponse(res: Response | undefined, onFinishedResolving: () => void): Promise {\n if (res?.body) {\n const body = res.body;\n const responseReader = body.getReader();\n\n // Define a maximum duration after which we just cancel\n const maxFetchDurationTimeout = setTimeout(\n () => {\n body.cancel().then(null, () => {\n // noop\n });\n },\n 90 * 1000, // 90s\n );\n\n let readingActive = true;\n while (readingActive) {\n let chunkTimeout;\n try {\n // abort reading if read op takes more than 5s\n chunkTimeout = setTimeout(() => {\n body.cancel().then(null, () => {\n // noop on error\n });\n }, 5000);\n\n // This .read() call will reject/throw when we abort due to timeouts through `body.cancel()`\n const { done } = await responseReader.read();\n\n clearTimeout(chunkTimeout);\n\n if (done) {\n onFinishedResolving();\n readingActive = false;\n }\n } catch {\n readingActive = false;\n } finally {\n clearTimeout(chunkTimeout);\n }\n }\n\n clearTimeout(maxFetchDurationTimeout);\n\n responseReader.releaseLock();\n body.cancel().then(null, () => {\n // noop on error\n });\n }\n}\n\nfunction streamHandler(response: Response): void {\n // clone response for awaiting stream\n let clonedResponseForResolving: Response;\n try {\n clonedResponseForResolving = response.clone();\n } catch {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n resolveResponse(clonedResponseForResolving, () => {\n triggerHandlers('fetch-body-resolved', {\n endTimestamp: timestampInSeconds() * 1000,\n response,\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 [resource, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(resource),\n method: hasProp(options, 'method')\n ? String(options.method).toUpperCase()\n : // Request object as first argument\n isRequest(resource) && hasProp(resource, 'method')\n ? String(resource.method).toUpperCase()\n : '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\nfunction getHeadersFromFetchArgs(fetchArgs: unknown[]): WebFetchHeaders | undefined {\n const [requestArgument, optionsArgument] = fetchArgs;\n\n try {\n if (\n typeof optionsArgument === 'object' &&\n optionsArgument !== null &&\n 'headers' in optionsArgument &&\n optionsArgument.headers\n ) {\n return new Headers(optionsArgument.headers as any);\n }\n\n if (isRequest(requestArgument)) {\n return new Headers(requestArgument.headers);\n }\n } catch {\n // noop\n }\n\n return;\n}\n", "/*\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 * `debug` 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' | 'aws-lambda-layer';\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 // This comment is used to identify this line in the CDN bundle build step and replace this with \"return 'cdn';\"\n /* __SENTRY_SDK_SOURCE__ */ return 'npm';\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 `debug` singleton, 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/no-explicit-any\nfunction 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 * @param existingModule module to use for requiring\n * @returns possibly required module\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function loadModule(moduleName: string, existingModule: any = module): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(existingModule, moduleName);\n } catch {\n // no-empty\n }\n\n if (!mod) {\n try {\n const { cwd } = dynamicRequire(existingModule, 'process');\n mod = dynamicRequire(existingModule, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch {\n // no-empty\n }\n }\n\n return mod;\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 const process = (GLOBAL_OBJ as typeof GLOBAL_OBJ & { process?: ElectronProcess }).process;\n return process?.type === 'renderer';\n}\n", "import type { Mechanism, WrappedFunction } from '@sentry/core';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n captureException,\n getLocationHref,\n getOriginalFunction,\n GLOBAL_OBJ,\n markFunctionWrapped,\n withScope,\n} from '@sentry/core';\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// eslint-disable-next-line @typescript-eslint/ban-types\ntype WrappableFunction = Function;\n\nexport function wrap(\n fn: T,\n options?: {\n mechanism?: Mechanism;\n },\n): WrappedFunction;\nexport function wrap(\n fn: NonFunction,\n options?: {\n mechanism?: Mechanism;\n },\n): NonFunction;\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: T | NonFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n): NonFunction | WrappedFunction {\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 function isFunction(fn: T | NonFunction): fn is T {\n return typeof fn === 'function';\n }\n\n if (!isFunction(fn)) {\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 as WrappedFunction).__sentry_wrapped__;\n if (wrapper) {\n if (typeof wrapper === 'function') {\n return wrapper;\n } else {\n // If we find that the `__sentry_wrapped__` function is not a function at the time of accessing it, it means\n // that something messed with it. In that case we want to return the originally passed function.\n return fn;\n }\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch {\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 // Wrap the function itself\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped = function (this: unknown, ...args: unknown[]): unknown {\n try {\n // Also wrap arguments that are themselves functions\n const wrappedArguments = args.map(arg => 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 // no need to add a mechanism here, we already add it via an event processor above\n captureException(ex);\n });\n\n throw ex;\n }\n } as unknown as WrappedFunction;\n\n // Wrap the wrapped function in a proxy, to ensure any other properties of the original function remain available\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property as keyof T] = fn[property as keyof T];\n }\n }\n } catch {\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n }\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 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name')!;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n } catch {\n // This may throw if e.g. the descriptor does not exist, or a browser does not allow redefining `name`.\n // to save some bytes we simply try-catch this\n }\n\n return sentryWrapped;\n}\n\n/**\n * Get HTTP request data from the current page.\n */\nexport function getHttpRequestData(): { url: string; headers: Record } {\n // grab as much info as exists and add it to the event\n const url = getLocationHref();\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = {\n url,\n headers,\n };\n\n return request;\n}\n", "import type {\n Event,\n EventHint,\n Exception,\n ParameterizedString,\n SeverityLevel,\n StackFrame,\n StackParser,\n} from '@sentry/core';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n extractExceptionKeysForMessage,\n getClient,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isParameterizedString,\n isPlainObject,\n normalizeToSize,\n resolvedSyncPromise,\n} from '@sentry/core';\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: extractType(ex),\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\nfunction eventFromPlainObject(\n stackParser: StackParser,\n exception: Record,\n syntheticException?: Error,\n isUnhandledRejection?: boolean,\n): Event {\n const client = getClient();\n const normalizeDepth = client?.getOptions().normalizeDepth;\n\n // If we can, we extract an exception from the object properties\n const errorFromProp = getErrorPropertyFromObject(exception);\n\n const extra = {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n };\n\n if (errorFromProp) {\n return {\n exception: {\n values: [exceptionFromError(stackParser, errorFromProp)],\n },\n extra,\n };\n }\n\n const event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }),\n } as Exception,\n ],\n },\n extra,\n } satisfies Event;\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception.values[0]!.stacktrace = { frames };\n }\n }\n\n return event;\n}\n\nfunction 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 */\nfunction 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 skipLines = getSkipFirstStackStringLines(ex);\n const framesToPop = getPopFirstTopFrames(ex);\n\n try {\n return stackParser(stacktrace, skipLines, framesToPop);\n } catch {\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\n/**\n * Certain known React errors contain links that would be falsely\n * parsed as frames. This function check for these errors and\n * returns number of the stack string lines to skip.\n */\nfunction getSkipFirstStackStringLines(ex: Error): number {\n if (ex && reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n\n return 0;\n}\n\n/**\n * If error has `framesToPop` property, it means that the\n * creator tells us the first x frames will be useless\n * and should be discarded. Typically error from wrapper function\n * which don't point to the actual location in the developer's code.\n *\n * Example: https://github.com/zertosh/invariant/blob/master/invariant.js#L46\n */\nfunction getPopFirstTopFrames(ex: Error & { framesToPop?: unknown }): number {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n return 0;\n}\n\n// https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Exception\n// @ts-expect-error - WebAssembly.Exception is a valid class\nfunction isWebAssemblyException(exception: unknown): exception is WebAssembly.Exception {\n // Check for support\n // @ts-expect-error - WebAssembly.Exception is a valid class\n if (typeof WebAssembly !== 'undefined' && typeof WebAssembly.Exception !== 'undefined') {\n // @ts-expect-error - WebAssembly.Exception is a valid class\n return exception instanceof WebAssembly.Exception;\n } else {\n return false;\n }\n}\n\n/**\n * Extracts from errors what we use as the exception `type` in error events.\n *\n * Usually, this is the `name` property on Error objects but WASM errors need to be treated differently.\n */\nexport function extractType(ex: Error & { message: { error?: Error } }): string | undefined {\n const name = ex?.name;\n\n // The name for WebAssembly.Exception Errors needs to be extracted differently.\n // Context: https://github.com/getsentry/sentry-javascript/issues/13787\n if (!name && isWebAssemblyException(ex)) {\n // Emscripten sets array[type, message] to the \"message\" property on the WebAssembly.Exception object\n const hasTypeInMessage = ex.message && Array.isArray(ex.message) && ex.message.length == 2;\n return hasTypeInMessage ? ex.message[0] : 'WebAssembly.Exception';\n }\n\n return name;\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 */\nexport function extractMessage(ex: Error & { message: { error?: Error } }): string {\n const message = ex?.message;\n\n if (isWebAssemblyException(ex)) {\n // For Node 18, Emscripten sets array[type, message] to the \"message\" property on the WebAssembly.Exception object\n if (Array.isArray(ex.message) && ex.message.length == 2) {\n return ex.message[1];\n }\n return 'wasm exception';\n }\n\n if (!message) {\n return 'No error message';\n }\n\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\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?.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?.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 level: SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = hint?.syntheticException || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (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;\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\nfunction 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 addExceptionMechanism(event, { synthetic: true });\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 {\n // ignore errors here\n }\n}\n\n/** If a plain object has a property that is an `Error`, return this error. */\nfunction getErrorPropertyFromObject(obj: Record): Error | undefined {\n for (const prop in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n const value = obj[prop];\n if (value instanceof Error) {\n return value;\n }\n }\n }\n\n return undefined;\n}\n", "import type {\n BrowserClientProfilingOptions,\n BrowserClientReplayOptions,\n ClientOptions,\n Event,\n EventHint,\n Options as CoreOptions,\n ParameterizedString,\n Scope,\n SeverityLevel,\n} from '@sentry/core';\nimport {\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_flushMetricsBuffer,\n addAutoIpAddressToSession,\n applySdkMetadata,\n Client,\n getSDKSource,\n} from '@sentry/core';\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { BrowserTransportOptions } from './transports/types';\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\ntype BrowserSpecificOptions = BrowserClientReplayOptions &\n BrowserClientProfilingOptions & {\n /** If configured, this URL will be used as base URL for lazy loading integration. */\n cdnBaseUrl?: string;\n\n /**\n * Important: Only set this option if you know what you are doing!\n *\n * By default, the SDK will check if `Sentry.init` is called in a browser extension.\n * In case it is, it will stop initialization and log a warning\n * because browser extensions require a different Sentry initialization process:\n * https://docs.sentry.io/platforms/javascript/best-practices/shared-environments/\n *\n * Setting up the SDK in a browser extension with global error monitoring is not recommended\n * and will likely flood you with errors from other web sites or extensions. This can heavily\n * impact your quota and cause interference with your and other Sentry SDKs in shared environments.\n *\n * If this check wrongfully flags your setup as a browser extension, you can set this\n * option to `true` to skip the check.\n *\n * @default false\n */\n skipBrowserExtensionCheck?: boolean;\n\n /**\n * If set to `true`, the SDK propagates the W3C `traceparent` header to any outgoing requests,\n * in addition to the `sentry-trace` and `baggage` headers. Use the {@link CoreOptions.tracePropagationTargets}\n * option to control to which outgoing requests the header will be attached.\n *\n * **Important:** If you set this option to `true`, make sure that you configured your servers'\n * CORS settings to allow the `traceparent` header. Otherwise, requests might get blocked.\n *\n * @see https://www.w3.org/TR/trace-context/\n *\n * @default false\n */\n propagateTraceparent?: boolean;\n\n /**\n * If you use Spotlight by Sentry during development, use\n * this option to forward captured Sentry events to Spotlight.\n *\n * Either set it to true, or provide a specific Spotlight Sidecar URL.\n *\n * More details: https://spotlightjs.com/\n *\n * IMPORTANT: Only set this option to `true` while developing, not in production!\n */\n spotlight?: boolean | string;\n };\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/core Options for more information.\n */\nexport type BrowserOptions = CoreOptions & BrowserSpecificOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions & BrowserSpecificOptions;\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 Client {\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 opts = applyDefaultOptions(options);\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(opts, 'browser', ['browser'], sdkSource);\n\n // Only allow IP inferral by Relay if sendDefaultPii is true\n if (opts._metadata?.sdk) {\n opts._metadata.sdk.settings = {\n infer_ip: opts.sendDefaultPii ? 'auto' : 'never',\n // purposefully allowing already passed settings to override the default\n ...opts._metadata.sdk.settings,\n };\n }\n\n super(opts);\n\n const {\n sendDefaultPii,\n sendClientReports,\n enableLogs,\n _experiments,\n enableMetrics: enableMetricsOption,\n } = this._options;\n\n // todo(v11): Remove the experimental flag\n // eslint-disable-next-line deprecation/deprecation\n const enableMetrics = enableMetricsOption ?? _experiments?.enableMetrics ?? true;\n\n // Flush logs and metrics when page becomes hidden (e.g., tab switch, navigation)\n // todo(v11): Remove the experimental flag\n if (WINDOW.document && (sendClientReports || enableLogs || enableMetrics)) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n if (sendClientReports) {\n this._flushOutcomes();\n }\n if (enableLogs) {\n _INTERNAL_flushLogsBuffer(this);\n }\n\n if (enableMetrics) {\n _INTERNAL_flushMetricsBuffer(this);\n }\n }\n });\n }\n\n if (sendDefaultPii) {\n this.on('beforeSendSession', addAutoIpAddressToSession);\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 level: SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n currentScope: Scope,\n isolationScope: Scope,\n ): PromiseLike {\n event.platform = event.platform || 'javascript';\n\n return super._prepareEvent(event, hint, currentScope, isolationScope);\n }\n}\n\n/** Exported only for tests. */\nexport function applyDefaultOptions>(optionsArg: T): T {\n return {\n release:\n typeof __SENTRY_RELEASE__ === 'string' // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n ? __SENTRY_RELEASE__\n : WINDOW.SENTRY_RELEASE?.id, // This supports the variable that sentry-webpack-plugin injects\n sendClientReports: true,\n // We default this to true, as it is the safer scenario\n parentSpanIsAlwaysRootSpan: true,\n ...optionsArg,\n };\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 type {\n FetchBreadcrumbHint,\n HandlerDataFetch,\n SentryWrappedXMLHttpRequest,\n XhrBreadcrumbHint,\n} from '@sentry/core';\nimport { GLOBAL_OBJ } from '@sentry/core';\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\nexport type NetworkMetaWarning =\n | 'MAYBE_JSON_TRUNCATED'\n | 'TEXT_TRUNCATED'\n | 'URL_SKIPPED'\n | 'BODY_PARSE_ERROR'\n | 'BODY_PARSE_TIMEOUT'\n | 'UNPARSEABLE_BODY_TYPE';\n\ntype RequestBody = null | Blob | BufferSource | FormData | URLSearchParams | string;\n\nexport type XhrHint = XhrBreadcrumbHint & {\n xhr: XMLHttpRequest & SentryWrappedXMLHttpRequest;\n input?: RequestBody;\n};\nexport type FetchHint = FetchBreadcrumbHint & {\n input: HandlerDataFetch['args'];\n response: Response;\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 { MetricRatingThresholds, MetricType } from '../types';\n\nconst getRating = (value: number, thresholds: MetricRatingThresholds): MetricType['rating'] => {\n if (value > thresholds[1]) {\n return 'poor';\n }\n if (value > thresholds[0]) {\n return 'needs-improvement';\n }\n return 'good';\n};\n\nexport const bindReporter = (\n callback: (metric: Extract) => void,\n metric: Extract,\n thresholds: MetricRatingThresholds,\n reportAllChanges?: boolean,\n) => {\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 metric.rating = getRating(metric.value, thresholds);\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 { WINDOW } from '../../../types';\n\n// sentry-specific change:\n// add optional param to not check for responseStart (see comment below)\nexport const getNavigationEntry = (checkResponseStart = true): PerformanceNavigationTiming | void => {\n const navigationEntry = WINDOW.performance?.getEntriesByType?.('navigation')[0];\n // Check to ensure the `responseStart` property is present and valid.\n // In some cases a zero value is reported by the browser (for\n // privacy/security reasons), and in other cases (bugs) the value is\n // negative or is larger 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 // - https://github.com/GoogleChrome/web-vitals/issues/275\n if (\n // sentry-specific change:\n // We don't want to check for responseStart for our own use of `getNavigationEntry`\n !checkResponseStart ||\n (navigationEntry && navigationEntry.responseStart > 0 && navigationEntry.responseStart < performance.now())\n ) {\n return navigationEntry;\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?.activationStart ?? 0;\n};\n", "import { WINDOW } from '../../../types';\n\n/**\n * web-vitals 5.1.0 switched listeners to be added on the window rather than the document.\n * Instead of having to check for window/document every time we add a listener, we can use this function.\n */\nexport function addPageListener(type: string, listener: EventListener, options?: boolean | AddEventListenerOptions) {\n if (WINDOW.document) {\n WINDOW.addEventListener(type, listener, options);\n }\n}\n/**\n * web-vitals 5.1.0 switched listeners to be removed from the window rather than the document.\n * Instead of having to check for window/document every time we remove a listener, we can use this function.\n */\nexport function removePageListener(type: string, listener: EventListener, options?: boolean | AddEventListenerOptions) {\n if (WINDOW.document) {\n WINDOW.removeEventListener(type, listener, options);\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 { getActivationStart } from './getActivationStart';\nimport { addPageListener, removePageListener } from './globalListeners';\n\nlet firstHiddenTime = -1;\nconst onHiddenFunctions: Set<() => void> = new Set();\n\nconst initHiddenTime = () => {\n // If the document is hidden when this code runs, assume it was always\n // hidden and the page was loaded in the background, with the one exception\n // that visibility state is always 'hidden' during prerendering, so we have\n // to ignore that case until prerendering finishes (see: `prerenderingchange`\n // event logic below).\n return WINDOW.document?.visibilityState === 'hidden' && !WINDOW.document?.prerendering ? 0 : Infinity;\n};\n\nconst onVisibilityUpdate = (event: Event) => {\n // Handle changes to hidden state\n if (isPageHidden(event) && firstHiddenTime > -1) {\n // Sentry-specific change: Also call onHidden callbacks for pagehide events\n // to support older browsers (Safari <14.4) that don't properly fire visibilitychange\n if (event.type === 'visibilitychange' || event.type === 'pagehide') {\n for (const onHiddenFunction of onHiddenFunctions) {\n onHiddenFunction();\n }\n }\n\n // If the document is 'hidden' and no previous hidden timestamp has been\n // set (so is infinity), update it based on the current event data.\n if (!isFinite(firstHiddenTime)) {\n // If the event is a 'visibilitychange' event, it means the page was\n // visible prior to this change, so the event timestamp is the first\n // hidden time.\n // However, if the event is not a 'visibilitychange' event, then it must\n // be a 'prerenderingchange' or 'pagehide' event, and the fact that the document is\n // still 'hidden' from the above check means the tab was activated\n // in a background state and so has always been hidden.\n firstHiddenTime = event.type === 'visibilitychange' ? event.timeStamp : 0;\n\n // We no longer need the `prerenderingchange` event listener now we've\n // set an initial init time so remove that\n // (we'll keep the visibilitychange and pagehide ones for onHiddenFunction above)\n removePageListener('prerenderingchange', onVisibilityUpdate, true);\n }\n }\n};\n\nexport const getVisibilityWatcher = () => {\n if (WINDOW.document && firstHiddenTime < 0) {\n // Check if we have a previous hidden `visibility-state` performance entry.\n const activationStart = getActivationStart();\n const firstVisibilityStateHiddenTime = !WINDOW.document.prerendering\n ? globalThis.performance\n .getEntriesByType('visibility-state')\n .filter(e => e.name === 'hidden' && e.startTime > activationStart)[0]?.startTime\n : undefined;\n\n // Prefer that, but if it's not available and the document is hidden when\n // this code runs, assume it was hidden since navigation start. This isn't\n // a perfect heuristic, but it's the best we can do until the\n // `visibility-state` performance entry becomes available in all browsers.\n firstHiddenTime = firstVisibilityStateHiddenTime ?? initHiddenTime();\n // Listen for visibility changes so we can handle things like bfcache\n // restores and/or prerender without having to examine individual\n // timestamps in detail and also for onHidden function calls.\n addPageListener('visibilitychange', onVisibilityUpdate, true);\n\n // Sentry-specific change: Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe. This is also required for older\n // Safari versions (<14.4) that we still support.\n addPageListener('pagehide', onVisibilityUpdate, true);\n\n // IMPORTANT: when a page is prerendering, its `visibilityState` is\n // 'hidden', so in order to account for cases where this module checks for\n // visibility during prerendering, an additional check after prerendering\n // completes is also required.\n addPageListener('prerenderingchange', onVisibilityUpdate, true);\n }\n\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n onHidden(cb: () => void) {\n onHiddenFunctions.add(cb);\n },\n };\n};\n\n/**\n * Check if the page is hidden, uses the `pagehide` event for older browsers support that we used to have in `onHidden` function.\n * Some browsers we still support (Safari <14.4) don't fully support `visibilitychange`\n * or have known bugs w.r.t the `visibilitychange` event.\n * // TODO (v11): If we decide to drop support for Safari 14.4, we can use the logic from web-vitals 4.2.4\n */\nfunction isPageHidden(event: Event) {\n return event.type === 'pagehide' || WINDOW.document?.visibilityState === 'hidden';\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 = () => {\n return `v5-${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 { WINDOW } from '../../../types';\nimport type { MetricType } from '../types';\nimport { generateUniqueID } from './generateUniqueID';\nimport { getActivationStart } from './getActivationStart';\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const initMetric = (name: MetricName, value: number = -1) => {\n const navEntry = getNavigationEntry();\n let navigationType: MetricType['navigationType'] = 'navigate';\n\n if (navEntry) {\n if (WINDOW.document?.prerendering || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else if (WINDOW.document?.wasDiscarded) {\n navigationType = 'restore';\n } else if (navEntry.type) {\n navigationType = navEntry.type.replace(/_/g, '-') as MetricType['navigationType'];\n }\n }\n\n // Use `entries` type specific for the metric.\n const entries: Extract['entries'] = [];\n\n return {\n name,\n value,\n rating: 'good' as const, // If needed, will be updated when reported. `const` to keep the type from widening to `string`.\n delta: 0,\n entries,\n id: generateUniqueID(),\n navigationType,\n };\n};\n", "/*\n * Copyright 2024 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\nconst instanceMap: WeakMap = new WeakMap();\n\n/**\n * A function that accepts and identity object and a class object and returns\n * either a new instance of that class or an existing instance, if the\n * identity object was previously used.\n */\nexport function initUnique(identityObj: object, ClassObj: new () => T): T {\n if (!instanceMap.get(identityObj)) {\n instanceMap.set(identityObj, new ClassObj());\n }\n return instanceMap.get(identityObj)! as T;\n}\n", "/* eslint-disable jsdoc/require-jsdoc */\n/*\n * Copyright 2024 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\nexport class LayoutShiftManager {\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n _onAfterProcessingUnexpectedShift?: (entry: LayoutShift) => void;\n\n // eslint-disable-next-line @sentry-internal/sdk/no-class-field-initializers, @typescript-eslint/explicit-member-accessibility\n _sessionValue = 0;\n // eslint-disable-next-line @sentry-internal/sdk/no-class-field-initializers, @typescript-eslint/explicit-member-accessibility\n _sessionEntries: LayoutShift[] = [];\n\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n _processEntry(entry: LayoutShift) {\n // Only count layout shifts without recent user input.\n if (entry.hadRecentInput) return;\n\n const firstSessionEntry = this._sessionEntries[0];\n // This previously used `this._sessionEntries.at(-1)` but that is ES2022. We support ES2021 and earlier.\n const lastSessionEntry = this._sessionEntries[this._sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry\n // and less than 5 seconds after the first entry in the session,\n // include the entry in the current session. Otherwise, start a new\n // session.\n if (\n this._sessionValue &&\n firstSessionEntry &&\n lastSessionEntry &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n this._sessionValue += entry.value;\n this._sessionEntries.push(entry);\n } else {\n this._sessionValue = entry.value;\n this._sessionEntries = [entry];\n }\n\n this._onAfterProcessingUnexpectedShift?.(entry);\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\ninterface PerformanceEntryMap {\n event: PerformanceEventTiming[];\n 'first-input': PerformanceEventTiming[];\n 'layout-shift': LayoutShift[];\n 'largest-contentful-paint': LargestContentfulPaint[];\n 'long-animation-frame': PerformanceLongAnimationFrameTiming[];\n paint: PerformancePaintTiming[];\n navigation: PerformanceNavigationTiming[];\n resource: PerformanceResourceTiming[];\n // Sentry-specific change:\n // We add longtask as a supported entry type as we use this in\n // our `instrumentPerformanceObserver` function also observes 'longtask'\n // entries.\n longtask: PerformanceEntry[];\n // Sentry-specific change:\n // We add element as a supported entry type for ElementTiming API\n element: 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 // Delay by a microtask to workaround a bug in Safari where the\n // callback is invoked immediately, rather than in a separate task.\n // See: https://github.com/GoogleChrome/web-vitals/issues/277\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.resolve().then(() => {\n callback(list.getEntries() as PerformanceEntryMap[K]);\n });\n });\n po.observe({ type, buffered: true, ...opts });\n return po;\n }\n } catch {\n // Do nothing.\n }\n return;\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\nexport const runOnce = (cb: () => void) => {\n let called = false;\n return () => {\n if (!called) {\n cb();\n called = true;\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';\n\nexport const whenActivated = (callback: () => void) => {\n if (WINDOW.document?.prerendering) {\n addEventListener('prerenderingchange', () => callback(), true);\n } else {\n callback();\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 { getActivationStart } from './lib/getActivationStart';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { whenActivated } from './lib/whenActivated';\nimport type { FCPMetric, MetricRatingThresholds, ReportOpts } from './types';\n\n/** Thresholds for FCP. See https://web.dev/articles/fcp#what_is_a_good_fcp_score */\nexport const FCPThresholds: MetricRatingThresholds = [1800, 3000];\n\n/**\n * Calculates the [FCP](https://web.dev/articles/fcp) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `paint` performance entry used to determine the value. The reported\n * value is a `DOMHighResTimeStamp`.\n */\nexport const onFCP = (onReport: (metric: FCPMetric) => void, opts: ReportOpts = {}) => {\n whenActivated(() => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FCP');\n let report: ReturnType;\n\n const handleEntries = (entries: FCPMetric['entries']) => {\n for (const entry of entries) {\n if (entry.name === 'first-contentful-paint') {\n po!.disconnect();\n\n // Only report if the page wasn't hidden prior to the first paint.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n // The activationStart reference is used because FCP 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 FCP, this time should be clamped at 0.\n metric.value = Math.max(entry.startTime - getActivationStart(), 0);\n metric.entries.push(entry);\n report(true);\n }\n }\n }\n };\n\n const po = observe('paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric, FCPThresholds, opts.reportAllChanges);\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 { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { initUnique } from './lib/initUnique';\nimport { LayoutShiftManager } from './lib/LayoutShiftManager';\nimport { observe } from './lib/observe';\nimport { runOnce } from './lib/runOnce';\nimport { onFCP } from './onFCP';\nimport type { CLSMetric, MetricRatingThresholds, ReportOpts } from './types';\n\n/** Thresholds for CLS. See https://web.dev/articles/cls#what_is_a_good_cls_score */\nexport const CLSThresholds: MetricRatingThresholds = [0.1, 0.25];\n\n/**\n * Calculates the [CLS](https://web.dev/articles/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/articles/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 = (onReport: (metric: CLSMetric) => void, opts: ReportOpts = {}) => {\n // Start monitoring FCP so we can only report CLS if FCP is also reported.\n // Note: this is done to match the current behavior of CrUX.\n onFCP(\n runOnce(() => {\n const metric = initMetric('CLS', 0);\n let report: ReturnType;\n const visibilityWatcher = getVisibilityWatcher();\n\n const layoutShiftManager = initUnique(opts, LayoutShiftManager);\n\n const handleEntries = (entries: LayoutShift[]) => {\n for (const entry of entries) {\n layoutShiftManager._processEntry(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 (layoutShiftManager._sessionValue > metric.value) {\n metric.value = layoutShiftManager._sessionValue;\n metric.entries = layoutShiftManager._sessionEntries;\n report();\n }\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric, CLSThresholds, opts.reportAllChanges);\n\n visibilityWatcher.onHidden(() => {\n handleEntries(po.takeRecords() as CLSMetric['entries']);\n report(true);\n });\n\n // Queue a task to report (if nothing else triggers a report first).\n // This allows CLS to be reported as soon as FCP fires when\n // `reportAllChanges` is true.\n WINDOW?.setTimeout?.(report);\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 { 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: PerformanceEventTiming[]) => {\n entries.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", "/*\n * Copyright 2024 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 { getInteractionCount } from './polyfills/interactionCountPolyfill.js';\n\nexport interface Interaction {\n _latency: number;\n // While the `id` and `entries` properties are also internal and could be\n // mangled by prefixing with an underscore, since they correspond to public\n // symbols there is no need to mangle them as the library will compress\n // better if we reuse the existing names.\n id: number;\n entries: PerformanceEventTiming[];\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// Used to store the interaction count after a bfcache restore, since p98\n// interaction latencies should only consider the current navigation.\nlet prevInteractionCount = 0;\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 = () => {\n return getInteractionCount() - prevInteractionCount;\n};\n\n/**\n *\n */\nexport class InteractionManager {\n /**\n * A list of longest interactions on the page (by latency) sorted so the\n * longest one is first. The list is at most MAX_INTERACTIONS_TO_CONSIDER\n * long.\n */\n // eslint-disable-next-line @sentry-internal/sdk/no-class-field-initializers, @typescript-eslint/explicit-member-accessibility\n _longestInteractionList: Interaction[] = [];\n\n /**\n * A mapping of longest interactions by their interaction ID.\n * This is used for faster lookup.\n */\n // eslint-disable-next-line @sentry-internal/sdk/no-class-field-initializers, @typescript-eslint/explicit-member-accessibility\n _longestInteractionMap: Map = new Map();\n\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n _onBeforeProcessingEntry?: (entry: PerformanceEventTiming) => void;\n\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n _onAfterProcessingINPCandidate?: (interaction: Interaction) => void;\n\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility, jsdoc/require-jsdoc\n _resetInteractions() {\n prevInteractionCount = getInteractionCount();\n this._longestInteractionList.length = 0;\n this._longestInteractionMap.clear();\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 */\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n _estimateP98LongestInteraction() {\n const candidateInteractionIndex = Math.min(\n this._longestInteractionList.length - 1,\n Math.floor(getInteractionCountForNavigation() / 50),\n );\n\n return this._longestInteractionList[candidateInteractionIndex];\n }\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 */\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n _processEntry(entry: PerformanceEventTiming) {\n this._onBeforeProcessingEntry?.(entry);\n\n // Skip further processing for entries that cannot be INP candidates.\n if (!(entry.interactionId || entry.entryType === 'first-input')) return;\n\n // The least-long of the 10 longest interactions.\n const minLongestInteraction = this._longestInteractionList.at(-1);\n\n let interaction = this._longestInteractionMap.get(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 interaction ||\n this._longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER ||\n // If the above conditions are false, `minLongestInteraction` will be set.\n entry.duration > minLongestInteraction!._latency\n ) {\n // If the interaction already exists, update it. Otherwise create one.\n if (interaction) {\n // If the new entry has a longer duration, replace the old entries,\n // otherwise add to the array.\n if (entry.duration > interaction._latency) {\n interaction.entries = [entry];\n interaction._latency = entry.duration;\n } else if (entry.duration === interaction._latency && entry.startTime === interaction.entries[0]!.startTime) {\n interaction.entries.push(entry);\n }\n } else {\n interaction = {\n id: entry.interactionId,\n entries: [entry],\n _latency: entry.duration,\n };\n this._longestInteractionMap.set(interaction.id, interaction);\n this._longestInteractionList.push(interaction);\n }\n\n // Sort the entries by latency (descending) and keep only the top ten.\n this._longestInteractionList.sort((a, b) => b._latency - a._latency);\n if (this._longestInteractionList.length > MAX_INTERACTIONS_TO_CONSIDER) {\n const removedInteractions = this._longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER);\n\n for (const interaction of removedInteractions) {\n this._longestInteractionMap.delete(interaction.id);\n }\n }\n\n // Call any post-processing on the interaction\n this._onAfterProcessingINPCandidate?.(interaction);\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 { addPageListener } from './globalListeners';\n\nexport interface OnHiddenCallback {\n (event: Event): void;\n}\n\n// Sentry-specific change:\n// This function's logic was NOT updated to web-vitals 4.2.4 or 5.x but we continue\n// to use the web-vitals 3.5.2 versiondue to us having stricter browser support.\n// PR with context that made the changes: https://github.com/GoogleChrome/web-vitals/pull/442/files#r1530492402\n// The PR removed listening to the `pagehide` event, in favour of only listening to `visibilitychange` event.\n// This is \"more correct\" but some browsers we still support (Safari <14.4) don't fully support `visibilitychange`\n// or have known bugs w.r.t the `visibilitychange` event.\n// TODO (v11): If we decide to drop support for Safari 14.4, we can use the logic from web-vitals 4.2.4\n// In this case, we also need to update the integration tests that currently trigger the `pagehide` event to\n// simulate the page being hidden.\nexport const onHidden = (cb: OnHiddenCallback) => {\n const onHiddenOrPageHide = (event: Event) => {\n if (event.type === 'pagehide' || WINDOW.document?.visibilityState === 'hidden') {\n cb(event);\n }\n };\n\n addPageListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addPageListener('pagehide', onHiddenOrPageHide, true);\n};\n", "/*\n * Copyright 2024 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.js';\nimport { addPageListener, removePageListener } from './globalListeners.js';\nimport { onHidden } from './onHidden.js';\nimport { runOnce } from './runOnce.js';\n\n/**\n * Runs the passed callback during the next idle period, or immediately\n * if the browser's visibility state is (or becomes) hidden.\n */\nexport const whenIdleOrHidden = (cb: () => void) => {\n const rIC = WINDOW.requestIdleCallback || WINDOW.setTimeout;\n\n // If the document is hidden, run the callback immediately, otherwise\n // race an idle callback with the next `visibilitychange` event.\n if (WINDOW.document?.visibilityState === 'hidden') {\n cb();\n } else {\n // eslint-disable-next-line no-param-reassign\n cb = runOnce(cb);\n addPageListener('visibilitychange', cb, { once: true, capture: true });\n rIC(() => {\n cb();\n // Remove the above event listener since no longer required.\n // See: https://github.com/GoogleChrome/web-vitals/issues/622\n removePageListener('visibilitychange', cb, { capture: true });\n });\n // sentry: we use onHidden instead of directly listening to visibilitychange\n // because some browsers we still support (Safari <14.4) don't fully support\n // `visibilitychange` or have known bugs w.r.t the `visibilitychange` event.\n onHidden(cb);\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 { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { initUnique } from './lib/initUnique';\nimport { InteractionManager } from './lib/InteractionManager';\nimport { observe } from './lib/observe';\nimport { initInteractionCountPolyfill } from './lib/polyfills/interactionCountPolyfill';\nimport { whenActivated } from './lib/whenActivated';\nimport { whenIdleOrHidden } from './lib/whenIdleOrHidden';\nimport type { INPMetric, INPReportOpts, MetricRatingThresholds } from './types';\n\n/** Thresholds for INP. See https://web.dev/articles/inp#what_is_a_good_inp_score */\nexport const INPThresholds: MetricRatingThresholds = [200, 500];\n\n// The default `durationThreshold` used across this library for observing\n// `event` entries via PerformanceObserver.\nconst DEFAULT_DURATION_THRESHOLD = 40;\n\n/**\n * Calculates the [INP](https://web.dev/articles/inp) 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\n * to control what `event-timing` entries are considered for INP reporting. The\n * default threshold is `40`, which means INP scores of less than 40 will not\n * be reported. To avoid reporting no interactions in these cases, the library\n * will fall back to the input delay of the first interaction. Note that this\n * will not affect your 75th percentile INP value unless that value is also\n * less than 40 (well below the recommended\n * [good](https://web.dev/articles/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: (metric: INPMetric) => void, opts: INPReportOpts = {}) => {\n // Return if the browser doesn't support all APIs needed to measure INP.\n if (!(globalThis.PerformanceEventTiming && 'interactionId' in PerformanceEventTiming.prototype)) {\n return;\n }\n\n const visibilityWatcher = getVisibilityWatcher();\n\n whenActivated(() => {\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 interactionManager = initUnique(opts, InteractionManager);\n\n const handleEntries = (entries: INPMetric['entries']) => {\n // Queue the `handleEntries()` callback in the next idle task.\n // This is needed to increase the chances that all event entries that\n // occurred between the user interaction and the next paint\n // have been dispatched. Note: there is currently an experiment\n // running in Chrome (EventTimingKeypressAndCompositionInteractionId)\n // 123+ that if rolled out fully may make this no longer necessary.\n whenIdleOrHidden(() => {\n for (const entry of entries) {\n interactionManager._processEntry(entry);\n }\n\n const inp = interactionManager._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\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 ?? DEFAULT_DURATION_THRESHOLD,\n });\n\n report = bindReporter(onReport, metric, INPThresholds, 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 visibilityWatcher.onHidden(() => {\n handleEntries(po.takeRecords() as INPMetric['entries']);\n report(true);\n });\n }\n });\n};\n", "/*\n * Copyright 2024 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// eslint-disable-next-line jsdoc/require-jsdoc\nexport class LCPEntryManager {\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n _onBeforeProcessingEntry?: (entry: LargestContentfulPaint) => void;\n\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility, jsdoc/require-jsdoc\n _processEntry(entry: LargestContentfulPaint) {\n this._onBeforeProcessingEntry?.(entry);\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 { getActivationStart } from './lib/getActivationStart';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { addPageListener, removePageListener } from './lib/globalListeners';\nimport { initMetric } from './lib/initMetric';\nimport { initUnique } from './lib/initUnique';\nimport { LCPEntryManager } from './lib/LCPEntryManager';\nimport { observe } from './lib/observe';\nimport { runOnce } from './lib/runOnce';\nimport { whenActivated } from './lib/whenActivated';\nimport { whenIdleOrHidden } from './lib/whenIdleOrHidden';\nimport type { LCPMetric, MetricRatingThresholds, ReportOpts } from './types';\n\n/** Thresholds for LCP. See https://web.dev/articles/lcp#what_is_a_good_lcp_score */\nexport const LCPThresholds: MetricRatingThresholds = [2500, 4000];\n\n/**\n * Calculates the [LCP](https://web.dev/articles/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 *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called any time a new `largest-contentful-paint`\n * performance entry is dispatched, or once the final value of the metric has\n * been determined.\n */\nexport const onLCP = (onReport: (metric: LCPMetric) => void, opts: ReportOpts = {}) => {\n whenActivated(() => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report: ReturnType;\n\n const lcpEntryManager = initUnique(opts, LCPEntryManager);\n\n const handleEntries = (entries: LCPMetric['entries']) => {\n // If reportAllChanges is set then call this function for each entry,\n // otherwise only consider the last one.\n if (!opts.reportAllChanges) {\n // eslint-disable-next-line no-param-reassign\n entries = entries.slice(-1);\n }\n\n for (const entry of entries) {\n lcpEntryManager._processEntry(entry);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\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. But in cases\n // where `activationStart` occurs after the LCP, this time should be\n // clamped at 0.\n metric.value = Math.max(entry.startTime - getActivationStart(), 0);\n metric.entries = [entry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric, LCPThresholds, opts.reportAllChanges);\n\n // Ensure this logic only runs once, since it can be triggered from\n // any of three different event listeners below.\n const stopListening = runOnce(() => {\n handleEntries(po.takeRecords() as LCPMetric['entries']);\n po.disconnect();\n report(true);\n });\n\n // Need a separate wrapper to ensure the `runOnce` function above is\n // common for all three functions\n const stopListeningWrapper = (event: Event) => {\n if (event.isTrusted) {\n // Wrap the listener in an idle callback so it's run in a separate\n // task to reduce potential INP impact.\n // https://github.com/GoogleChrome/web-vitals/issues/383\n whenIdleOrHidden(stopListening);\n removePageListener(event.type, stopListeningWrapper, {\n capture: true,\n });\n }\n };\n\n // Stop listening after input or visibilitychange.\n // Note: while scrolling is an input that stops LCP observation, it's\n // unreliable since it can be programmatically generated.\n // See: https://github.com/GoogleChrome/web-vitals/issues/75\n for (const type of ['keydown', 'click', 'visibilitychange']) {\n addPageListener(type, stopListeningWrapper, {\n capture: true,\n });\n }\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 { getNavigationEntry } from './lib/getNavigationEntry';\nimport { initMetric } from './lib/initMetric';\nimport { whenActivated } from './lib/whenActivated';\nimport type { MetricRatingThresholds, ReportOpts, TTFBMetric } from './types';\n\n/** Thresholds for TTFB. See https://web.dev/articles/ttfb#what_is_a_good_ttfb_score */\nexport const TTFBThresholds: MetricRatingThresholds = [800, 1800];\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) => {\n if (WINDOW.document?.prerendering) {\n whenActivated(() => whenReady(callback));\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);\n }\n};\n\n/**\n * Calculates the [TTFB](https://web.dev/articles/ttfb) 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: (metric: TTFBMetric) => void, opts: ReportOpts = {}) => {\n const metric = initMetric('TTFB');\n const report = bindReporter(onReport, metric, TTFBThresholds, opts.reportAllChanges);\n\n whenReady(() => {\n const navigationEntry = getNavigationEntry();\n\n if (navigationEntry) {\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(navigationEntry.responseStart - getActivationStart(), 0);\n\n metric.entries = [navigationEntry];\n report(true);\n }\n });\n};\n", "import { debug, getFunctionName } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { onCLS } from './web-vitals/getCLS';\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 | 'element'\n // fist-input is still needed for INP\n | 'first-input';\n\ntype InstrumentHandlerTypeMetric = 'cls' | 'lcp' | '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 PerformanceScriptTiming extends PerformanceEntry {\n sourceURL: string;\n sourceFunctionName: string;\n sourceCharPosition: number;\n invoker: string;\n invokerType: string;\n}\nexport interface PerformanceLongAnimationFrameTiming extends PerformanceEntry {\n scripts: PerformanceScriptTiming[];\n}\n\ninterface Metric {\n /**\n * The name of the metric (in acronym form).\n */\n name: 'CLS' | 'FCP' | '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' | 'restore';\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 _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 TTFD metric is available.\n */\nexport function addTtfbInstrumentationHandler(callback: (data: { metric: Metric }) => void): CleanupHandlerCallback {\n return addMetricObserver('ttfb', callback, instrumentTtfb, _previousTtfb);\n}\n\nexport type InstrumentationHandlerCallback = (data: {\n metric: Omit & {\n entries: PerformanceEventTiming[];\n };\n}) => void;\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(callback: InstrumentationHandlerCallback): CleanupHandlerCallback {\n return addMetricObserver('inp', callback, instrumentInp, _previousInp);\n}\n\nexport function addPerformanceInstrumentationHandler(\n type: 'event',\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?.length) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n debug.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 // We want the callback to be called whenever the CLS value updates.\n // By default, the callback is only called when the tab goes to the background.\n { reportAllChanges: true },\n );\n}\n\nfunction instrumentLcp(): StopListening {\n return onLCP(\n metric => {\n triggerHandlers('lcp', {\n metric,\n });\n _previousLcp = metric;\n },\n // We want the callback to be called whenever the LCP value updates.\n // By default, the callback is only called when the tab goes to the background.\n { reportAllChanges: true },\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].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/**\n * Check if a PerformanceEntry is a PerformanceEventTiming by checking for the `duration` property.\n */\nexport function isPerformanceEventTiming(entry: PerformanceEntry): entry is PerformanceEventTiming {\n return 'duration' in entry;\n}\n", "import type {\n Client,\n Integration,\n SentrySpan,\n Span,\n SpanAttributes,\n SpanTimeInput,\n StartSpanOptions,\n} from '@sentry/core';\nimport { getClient, getCurrentScope, spanToJSON, startInactiveSpan, withActiveSpan } from '@sentry/core';\nimport { WINDOW } from '../types';\nimport { onHidden } from './web-vitals/lib/onHidden';\n\nexport type WebVitalReportEvent = 'pagehide' | 'navigation';\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 */\nexport function startAndEndSpan(\n parentSpan: Span,\n startTimeInSeconds: number,\n endTime: SpanTimeInput,\n { ...ctx }: StartSpanOptions,\n): Span | undefined {\n const parentStartTime = spanToJSON(parentSpan).start_timestamp;\n if (parentStartTime && parentStartTime > startTimeInSeconds) {\n // We can only do this for SentrySpans...\n if (typeof (parentSpan as Partial).updateStartTime === 'function') {\n (parentSpan as SentrySpan).updateStartTime(startTimeInSeconds);\n }\n }\n\n // The return value only exists for tests\n return withActiveSpan(parentSpan, () => {\n const span = startInactiveSpan({\n startTime: startTimeInSeconds,\n ...ctx,\n });\n\n if (span) {\n span.end(endTime);\n }\n\n return span;\n });\n}\n\ninterface StandaloneWebVitalSpanOptions {\n name: string;\n transaction?: string;\n attributes: SpanAttributes;\n startTime: number;\n}\n\n/**\n * Starts an inactive, standalone span used to send web vital values to Sentry.\n * DO NOT use this for arbitrary spans, as these spans require special handling\n * during ingestion to extract metrics.\n *\n * This function adds a bunch of attributes and data to the span that's shared\n * by all web vital standalone spans. However, you need to take care of adding\n * the actual web vital value as an event to the span. Also, you need to assign\n * a transaction name and some other values that are specific to the web vital.\n *\n * Ultimately, you also need to take care of ending the span to send it off.\n *\n * @param options\n *\n * @returns an inactive, standalone and NOT YET ended span\n */\nexport function startStandaloneWebVitalSpan(options: StandaloneWebVitalSpanOptions): Span | undefined {\n const client = getClient();\n if (!client) {\n return;\n }\n\n const { name, transaction, attributes: passedAttributes, startTime } = options;\n\n const { release, environment, sendDefaultPii } = client.getOptions();\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 = client.getIntegrationByName string }>('Replay');\n const replayId = replay?.getReplayId();\n\n const scope = getCurrentScope();\n\n const user = scope.getUser();\n const userDisplay = user !== undefined ? user.email || user.id || user.ip_address : undefined;\n\n let profileId: string | undefined;\n try {\n // @ts-expect-error skip optional chaining to save bundle size with try catch\n profileId = scope.getScopeData().contexts.profile.profile_id;\n } catch {\n // do nothing\n }\n\n const attributes: SpanAttributes = {\n release,\n environment,\n\n user: userDisplay || undefined,\n profile_id: profileId || undefined,\n replay_id: replayId || undefined,\n\n transaction,\n\n // Web vital score calculation relies on the user agent to account for different\n // browsers setting different thresholds for what is considered a good/meh/bad value.\n // For example: Chrome vs. Chrome Mobile\n 'user_agent.original': WINDOW.navigator?.userAgent,\n\n // This tells Sentry to infer the IP address from the request\n 'client.address': sendDefaultPii ? '{{auto}}' : undefined,\n\n ...passedAttributes,\n };\n\n return startInactiveSpan({\n name,\n attributes,\n startTime,\n experimental: {\n standalone: true,\n },\n });\n}\n\n/** Get the browser performance API. */\nexport function 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.addEventListener && WINDOW.performance;\n}\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nexport function msToSec(time: number): number {\n return time / 1000;\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('/') as [string, string];\n break;\n }\n // h2, h3 etc.\n if (!isNaN(Number(char))) {\n name = _name === 'h' ? 'http' : _name;\n version = nextHopProtocol.split(_name)[1] as string;\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\n/**\n * Generic support check for web vitals\n */\nexport function supportsWebVital(entryType: 'layout-shift' | 'largest-contentful-paint'): boolean {\n try {\n return PerformanceObserver.supportedEntryTypes.includes(entryType);\n } catch {\n return false;\n }\n}\n\n/**\n * Listens for events on which we want to collect a previously accumulated web vital value.\n * Currently, this includes:\n *\n * - pagehide (i.e. user minimizes browser window, hides tab, etc)\n * - soft navigation (we only care about the vital of the initially loaded route)\n *\n * As a \"side-effect\", this function will also collect the span id of the pageload span.\n *\n * @param collectorCallback the callback to be called when the first of these events is triggered. Parameters:\n * - event: the event that triggered the reporting of the web vital value.\n * - pageloadSpanId: the span id of the pageload span. This is used to link the web vital span to the pageload span.\n */\nexport function listenForWebVitalReportEvents(\n client: Client,\n collectorCallback: (event: WebVitalReportEvent, pageloadSpanId: string) => void,\n) {\n let pageloadSpanId: string | undefined;\n\n let collected = false;\n function _runCollectorCallbackOnce(event: WebVitalReportEvent) {\n if (!collected && pageloadSpanId) {\n collectorCallback(event, pageloadSpanId);\n }\n collected = true;\n }\n\n onHidden(() => {\n _runCollectorCallbackOnce('pagehide');\n });\n\n const unsubscribeStartNavigation = client.on('beforeStartNavigationSpan', (_, options) => {\n // we only want to collect LCP if we actually navigate. Redirects should be ignored.\n if (!options?.isRedirect) {\n _runCollectorCallbackOnce('navigation');\n unsubscribeStartNavigation();\n unsubscribeAfterStartPageLoadSpan();\n }\n });\n\n const unsubscribeAfterStartPageLoadSpan = client.on('afterStartPageLoadSpan', span => {\n pageloadSpanId = span.spanContext().spanId;\n unsubscribeAfterStartPageLoadSpan();\n });\n}\n", "import type { Client, SpanAttributes } from '@sentry/core';\nimport {\n browserPerformanceTimeOrigin,\n debug,\n getCurrentScope,\n htmlTreeAsString,\n SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME,\n SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT,\n SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n timestampInSeconds,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { addClsInstrumentationHandler } from './instrument';\nimport type { WebVitalReportEvent } from './utils';\nimport { listenForWebVitalReportEvents, msToSec, startStandaloneWebVitalSpan, supportsWebVital } from './utils';\n\n/**\n * Starts tracking the Cumulative Layout Shift on the current page and collects the value once\n *\n * - the page visibility is hidden\n * - a navigation span is started (to stop CLS measurement for SPA soft navigations)\n *\n * Once either of these events triggers, the CLS value is sent as a standalone span and we stop\n * measuring CLS.\n */\nexport function trackClsAsStandaloneSpan(client: Client): void {\n let standaloneCLsValue = 0;\n let standaloneClsEntry: LayoutShift | undefined;\n\n if (!supportsWebVital('layout-shift')) {\n return;\n }\n\n const cleanupClsHandler = addClsInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1] as LayoutShift | undefined;\n if (!entry) {\n return;\n }\n standaloneCLsValue = metric.value;\n standaloneClsEntry = entry;\n }, true);\n\n listenForWebVitalReportEvents(client, (reportEvent, pageloadSpanId) => {\n _sendStandaloneClsSpan(standaloneCLsValue, standaloneClsEntry, pageloadSpanId, reportEvent);\n cleanupClsHandler();\n });\n}\n\n/**\n * Exported only for testing!\n */\nexport function _sendStandaloneClsSpan(\n clsValue: number,\n entry: LayoutShift | undefined,\n pageloadSpanId: string,\n reportEvent: WebVitalReportEvent,\n) {\n DEBUG_BUILD && debug.log(`Sending CLS span (${clsValue})`);\n\n const startTime = entry ? msToSec((browserPerformanceTimeOrigin() || 0) + entry.startTime) : timestampInSeconds();\n const routeName = getCurrentScope().getScopeData().transactionName;\n\n const name = entry ? htmlTreeAsString(entry.sources[0]?.node) : 'Layout shift';\n\n const attributes: SpanAttributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser.cls',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'ui.webvital.cls',\n [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: 0,\n // attach the pageload span id to the CLS span so that we can link them in the UI\n 'sentry.pageload.span_id': pageloadSpanId,\n // describes what triggered the web vital to be reported\n 'sentry.report_event': reportEvent,\n };\n\n // Add CLS sources as span attributes to help with debugging layout shifts\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift/sources\n if (entry?.sources) {\n entry.sources.forEach((source, index) => {\n attributes[`cls.source.${index + 1}`] = htmlTreeAsString(source.node);\n });\n }\n\n const span = startStandaloneWebVitalSpan({\n name,\n transaction: routeName,\n attributes,\n startTime,\n });\n\n if (span) {\n span.addEvent('cls', {\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: '',\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: clsValue,\n });\n\n // LayoutShift performance entries always have a duration of 0, so we don't need to add `entry.duration` here\n // see: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/duration\n span.end(startTime);\n }\n}\n", "import type { Client, SpanAttributes } from '@sentry/core';\nimport {\n browserPerformanceTimeOrigin,\n debug,\n getCurrentScope,\n htmlTreeAsString,\n SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME,\n SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT,\n SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { addLcpInstrumentationHandler } from './instrument';\nimport type { WebVitalReportEvent } from './utils';\nimport { listenForWebVitalReportEvents, msToSec, startStandaloneWebVitalSpan, supportsWebVital } from './utils';\n\n/**\n * Starts tracking the Largest Contentful Paint on the current page and collects the value once\n *\n * - the page visibility is hidden\n * - a navigation span is started (to stop LCP measurement for SPA soft navigations)\n *\n * Once either of these events triggers, the LCP value is sent as a standalone span and we stop\n * measuring LCP for subsequent routes.\n */\nexport function trackLcpAsStandaloneSpan(client: Client): void {\n let standaloneLcpValue = 0;\n let standaloneLcpEntry: LargestContentfulPaint | undefined;\n\n if (!supportsWebVital('largest-contentful-paint')) {\n return;\n }\n\n const cleanupLcpHandler = addLcpInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1] as LargestContentfulPaint | undefined;\n if (!entry) {\n return;\n }\n standaloneLcpValue = metric.value;\n standaloneLcpEntry = entry;\n }, true);\n\n listenForWebVitalReportEvents(client, (reportEvent, pageloadSpanId) => {\n _sendStandaloneLcpSpan(standaloneLcpValue, standaloneLcpEntry, pageloadSpanId, reportEvent);\n cleanupLcpHandler();\n });\n}\n\n/**\n * Exported only for testing!\n */\nexport function _sendStandaloneLcpSpan(\n lcpValue: number,\n entry: LargestContentfulPaint | undefined,\n pageloadSpanId: string,\n reportEvent: WebVitalReportEvent,\n) {\n DEBUG_BUILD && debug.log(`Sending LCP span (${lcpValue})`);\n\n const startTime = msToSec((browserPerformanceTimeOrigin() || 0) + (entry?.startTime || 0));\n const routeName = getCurrentScope().getScopeData().transactionName;\n\n const name = entry ? htmlTreeAsString(entry.element) : 'Largest contentful paint';\n\n const attributes: SpanAttributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser.lcp',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'ui.webvital.lcp',\n [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: 0, // LCP is a point-in-time metric\n // attach the pageload span id to the LCP span so that we can link them in the UI\n 'sentry.pageload.span_id': pageloadSpanId,\n // describes what triggered the web vital to be reported\n 'sentry.report_event': reportEvent,\n };\n\n if (entry) {\n entry.element && (attributes['lcp.element'] = htmlTreeAsString(entry.element));\n entry.id && (attributes['lcp.id'] = entry.id);\n\n entry.url && (attributes['lcp.url'] = entry.url);\n\n // loadTime is the time of LCP that's related to receiving the LCP element response..\n entry.loadTime != null && (attributes['lcp.loadTime'] = entry.loadTime);\n\n // renderTime is loadTime + rendering time\n // it's 0 if the LCP element is loaded from a 3rd party origin that doesn't send the\n // `Timing-Allow-Origin` header.\n entry.renderTime != null && (attributes['lcp.renderTime'] = entry.renderTime);\n\n entry.size != null && (attributes['lcp.size'] = entry.size);\n }\n\n const span = startStandaloneWebVitalSpan({\n name,\n transaction: routeName,\n attributes,\n startTime,\n });\n\n if (span) {\n span.addEvent('lcp', {\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: 'millisecond',\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: lcpValue,\n });\n\n // LCP is a point-in-time metric, so we end the span immediately\n span.end(startTime);\n }\n}\n", "import type { SpanAttributes } from '@sentry/core';\nimport { browserPerformanceTimeOrigin } from '@sentry/core';\nimport { extractNetworkProtocol, getBrowserPerformanceAPI } from './utils';\n\nfunction getAbsoluteTime(time: number | undefined): number | undefined {\n // falsy values should be preserved so that we can later on drop undefined values and\n // preserve 0 vals for cross-origin resources without proper `Timing-Allow-Origin` header.\n return time ? ((browserPerformanceTimeOrigin() || performance.timeOrigin) + time) / 1000 : time;\n}\n\n/**\n * Converts a PerformanceResourceTiming entry to span data for the resource span. Most importantly,\n * it converts the timing values from timestamps relative to the `performance.timeOrigin` to absolute timestamps\n * in seconds.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming#timestamps\n *\n * @param resourceTiming\n * @returns An array where the first element is the attribute name and the second element is the attribute value.\n */\nexport function resourceTimingToSpanAttributes(resourceTiming: PerformanceResourceTiming): SpanAttributes {\n const timingSpanData: SpanAttributes = {};\n // Checking for only `undefined` and `null` is intentional because it's\n // valid for `nextHopProtocol` to be an empty string.\n if (resourceTiming.nextHopProtocol != undefined) {\n const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol);\n timingSpanData['network.protocol.version'] = version;\n timingSpanData['network.protocol.name'] = name;\n }\n\n if (!(browserPerformanceTimeOrigin() || getBrowserPerformanceAPI()?.timeOrigin)) {\n return timingSpanData;\n }\n\n return dropUndefinedKeysFromObject({\n ...timingSpanData,\n\n 'http.request.redirect_start': getAbsoluteTime(resourceTiming.redirectStart),\n 'http.request.redirect_end': getAbsoluteTime(resourceTiming.redirectEnd),\n\n 'http.request.worker_start': getAbsoluteTime(resourceTiming.workerStart),\n\n 'http.request.fetch_start': getAbsoluteTime(resourceTiming.fetchStart),\n\n 'http.request.domain_lookup_start': getAbsoluteTime(resourceTiming.domainLookupStart),\n 'http.request.domain_lookup_end': getAbsoluteTime(resourceTiming.domainLookupEnd),\n\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\n 'http.request.request_start': getAbsoluteTime(resourceTiming.requestStart),\n\n 'http.request.response_start': getAbsoluteTime(resourceTiming.responseStart),\n 'http.request.response_end': getAbsoluteTime(resourceTiming.responseEnd),\n\n // For TTFB we actually want the relative time from timeOrigin to responseStart\n // This way, TTFB always measures the \"first page load\" experience.\n // see: https://web.dev/articles/ttfb#measure-resource-requests\n 'http.request.time_to_first_byte':\n resourceTiming.responseStart != null ? resourceTiming.responseStart / 1000 : undefined,\n });\n}\n\n/**\n * Remove properties with `undefined` as value from an object.\n * In contrast to `dropUndefinedKeys` in core this funciton only works on first-level\n * key-value objects and does not recursively go into object properties or arrays.\n */\nfunction dropUndefinedKeysFromObject(attrs: T): Partial {\n return Object.fromEntries(Object.entries(attrs).filter(([, value]) => value != null)) as Partial;\n}\n", "/* eslint-disable max-lines */\nimport type { Client, Measurements, Span, SpanAttributes, SpanAttributeValue, StartSpanOptions } from '@sentry/core';\nimport {\n browserPerformanceTimeOrigin,\n getActiveSpan,\n getComponentName,\n htmlTreeAsString,\n isPrimitive,\n parseUrl,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n setMeasurement,\n spanToJSON,\n stringMatchesSomePattern,\n} from '@sentry/core';\nimport { WINDOW } from '../types';\nimport { trackClsAsStandaloneSpan } from './cls';\nimport {\n addClsInstrumentationHandler,\n addLcpInstrumentationHandler,\n addPerformanceInstrumentationHandler,\n addTtfbInstrumentationHandler,\n type PerformanceLongAnimationFrameTiming,\n} from './instrument';\nimport { trackLcpAsStandaloneSpan } from './lcp';\nimport { resourceTimingToSpanAttributes } from './resourceTiming';\nimport { getBrowserPerformanceAPI, isMeasurementValue, msToSec, startAndEndSpan } from './utils';\nimport { getActivationStart } from './web-vitals/lib/getActivationStart';\nimport { getNavigationEntry } from './web-vitals/lib/getNavigationEntry';\nimport { getVisibilityWatcher } from './web-vitals/lib/getVisibilityWatcher';\n\ninterface NavigatorNetworkInformation {\n readonly connection?: NetworkInformation;\n}\n\n// http://wicg.github.io/netinfo/#connection-types\ntype ConnectionType = 'bluetooth' | 'cellular' | 'ethernet' | 'mixed' | 'none' | 'other' | 'unknown' | 'wifi' | 'wimax';\n\n// http://wicg.github.io/netinfo/#effectiveconnectiontype-enum\ntype EffectiveConnectionType = '2g' | '3g' | '4g' | 'slow-2g';\n\n// http://wicg.github.io/netinfo/#dom-megabit\ntype Megabit = number;\n// http://wicg.github.io/netinfo/#dom-millisecond\ntype Millisecond = number;\n\n// http://wicg.github.io/netinfo/#networkinformation-interface\ninterface NetworkInformation extends EventTarget {\n // http://wicg.github.io/netinfo/#type-attribute\n readonly type?: ConnectionType;\n // http://wicg.github.io/netinfo/#effectivetype-attribute\n readonly effectiveType?: EffectiveConnectionType;\n // http://wicg.github.io/netinfo/#downlinkmax-attribute\n readonly downlinkMax?: Megabit;\n // http://wicg.github.io/netinfo/#downlink-attribute\n readonly downlink?: Megabit;\n // http://wicg.github.io/netinfo/#rtt-attribute\n readonly rtt?: Millisecond;\n // http://wicg.github.io/netinfo/#savedata-attribute\n readonly saveData?: boolean;\n // http://wicg.github.io/netinfo/#handling-changes-to-the-underlying-connection\n onchange?: EventListener;\n}\n\n// https://w3c.github.io/device-memory/#sec-device-memory-js-api\ninterface NavigatorDeviceMemory {\n readonly deviceMemory?: number;\n}\n\nconst MAX_INT_AS_BYTES = 2147483647;\n\nlet _performanceCursor: number = 0;\n\nlet _measurements: Measurements = {};\nlet _lcpEntry: LargestContentfulPaint | undefined;\nlet _clsEntry: LayoutShift | undefined;\n\ninterface StartTrackingWebVitalsOptions {\n recordClsStandaloneSpans: boolean;\n recordLcpStandaloneSpans: boolean;\n client: Client;\n}\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({\n recordClsStandaloneSpans,\n recordLcpStandaloneSpans,\n client,\n}: StartTrackingWebVitalsOptions): () => 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 lcpCleanupCallback = recordLcpStandaloneSpans ? trackLcpAsStandaloneSpan(client) : _trackLCP();\n const ttfbCleanupCallback = _trackTtfb();\n const clsCleanupCallback = recordClsStandaloneSpans ? trackClsAsStandaloneSpan(client) : _trackCLS();\n\n return (): void => {\n lcpCleanupCallback?.();\n ttfbCleanupCallback();\n clsCleanupCallback?.();\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nexport function startTrackingLongTasks(): void {\n addPerformanceInstrumentationHandler('longtask', ({ entries }) => {\n const parent = getActiveSpan();\n if (!parent) {\n return;\n }\n\n const { op: parentOp, start_timestamp: parentStartTimestamp } = spanToJSON(parent);\n\n for (const entry of entries) {\n const startTime = msToSec((browserPerformanceTimeOrigin() as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n if (parentOp === 'navigation' && parentStartTimestamp && startTime < parentStartTimestamp) {\n // Skip adding a span if the long task started before the navigation started.\n // `startAndEndSpan` will otherwise adjust the parent's start time to the span's start\n // time, potentially skewing the duration of the actual navigation as reported via our\n // routing instrumentations\n continue;\n }\n\n startAndEndSpan(parent, startTime, startTime + duration, {\n name: 'Main UI thread blocked',\n op: 'ui.long-task',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n },\n });\n }\n });\n}\n\n/**\n * Start tracking long animation frames.\n */\nexport function startTrackingLongAnimationFrames(): void {\n // NOTE: the current web-vitals version (3.5.2) does not support long-animation-frame, so\n // we directly observe `long-animation-frame` events instead of through the web-vitals\n // `observe` helper function.\n const observer = new PerformanceObserver(list => {\n const parent = getActiveSpan();\n if (!parent) {\n return;\n }\n for (const entry of list.getEntries() as PerformanceLongAnimationFrameTiming[]) {\n if (!entry.scripts[0]) {\n continue;\n }\n\n const startTime = msToSec((browserPerformanceTimeOrigin() as number) + entry.startTime);\n\n const { start_timestamp: parentStartTimestamp, op: parentOp } = spanToJSON(parent);\n\n if (parentOp === 'navigation' && parentStartTimestamp && startTime < parentStartTimestamp) {\n // Skip adding the span if the long animation frame started before the navigation started.\n // `startAndEndSpan` will otherwise adjust the parent's start time to the span's start\n // time, potentially skewing the duration of the actual navigation as reported via our\n // routing instrumentations\n continue;\n }\n const duration = msToSec(entry.duration);\n\n const attributes: SpanAttributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n };\n\n const initialScript = entry.scripts[0];\n const { invoker, invokerType, sourceURL, sourceFunctionName, sourceCharPosition } = initialScript;\n attributes['browser.script.invoker'] = invoker;\n attributes['browser.script.invoker_type'] = invokerType;\n if (sourceURL) {\n attributes['code.filepath'] = sourceURL;\n }\n if (sourceFunctionName) {\n attributes['code.function'] = sourceFunctionName;\n }\n if (sourceCharPosition !== -1) {\n attributes['browser.script.source_char_position'] = sourceCharPosition;\n }\n\n startAndEndSpan(parent, startTime, startTime + duration, {\n name: 'Main UI thread blocked',\n op: 'ui.long-animation-frame',\n attributes,\n });\n }\n });\n\n observer.observe({ type: 'long-animation-frame', buffered: true });\n}\n\n/**\n * Start tracking interaction events.\n */\nexport function startTrackingInteractions(): void {\n addPerformanceInstrumentationHandler('event', ({ entries }) => {\n const parent = getActiveSpan();\n if (!parent) {\n return;\n }\n for (const entry of entries) {\n if (entry.name === 'click') {\n const startTime = msToSec((browserPerformanceTimeOrigin() as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n const spanOptions: StartSpanOptions & Required> = {\n name: htmlTreeAsString(entry.target),\n op: `ui.interaction.${entry.name}`,\n startTime: startTime,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n },\n };\n\n const componentName = getComponentName(entry.target);\n if (componentName) {\n spanOptions.attributes['ui.component_name'] = componentName;\n }\n\n startAndEndSpan(parent, startTime, startTime + duration, spanOptions);\n }\n }\n });\n}\n\nexport { registerInpInteractionListener, startTrackingINP } from './inp';\n\n/**\n * Starts tracking the Cumulative Layout Shift on the current page and collects the value and last entry\n * to the `_measurements` object which ultimately is applied to the pageload span's measurements.\n */\nfunction _trackCLS(): () => void {\n return addClsInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1] as LayoutShift | undefined;\n if (!entry) {\n return;\n }\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry;\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 _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry as LargestContentfulPaint;\n }, true);\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 _measurements['ttfb'] = { value: metric.value, unit: 'millisecond' };\n });\n}\n\ninterface AddPerformanceEntriesOptions {\n /**\n * Flag to determine if CLS should be recorded as a measurement on the pageload span or\n * sent as a standalone span instead.\n * Sending it as a standalone span will yield more accurate LCP values.\n *\n * Default: `false` for backwards compatibility.\n */\n recordClsOnPageloadSpan: boolean;\n\n /**\n * Flag to determine if LCP should be recorded as a measurement on the pageload span or\n * sent as a standalone span instead.\n * Sending it as a standalone span will yield more accurate LCP values.\n *\n * Default: `false` for backwards compatibility.\n */\n recordLcpOnPageloadSpan: boolean;\n\n /**\n * Resource spans with `op`s matching strings in the array will not be emitted.\n *\n * Default: []\n */\n ignoreResourceSpans: Array<'resouce.script' | 'resource.css' | 'resource.img' | 'resource.other' | string>;\n\n /**\n * Performance spans created from browser Performance APIs,\n * `performance.mark(...)` nand `performance.measure(...)`\n * with `name`s matching strings in the array will not be emitted.\n *\n * Default: []\n */\n ignorePerformanceApiSpans: Array;\n}\n\n/** Add performance related spans to a transaction */\nexport function addPerformanceEntries(span: Span, options: AddPerformanceEntriesOptions): void {\n const performance = getBrowserPerformanceAPI();\n const origin = browserPerformanceTimeOrigin();\n if (!performance?.getEntries || !origin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n const timeOrigin = msToSec(origin);\n\n const performanceEntries = performance.getEntries();\n\n const { op, start_timestamp: transactionStartTime } = spanToJSON(span);\n\n performanceEntries.slice(_performanceCursor).forEach(entry => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(\n // Inexplicably, Chrome sometimes emits a negative duration. We need to work around this.\n // There is a SO post attempting to explain this, but it leaves one with open questions: https://stackoverflow.com/questions/23191918/peformance-getentries-and-negative-duration-display\n // The way we clamp the value is probably not accurate, since we have observed this happen for things that may take a while to load, like for example the replay worker.\n // TODO: Investigate why this happens and how to properly mitigate. For now, this is a workaround to prevent transactions being dropped due to negative duration spans.\n Math.max(0, entry.duration),\n );\n\n if (op === 'navigation' && transactionStartTime && timeOrigin + startTime < transactionStartTime) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(span, entry as PerformanceNavigationTiming, timeOrigin);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(span, entry, startTime, duration, timeOrigin, options.ignorePerformanceApiSpans);\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 _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n _addResourceSpans(\n span,\n entry as PerformanceResourceTiming,\n entry.name,\n startTime,\n duration,\n timeOrigin,\n options.ignoreResourceSpans,\n );\n break;\n }\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(span);\n\n // Measurements are only available for pageload transactions\n if (op === 'pageload') {\n _addTtfbRequestTimeToMeasurements(_measurements);\n\n // If CLS standalone spans are enabled, don't record CLS as a measurement\n if (!options.recordClsOnPageloadSpan) {\n delete _measurements.cls;\n }\n\n // If LCP standalone spans are enabled, don't record LCP as a measurement\n if (!options.recordLcpOnPageloadSpan) {\n delete _measurements.lcp;\n }\n\n Object.entries(_measurements).forEach(([measurementName, measurement]) => {\n setMeasurement(measurementName, measurement.value, measurement.unit);\n });\n\n // Set timeOrigin which denotes the timestamp which to base the LCP/FCP/FP/TTFB measurements on\n span.setAttribute('performance.timeOrigin', timeOrigin);\n\n // In prerendering scenarios, where a page might be prefetched and pre-rendered before the user clicks the link,\n // the navigation starts earlier than when the user clicks it. Web Vitals should always be based on the\n // user-perceived time, so they are not reported from the actual start of the navigation, but rather from the\n // time where the user actively started the navigation, for example by clicking a link.\n // This is user action is called \"activation\" and the time between navigation and activation is stored in\n // the `activationStart` attribute of the \"navigation\" PerformanceEntry.\n span.setAttribute('performance.activationStart', getActivationStart());\n\n _setWebVitalAttributes(span, options);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/**\n * React 19.2+ creates performance.measure entries for component renders.\n * We can identify them by the `detail.devtools.track` property being set to 'Components ⚛'.\n * see: https://react.dev/reference/dev-tools/react-performance-tracks\n * see: https://github.com/facebook/react/blob/06fcc8f380c6a905c7bc18d94453f623cf8cbc81/packages/react-reconciler/src/ReactFiberPerformanceTrack.js#L454-L473\n */\nfunction isReact19MeasureEntry(entry: PerformanceEntry | null): boolean | void {\n if (entry?.entryType !== 'measure') {\n return;\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return (entry as PerformanceMeasure).detail.devtools.track === 'Components ⚛';\n } catch {\n return;\n }\n}\n\n/**\n * Create measure related spans.\n * Exported only for tests.\n */\nexport function _addMeasureSpans(\n span: Span,\n entry: PerformanceEntry,\n startTime: number,\n duration: number,\n timeOrigin: number,\n ignorePerformanceApiSpans: AddPerformanceEntriesOptions['ignorePerformanceApiSpans'],\n): void {\n if (isReact19MeasureEntry(entry)) {\n return;\n }\n\n if (\n ['mark', 'measure'].includes(entry.entryType) &&\n stringMatchesSomePattern(entry.name, ignorePerformanceApiSpans)\n ) {\n return;\n }\n\n const navEntry = getNavigationEntry(false);\n\n const requestTime = msToSec(navEntry ? navEntry.requestStart : 0);\n // Because performance.measure accepts arbitrary timestamps it can produce\n // spans that happen before the browser even makes a request for the page.\n //\n // An example of this is the automatically generated Next.js-before-hydration\n // spans created by the Next.js framework.\n //\n // To prevent this we will pin the start timestamp to the request start time\n // This does make duration inaccurate, so if this does happen, we will add\n // an attribute to the span\n const measureStartTimestamp = timeOrigin + Math.max(startTime, requestTime);\n const startTimeStamp = timeOrigin + startTime;\n const measureEndTimestamp = startTimeStamp + duration;\n\n const attributes: SpanAttributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.resource.browser.metrics',\n };\n\n if (measureStartTimestamp !== startTimeStamp) {\n attributes['sentry.browser.measure_happened_before_request'] = true;\n attributes['sentry.browser.measure_start_time'] = measureStartTimestamp;\n }\n\n _addDetailToSpanAttributes(attributes, entry as PerformanceMeasure);\n\n // Measurements from third parties can be off, which would create invalid spans, dropping transactions in the process.\n if (measureStartTimestamp <= measureEndTimestamp) {\n startAndEndSpan(span, measureStartTimestamp, measureEndTimestamp, {\n name: entry.name,\n op: entry.entryType,\n attributes,\n });\n }\n}\n\nfunction _addDetailToSpanAttributes(attributes: SpanAttributes, performanceMeasure: PerformanceMeasure): void {\n try {\n // Accessing detail might throw in some browsers (e.g., Firefox) due to security restrictions\n const detail = performanceMeasure.detail;\n\n if (!detail) {\n return;\n }\n\n // Process detail based on its type\n if (typeof detail === 'object') {\n // Handle object details\n for (const [key, value] of Object.entries(detail)) {\n if (value && isPrimitive(value)) {\n attributes[`sentry.browser.measure.detail.${key}`] = value as SpanAttributeValue;\n } else if (value !== undefined) {\n try {\n // This is user defined so we can't guarantee it's serializable\n attributes[`sentry.browser.measure.detail.${key}`] = JSON.stringify(value);\n } catch {\n // Skip values that can't be stringified\n }\n }\n }\n return;\n }\n\n if (isPrimitive(detail)) {\n // Handle primitive details\n attributes['sentry.browser.measure.detail'] = detail as SpanAttributeValue;\n return;\n }\n\n try {\n attributes['sentry.browser.measure.detail'] = JSON.stringify(detail);\n } catch {\n // Skip if stringification fails\n }\n } catch {\n // Silently ignore any errors when accessing detail\n // This handles the Firefox \"Permission denied to access object\" error\n }\n}\n\n/**\n * Instrument navigation entries\n * exported only for tests\n */\nexport function _addNavigationSpans(span: Span, entry: PerformanceNavigationTiming, timeOrigin: number): void {\n (['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'] as const).forEach(event => {\n _addPerformanceNavigationTiming(span, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(span, entry, 'secureConnection', timeOrigin, 'TLS/SSL');\n _addPerformanceNavigationTiming(span, entry, 'fetch', timeOrigin, 'cache');\n _addPerformanceNavigationTiming(span, entry, 'domainLookup', timeOrigin, 'DNS');\n\n _addRequest(span, entry, timeOrigin);\n}\n\ntype StartEventName =\n | 'secureConnection'\n | 'fetch'\n | 'domainLookup'\n | 'unloadEvent'\n | 'redirect'\n | 'connect'\n | 'domContentLoadedEvent'\n | 'loadEvent';\n\ntype EndEventName =\n | 'connectEnd'\n | 'domainLookupStart'\n | 'domainLookupEnd'\n | 'unloadEventEnd'\n | 'redirectEnd'\n | 'connectEnd'\n | 'domContentLoadedEventEnd'\n | 'loadEventEnd';\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n span: Span,\n entry: PerformanceNavigationTiming,\n event: StartEventName,\n timeOrigin: number,\n name: string = event,\n): void {\n const eventEnd = _getEndPropertyNameForNavigationTiming(event) satisfies keyof PerformanceNavigationTiming;\n const end = entry[eventEnd];\n const start = entry[`${event}Start`];\n if (!start || !end) {\n return;\n }\n startAndEndSpan(span, timeOrigin + msToSec(start), timeOrigin + msToSec(end), {\n op: `browser.${name}`,\n name: entry.name,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n ...(event === 'redirect' && entry.redirectCount != null ? { 'http.redirect_count': entry.redirectCount } : {}),\n },\n });\n}\n\nfunction _getEndPropertyNameForNavigationTiming(event: StartEventName): EndEventName {\n if (event === 'secureConnection') {\n return 'connectEnd';\n }\n if (event === 'fetch') {\n return 'domainLookupStart';\n }\n return `${event}End`;\n}\n\n/** Create request and response related spans */\nfunction _addRequest(span: Span, entry: PerformanceNavigationTiming, timeOrigin: number): void {\n const requestStartTimestamp = timeOrigin + msToSec(entry.requestStart);\n const responseEndTimestamp = timeOrigin + msToSec(entry.responseEnd);\n const responseStartTimestamp = timeOrigin + msToSec(entry.responseStart);\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 span if it contained faulty spans.\n startAndEndSpan(span, requestStartTimestamp, responseEndTimestamp, {\n op: 'browser.request',\n name: entry.name,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n },\n });\n\n startAndEndSpan(span, responseStartTimestamp, responseEndTimestamp, {\n op: 'browser.response',\n name: entry.name,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n },\n });\n }\n}\n\n/**\n * Create resource-related spans.\n * Exported only for tests.\n */\nexport function _addResourceSpans(\n span: Span,\n entry: PerformanceResourceTiming,\n resourceUrl: string,\n startTime: number,\n duration: number,\n timeOrigin: number,\n ignoredResourceSpanOps?: Array,\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 op = entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other';\n if (ignoredResourceSpanOps?.includes(op)) {\n return;\n }\n\n const attributes: SpanAttributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.resource.browser.metrics',\n };\n\n const parsedUrl = parseUrl(resourceUrl);\n\n if (parsedUrl.protocol) {\n attributes['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 attributes['server.address'] = parsedUrl.host;\n }\n\n attributes['url.same_origin'] = resourceUrl.includes(WINDOW.location.origin);\n\n _setResourceRequestAttributes(entry, attributes, [\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/responseStatus\n ['responseStatus', 'http.response.status_code'],\n\n ['transferSize', 'http.response_transfer_size'],\n ['encodedBodySize', 'http.response_content_length'],\n ['decodedBodySize', 'http.decoded_response_content_length'],\n\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/renderBlockingStatus\n ['renderBlockingStatus', 'resource.render_blocking_status'],\n\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/deliveryType\n ['deliveryType', 'http.response_delivery_type'],\n ]);\n\n const attributesWithResourceTiming: SpanAttributes = { ...attributes, ...resourceTimingToSpanAttributes(entry) };\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n startAndEndSpan(span, startTimestamp, endTimestamp, {\n name: resourceUrl.replace(WINDOW.location.origin, ''),\n op,\n attributes: attributesWithResourceTiming,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(span: Span): 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 span.setAttribute('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n span.setAttribute('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 span.setAttribute('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n span.setAttribute('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to span to allow debugging */\nfunction _setWebVitalAttributes(span: Span, options: AddPerformanceEntriesOptions): void {\n // Only add LCP attributes if LCP is being recorded on the pageload span\n if (_lcpEntry && options.recordLcpOnPageloadSpan) {\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n span.setAttribute('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n span.setAttribute('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n span.setAttribute('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n if (_lcpEntry.loadTime != null) {\n // loadTime is the time of LCP that's related to receiving the LCP element response..\n span.setAttribute('lcp.loadTime', _lcpEntry.loadTime);\n }\n\n if (_lcpEntry.renderTime != null) {\n // renderTime is loadTime + rendering time\n // it's 0 if the LCP element is loaded from a 3rd party origin that doesn't send the\n // `Timing-Allow-Origin` header.\n span.setAttribute('lcp.renderTime', _lcpEntry.renderTime);\n }\n\n span.setAttribute('lcp.size', _lcpEntry.size);\n }\n\n // Only add CLS attributes if CLS is being recorded on the pageload span\n if (_clsEntry?.sources && options.recordClsOnPageloadSpan) {\n _clsEntry.sources.forEach((source, index) =>\n span.setAttribute(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n\ntype ExperimentalResourceTimingProperty =\n | 'renderBlockingStatus'\n | 'deliveryType'\n // For some reason, TS during build, errors on `responseStatus` not being a property of\n // PerformanceResourceTiming while it actually is. Hence, we're adding it here.\n // Perhaps because response status is not yet available in Webkit/Safari.\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/responseStatus\n | 'responseStatus';\n\n/**\n * Use this to set any attributes we can take directly form the PerformanceResourceTiming entry.\n *\n * This is just a mapping function for entry->attribute to keep bundle-size minimal.\n * Experimental properties are also accepted (see {@link ExperimentalResourceTimingProperty}).\n * Assumes that all entry properties might be undefined for browser-specific differences.\n * Only accepts string and number values for now and also sets 0-values.\n */\nexport function _setResourceRequestAttributes(\n entry: Partial & Partial>,\n attributes: SpanAttributes,\n properties: [keyof PerformanceResourceTiming | ExperimentalResourceTimingProperty, string][],\n): void {\n properties.forEach(([entryKey, attributeKey]) => {\n const entryVal = entry[entryKey];\n if (\n entryVal != null &&\n ((typeof entryVal === 'number' && entryVal < MAX_INT_AS_BYTES) || typeof entryVal === 'string')\n ) {\n attributes[attributeKey] = entryVal;\n }\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(false);\n if (!navEntry) {\n return;\n }\n\n const { responseStart, requestStart } = navEntry;\n\n if (requestStart <= responseStart) {\n _measurements['ttfb.requestTime'] = {\n value: responseStart - requestStart,\n unit: 'millisecond',\n };\n }\n}\n", "import type { SpanAttributes } from '@sentry/core';\nimport {\n browserPerformanceTimeOrigin,\n getActiveSpan,\n getCurrentScope,\n getRootSpan,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n spanToJSON,\n startSpan,\n timestampInSeconds,\n} from '@sentry/core';\nimport { addPerformanceInstrumentationHandler } from './instrument';\nimport { getBrowserPerformanceAPI, msToSec } from './utils';\n\n// ElementTiming interface based on the W3C spec\ninterface PerformanceElementTiming extends PerformanceEntry {\n renderTime: number;\n loadTime: number;\n intersectionRect: DOMRectReadOnly;\n identifier: string;\n naturalWidth: number;\n naturalHeight: number;\n id: string;\n element: Element | null;\n url?: string;\n}\n\n/**\n * Start tracking ElementTiming performance entries.\n */\nexport function startTrackingElementTiming(): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin()) {\n return addPerformanceInstrumentationHandler('element', _onElementTiming);\n }\n\n return () => undefined;\n}\n\n/**\n * exported only for testing\n */\nexport const _onElementTiming = ({ entries }: { entries: PerformanceEntry[] }): void => {\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan ? getRootSpan(activeSpan) : undefined;\n const transactionName = rootSpan\n ? spanToJSON(rootSpan).description\n : getCurrentScope().getScopeData().transactionName;\n\n entries.forEach(entry => {\n const elementEntry = entry as PerformanceElementTiming;\n\n // Skip entries without identifier (elementtiming attribute)\n if (!elementEntry.identifier) {\n return;\n }\n\n // `name` contains the type of the element paint. Can be `'image-paint'` or `'text-paint'`.\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceElementTiming#instance_properties\n const paintType = elementEntry.name as 'image-paint' | 'text-paint' | undefined;\n\n const renderTime = elementEntry.renderTime;\n const loadTime = elementEntry.loadTime;\n\n // starting the span at:\n // - `loadTime` if available (should be available for all \"image-paint\" entries, 0 otherwise)\n // - `renderTime` if available (available for all entries, except 3rd party images, but these should be covered by `loadTime`, 0 otherwise)\n // - `timestampInSeconds()` as a safeguard\n // see https://developer.mozilla.org/en-US/docs/Web/API/PerformanceElementTiming/renderTime#cross-origin_image_render_time\n const [spanStartTime, spanStartTimeSource] = loadTime\n ? [msToSec(loadTime), 'load-time']\n : renderTime\n ? [msToSec(renderTime), 'render-time']\n : [timestampInSeconds(), 'entry-emission'];\n\n const duration =\n paintType === 'image-paint'\n ? // for image paints, we can acually get a duration because image-paint entries also have a `loadTime`\n // and `renderTime`. `loadTime` is the time when the image finished loading and `renderTime` is the\n // time when the image finished rendering.\n msToSec(Math.max(0, (renderTime ?? 0) - (loadTime ?? 0)))\n : // for `'text-paint'` entries, we can't get a duration because the `loadTime` is always zero.\n 0;\n\n const attributes: SpanAttributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.elementtiming',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'ui.elementtiming',\n // name must be user-entered, so we can assume low cardinality\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'component',\n // recording the source of the span start time, as it varies depending on available data\n 'sentry.span_start_time_source': spanStartTimeSource,\n 'sentry.transaction_name': transactionName,\n 'element.id': elementEntry.id,\n 'element.type': elementEntry.element?.tagName?.toLowerCase() || 'unknown',\n 'element.size':\n elementEntry.naturalWidth && elementEntry.naturalHeight\n ? `${elementEntry.naturalWidth}x${elementEntry.naturalHeight}`\n : undefined,\n 'element.render_time': renderTime,\n 'element.load_time': loadTime,\n // `url` is `0`(number) for text paints (hence we fall back to undefined)\n 'element.url': elementEntry.url || undefined,\n 'element.identifier': elementEntry.identifier,\n 'element.paint_type': paintType,\n };\n\n startSpan(\n {\n name: `element[${elementEntry.identifier}]`,\n attributes,\n startTime: spanStartTime,\n onlyIfParent: true,\n },\n span => {\n span.end(spanStartTime + duration);\n },\n );\n });\n};\n", "import type { HandlerDataDom } from '@sentry/core';\nimport { addHandler, addNonEnumerableProperty, fill, maybeInstrument, triggerHandlers, uuid4 } from '@sentry/core';\nimport { WINDOW } from '../types';\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?: unknown;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\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 const globalObject = WINDOW as unknown as Record;\n const proto = globalObject[target]?.prototype;\n\n // eslint-disable-next-line no-prototype-builtins\n if (!proto?.hasOwnProperty?.('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (this: InstrumentedElement, type, listener, options): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const handlers = (this.__sentry_instrumentation_handlers__ =\n this.__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 {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListeners` 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 (this: InstrumentedElement, type, listener, options): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const handlers = this.__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 this.__sentry_instrumentation_handlers__;\n }\n }\n } catch {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListeners` 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 {\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?.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 {\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", "import type { HandlerDataHistory } from '@sentry/core';\nimport { addHandler, fill, maybeInstrument, supportsHistory, triggerHandlers } from '@sentry/core';\nimport { WINDOW } from '../types';\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\n/**\n * Exported just for testing\n */\nexport function instrumentHistory(): void {\n // The `popstate` event may also be triggered on `pushState`, but it may not always reliably be emitted by the browser\n // Which is why we also monkey-patch methods below, in addition to this\n WINDOW.addEventListener('popstate', () => {\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\n if (from === to) {\n return;\n }\n\n const handlerData = { from, to } satisfies HandlerDataHistory;\n triggerHandlers('history', handlerData);\n });\n\n // Just guard against this not being available, in weird environments\n if (!supportsHistory()) {\n return;\n }\n\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: unknown[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n const from = lastHref;\n\n // Ensure the URL is absolute\n // this can be either a path, then it is relative to the current origin\n // or a full URL of the current origin - other origins are not allowed\n // See: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState#url\n // coerce to string (this is what pushState does)\n const to = getAbsoluteUrl(String(url));\n\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n\n if (from === to) {\n return originalHistoryFunction.apply(this, args);\n }\n\n const handlerData = { from, to } satisfies HandlerDataHistory;\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\nfunction getAbsoluteUrl(urlOrPath: string): string {\n try {\n const url = new URL(urlOrPath, WINDOW.location.origin);\n return url.toString();\n } catch {\n // fallback, just do nothing\n return urlOrPath;\n }\n}\n", "import { debug, isNativeFunction } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport { WINDOW } from './types';\n\n/**\n * We generally want to use window.fetch / window.setTimeout.\n * However, in some cases this may be wrapped (e.g. by Zone.js for Angular),\n * so we try to get an unpatched version of this from a sandboxed iframe.\n */\n\ninterface CacheableImplementations {\n setTimeout: typeof WINDOW.setTimeout;\n fetch: typeof WINDOW.fetch;\n}\n\nconst cachedImplementations: Partial = {};\n\n/**\n * Get the native implementation of a browser function.\n *\n * This can be used to ensure we get an unwrapped version of a function, in cases where a wrapped function can lead to problems.\n *\n * The following methods can be retrieved:\n * - `setTimeout`: This can be wrapped by e.g. Angular, causing change detection to be triggered.\n * - `fetch`: This can be wrapped by e.g. ad-blockers, causing an infinite loop when a request is blocked.\n */\nexport function getNativeImplementation(\n name: T,\n): CacheableImplementations[T] {\n const cached = cachedImplementations[name];\n if (cached) {\n return cached;\n }\n\n let impl = WINDOW[name] as CacheableImplementations[T];\n\n // Fast path to avoid DOM I/O\n if (isNativeFunction(impl)) {\n return (cachedImplementations[name] = impl.bind(WINDOW) as CacheableImplementations[T]);\n }\n\n const document = WINDOW.document;\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?.[name]) {\n impl = contentWindow[name] as CacheableImplementations[T];\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n // Could not create sandbox iframe, just use window.xxx\n DEBUG_BUILD && debug.warn(`Could not create sandbox iframe for ${name} check, bailing to window.${name}: `, e);\n }\n }\n\n // Sanity check: This _should_ not happen, but if it does, we just skip caching...\n // This can happen e.g. in tests where fetch may not be available in the env, or similar.\n if (!impl) {\n return impl;\n }\n\n return (cachedImplementations[name] = impl.bind(WINDOW) as CacheableImplementations[T]);\n}\n\n/** Clear a cached implementation. */\nexport function clearCachedImplementation(name: keyof CacheableImplementations): void {\n cachedImplementations[name] = undefined;\n}\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 fetch(...rest: Parameters): ReturnType {\n return getNativeImplementation('fetch')(...rest);\n}\n\n/**\n * Get an unwrapped `setTimeout` method.\n * This ensures that even if e.g. Angular wraps `setTimeout`, we get the native implementation,\n * avoiding triggering change detection.\n */\nexport function setTimeout(...rest: Parameters): ReturnType {\n return getNativeImplementation('setTimeout')(...rest);\n}\n", "import type { HandlerDataXhr, SentryWrappedXMLHttpRequest } from '@sentry/core';\nimport { addHandler, isString, maybeInstrument, timestampInSeconds, triggerHandlers } from '@sentry/core';\nimport { WINDOW } from '../types';\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';\n\ntype WindowWithXhr = Window & { XMLHttpRequest?: typeof XMLHttpRequest };\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 if (!(WINDOW as WindowWithXhr).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n xhrproto.open = new Proxy(xhrproto.open, {\n apply(\n originalOpen,\n xhrOpenThisArg: XMLHttpRequest & SentryWrappedXMLHttpRequest,\n xhrOpenArgArray:\n | [method: string, url: string | URL]\n | [method: string, url: string | URL, async: boolean, username?: string | null, password?: string | null],\n ) {\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your XHR call did not\n // have a stack trace. If you are using HttpClient integration,\n // this is the expected behavior, as we are using this virtual error to capture\n // the location of your XHR call, and group your HttpClient events accordingly.\n const virtualError = new Error();\n\n const startTimestamp = timestampInSeconds() * 1000;\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(xhrOpenArgArray[0]) ? xhrOpenArgArray[0].toUpperCase() : undefined;\n const url = parseXhrUrlArg(xhrOpenArgArray[1]);\n\n if (!method || !url) {\n return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray);\n }\n\n xhrOpenThisArg[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 xhrOpenThisArg.__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 = xhrOpenThisArg[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (xhrOpenThisArg.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = xhrOpenThisArg.status;\n } catch {\n /* do nothing */\n }\n\n const handlerData: HandlerDataXhr = {\n endTimestamp: timestampInSeconds() * 1000,\n startTimestamp,\n xhr: xhrOpenThisArg,\n virtualError,\n };\n triggerHandlers('xhr', handlerData);\n }\n };\n\n if ('onreadystatechange' in xhrOpenThisArg && typeof xhrOpenThisArg.onreadystatechange === 'function') {\n xhrOpenThisArg.onreadystatechange = new Proxy(xhrOpenThisArg.onreadystatechange, {\n apply(originalOnreadystatechange, onreadystatechangeThisArg, onreadystatechangeArgArray: unknown[]) {\n onreadystatechangeHandler();\n return originalOnreadystatechange.apply(onreadystatechangeThisArg, onreadystatechangeArgArray);\n },\n });\n } else {\n xhrOpenThisArg.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 xhrOpenThisArg.setRequestHeader = new Proxy(xhrOpenThisArg.setRequestHeader, {\n apply(\n originalSetRequestHeader,\n setRequestHeaderThisArg: SentryWrappedXMLHttpRequest,\n setRequestHeaderArgArray: unknown[],\n ) {\n const [header, value] = setRequestHeaderArgArray;\n\n const xhrInfo = setRequestHeaderThisArg[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo && isString(header) && isString(value)) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return originalSetRequestHeader.apply(setRequestHeaderThisArg, setRequestHeaderArgArray);\n },\n });\n\n return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray);\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n xhrproto.send = new Proxy(xhrproto.send, {\n apply(originalSend, sendThisArg: XMLHttpRequest & SentryWrappedXMLHttpRequest, sendArgArray: unknown[]) {\n const sentryXhrData = sendThisArg[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return originalSend.apply(sendThisArg, sendArgArray);\n }\n\n if (sendArgArray[0] !== undefined) {\n sentryXhrData.body = sendArgArray[0];\n }\n\n const handlerData: HandlerDataXhr = {\n startTimestamp: timestampInSeconds() * 1000,\n xhr: sendThisArg,\n };\n triggerHandlers('xhr', handlerData);\n\n return originalSend.apply(sendThisArg, sendArgArray);\n },\n });\n}\n\n/**\n * Parses the URL argument of a XHR method to a string.\n *\n * See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open#url\n * url: A string or any other object with a stringifier — including a URL object — that provides the URL of the resource to send the request to.\n *\n * @param url - The URL argument of an XHR method\n * @returns The parsed URL string or undefined if the URL is invalid\n */\nfunction parseXhrUrlArg(url: unknown): string | undefined {\n if (isString(url)) {\n return url;\n }\n\n try {\n // If the passed in argument is not a string, it should have a `toString` method as a stringifier.\n // If that fails, we just return undefined (like in IE11 where URL is not available)\n return (url as URL).toString();\n } catch {} // eslint-disable-line no-empty\n\n return undefined;\n}\n", "import { debug } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { NetworkMetaWarning } from './types';\n\n/**\n * Serializes FormData.\n *\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 *\n */\nexport function serializeFormData(formData: FormData): string {\n // @ts-expect-error passing FormData to URLSearchParams actually works\n return new URLSearchParams(formData).toString();\n}\n\n/** Get the string representation of a body. */\nexport function getBodyString(body: unknown, _debug: typeof debug = debug): [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 (error) {\n DEBUG_BUILD && _debug.error(error, 'Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && _debug.log('Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\n/**\n * Parses the fetch arguments to extract the request payload.\n *\n * We only support getting the body from the fetch options.\n */\nexport function getFetchRequestArgBody(fetchArgs: unknown[] = []): RequestInit['body'] | undefined {\n if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== 'object') {\n return undefined;\n }\n\n return (fetchArgs[1] as RequestInit).body;\n}\n\n/**\n * Parses XMLHttpRequest response headers into a Record.\n * Extracted from replay internals to be reusable.\n */\nexport function parseXhrResponseHeaders(xhr: XMLHttpRequest): Record {\n let headers: string | undefined;\n try {\n headers = xhr.getAllResponseHeaders();\n } catch (error) {\n DEBUG_BUILD && debug.error(error, 'Failed to get xhr response headers', xhr);\n return {};\n }\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(': ') as [string, string | undefined];\n if (value) {\n acc[key.toLowerCase()] = value;\n }\n return acc;\n }, {});\n}\n", "import type { Span, SpanAttributes } from '@sentry/core';\nimport {\n browserPerformanceTimeOrigin,\n getActiveSpan,\n getCurrentScope,\n getRootSpan,\n htmlTreeAsString,\n isBrowser,\n SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME,\n SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT,\n SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n spanToJSON,\n} from '@sentry/core';\nimport { WINDOW } from '../types';\nimport type { InstrumentationHandlerCallback } from './instrument';\nimport {\n addInpInstrumentationHandler,\n addPerformanceInstrumentationHandler,\n isPerformanceEventTiming,\n} from './instrument';\nimport { getBrowserPerformanceAPI, msToSec, startStandaloneWebVitalSpan } from './utils';\n\ninterface InteractionContext {\n span: Span | undefined;\n elementName: string;\n}\n\nconst LAST_INTERACTIONS: number[] = [];\nconst INTERACTIONS_SPAN_MAP = new Map();\n\n// Map to store element names by timestamp, since we get the DOM event before the PerformanceObserver entry\nconst ELEMENT_NAME_TIMESTAMP_MAP = new Map();\n\n/**\n * 60 seconds is the maximum for a plausible INP value\n * (source: Me)\n */\nconst MAX_PLAUSIBLE_INP_DURATION = 60;\n/**\n * Start tracking INP webvital events.\n */\nexport function startTrackingINP(): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin()) {\n const inpCallback = _trackINP();\n\n return (): void => {\n inpCallback();\n };\n }\n\n return () => undefined;\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. #\n * exported only for testing\n */\nexport function _trackINP(): () => void {\n return addInpInstrumentationHandler(_onInp);\n}\n\n/**\n * exported only for testing\n */\nexport const _onInp: InstrumentationHandlerCallback = ({ metric }) => {\n if (metric.value == undefined) {\n return;\n }\n\n const duration = msToSec(metric.value);\n\n // We received occasional reports of hour-long INP values.\n // Therefore, we add a sanity check to avoid creating spans for\n // unrealistically long INP durations.\n if (duration > MAX_PLAUSIBLE_INP_DURATION) {\n return;\n }\n\n const entry = metric.entries.find(entry => entry.duration === metric.value && INP_ENTRY_MAP[entry.name]);\n\n if (!entry) {\n return;\n }\n\n const { interactionId } = entry;\n const interactionType = INP_ENTRY_MAP[entry.name];\n\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 activeSpan = getActiveSpan();\n const rootSpan = activeSpan ? getRootSpan(activeSpan) : undefined;\n\n // We first try to lookup the interaction context from our INTERACTIONS_SPAN_MAP,\n // where we cache the route and element name per interactionId\n const cachedInteractionContext = interactionId != null ? INTERACTIONS_SPAN_MAP.get(interactionId) : undefined;\n\n const spanToUse = cachedInteractionContext?.span || rootSpan;\n\n // Else, we try to use the active span.\n // Finally, we fall back to look at the transactionName on the scope\n const routeName = spanToUse ? spanToJSON(spanToUse).description : getCurrentScope().getScopeData().transactionName;\n\n const name = cachedInteractionContext?.elementName || htmlTreeAsString(entry.target);\n const attributes: SpanAttributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser.inp',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `ui.interaction.${interactionType}`,\n [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: entry.duration,\n };\n\n const span = startStandaloneWebVitalSpan({\n name,\n transaction: routeName,\n attributes,\n startTime,\n });\n\n if (span) {\n span.addEvent('inp', {\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: 'millisecond',\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: metric.value,\n });\n\n span.end(startTime + duration);\n }\n};\n\n/**\n * Register a listener to cache route information for INP interactions.\n */\nexport function registerInpInteractionListener(): void {\n // Listen for all interaction events that could contribute to INP\n const interactionEvents = Object.keys(INP_ENTRY_MAP);\n if (isBrowser()) {\n interactionEvents.forEach(eventType => {\n WINDOW.addEventListener(eventType, captureElementFromEvent, { capture: true, passive: true });\n });\n }\n\n /**\n * Captures the element name from a DOM event and stores it in the ELEMENT_NAME_TIMESTAMP_MAP.\n */\n function captureElementFromEvent(event: Event): void {\n const target = event.target as HTMLElement | null;\n if (!target) {\n return;\n }\n\n const elementName = htmlTreeAsString(target);\n const timestamp = Math.round(event.timeStamp);\n\n // Store the element name by timestamp so we can match it with the PerformanceEntry\n ELEMENT_NAME_TIMESTAMP_MAP.set(timestamp, elementName);\n\n // Clean up old\n if (ELEMENT_NAME_TIMESTAMP_MAP.size > 50) {\n const firstKey = ELEMENT_NAME_TIMESTAMP_MAP.keys().next().value;\n if (firstKey !== undefined) {\n ELEMENT_NAME_TIMESTAMP_MAP.delete(firstKey);\n }\n }\n }\n\n /**\n * Tries to get the element name from the timestamp map.\n */\n function resolveElementNameFromEntry(entry: PerformanceEntry): string {\n const timestamp = Math.round(entry.startTime);\n let elementName = ELEMENT_NAME_TIMESTAMP_MAP.get(timestamp);\n\n // try nearby timestamps (±5ms)\n if (!elementName) {\n for (let offset = -5; offset <= 5; offset++) {\n const nearbyName = ELEMENT_NAME_TIMESTAMP_MAP.get(timestamp + offset);\n if (nearbyName) {\n elementName = nearbyName;\n break;\n }\n }\n }\n\n return elementName || '';\n }\n\n const handleEntries = ({ entries }: { entries: PerformanceEntry[] }): void => {\n const activeSpan = getActiveSpan();\n const activeRootSpan = activeSpan && getRootSpan(activeSpan);\n\n entries.forEach(entry => {\n if (!isPerformanceEventTiming(entry)) {\n return;\n }\n\n const interactionId = entry.interactionId;\n if (interactionId == null) {\n return;\n }\n\n // If the interaction was already recorded before, nothing more to do\n if (INTERACTIONS_SPAN_MAP.has(interactionId)) {\n return;\n }\n\n const elementName = entry.target ? htmlTreeAsString(entry.target) : resolveElementNameFromEntry(entry);\n\n // We keep max. 10 interactions in the list, then remove the oldest one & clean up\n if (LAST_INTERACTIONS.length > 10) {\n const last = LAST_INTERACTIONS.shift() as number;\n INTERACTIONS_SPAN_MAP.delete(last);\n }\n\n // We add the interaction to the list of recorded interactions\n // and store both the span and element name for this interaction\n LAST_INTERACTIONS.push(interactionId);\n INTERACTIONS_SPAN_MAP.set(interactionId, {\n span: activeRootSpan,\n elementName,\n });\n });\n };\n\n addPerformanceInstrumentationHandler('event', handleEntries);\n addPerformanceInstrumentationHandler('first-input', handleEntries);\n}\n", "import type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/core';\nimport { createTransport, makePromiseBuffer } from '@sentry/core';\nimport { clearCachedImplementation, getNativeImplementation } from '@sentry-internal/browser-utils';\nimport type { WINDOW } from '../helpers';\nimport type { BrowserTransportOptions } from './types';\n\nconst DEFAULT_BROWSER_TRANSPORT_BUFFER_SIZE = 40;\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: typeof WINDOW.fetch = getNativeImplementation('fetch'),\n): Transport {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n async function makeRequest(request: TransportRequest): Promise {\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: 'strict-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. when finishing 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 // Note: We do not need to suppress tracing here, because we are using the native fetch, instead of our wrapped one.\n const response = await nativeFetch(options.url, requestOptions);\n\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 } catch (e) {\n clearCachedImplementation('fetch');\n throw e;\n } finally {\n pendingBodySize -= requestSize;\n pendingCount--;\n }\n }\n\n return createTransport(\n options,\n makeRequest,\n makePromiseBuffer(options.bufferSize || DEFAULT_BROWSER_TRANSPORT_BUFFER_SIZE),\n );\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", "// 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/core';\nimport { createStackParser, UNKNOWN_FUNCTION } from '@sentry/core';\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 === '' ? UNKNOWN_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// This regex matches frames that have no function name (ie. are at the top level of a module).\n// For example \"at http://localhost:5000//script.js:1:126\"\n// Frames _with_ function names usually look as follows: \"at commitLayoutEffects (react-dom.development.js:23426:1)\"\nconst chromeRegexNoFnName = /^\\s*at (\\S+?)(?::(\\d+))(?::(\\d+))\\s*$/i;\n\n// This regex matches all the frames that have a function name.\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\n\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\n// Matches stack frames with data URIs instead of filename so we can still get the function name\n// Example: \"at dynamicFn (data:application/javascript,export function dynamicFn() {...\"\nconst chromeDataUriRegex = /at (.+?) ?\\(data:(.+?),/;\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\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 dataUriMatch = line.match(chromeDataUriRegex);\n if (dataUriMatch) {\n return {\n filename: ``,\n function: dataUriMatch[1],\n };\n }\n\n // If the stack line has no function name, we need to parse it differently\n const noFnParts = chromeRegexNoFnName.exec(line) as null | [string, string, string, string];\n\n if (noFnParts) {\n const [, filename, line, col] = noFnParts;\n return createFrame(filename, UNKNOWN_FUNCTION, +line, +col);\n }\n\n const parts = chromeRegex.exec(line) as null | [string, string, string, string, string];\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]) as null | [string, string, string, string];\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) as null | [string, string, string, string, string, string];\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]) as null | [string, string, string];\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) as null | [string, string, string, string, string];\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) as null | [string, string, string, string];\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) as null | [string, string, string, string, string, string];\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];\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] as string) : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n", "/* eslint-disable max-lines */\n\nimport type {\n Breadcrumb,\n Client,\n Event as SentryEvent,\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n HandlerDataConsole,\n HandlerDataDom,\n HandlerDataFetch,\n HandlerDataHistory,\n HandlerDataXhr,\n IntegrationFn,\n XhrBreadcrumbData,\n XhrBreadcrumbHint,\n} from '@sentry/core';\nimport {\n addBreadcrumb,\n addConsoleInstrumentationHandler,\n addFetchInstrumentationHandler,\n debug,\n defineIntegration,\n getBreadcrumbLogLevelFromHttpStatusCode,\n getClient,\n getComponentName,\n getEventDescription,\n htmlTreeAsString,\n parseUrl,\n safeJoin,\n severityLevelFromString,\n} from '@sentry/core';\nimport type { FetchHint, XhrHint } from '@sentry-internal/browser-utils';\nimport {\n addClickKeypressInstrumentationHandler,\n addHistoryInstrumentationHandler,\n addXhrInstrumentationHandler,\n SENTRY_XHR_DATA_KEY,\n} from '@sentry-internal/browser-utils';\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 setup(client) {\n // TODO(v11): Remove this functionality and use `consoleIntegration` from @sentry/core instead.\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) {\n client.on('beforeSendEvent', _getSentryBreadcrumbHandler(client));\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);\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 creates 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 debug.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 {\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 const breadcrumb = {\n category: 'xhr',\n data,\n type: 'http',\n level: getBreadcrumbLogLevelFromHttpStatusCode(status_code),\n };\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint as XhrHint);\n\n addBreadcrumb(breadcrumb, hint);\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 const breadcrumbData: FetchBreadcrumbData = {\n method: handlerData.fetchData.method,\n url: handlerData.fetchData.url,\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 const breadcrumb = {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n } satisfies Breadcrumb;\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint as FetchHint);\n\n addBreadcrumb(breadcrumb, hint);\n } else {\n const response = handlerData.response as Response | undefined;\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: response?.status,\n };\n\n breadcrumbData.request_body_size = handlerData.fetchData.request_body_size;\n breadcrumbData.response_body_size = handlerData.fetchData.response_body_size;\n breadcrumbData.status_code = response?.status;\n\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n\n const breadcrumb = {\n category: 'fetch',\n data,\n type: 'http',\n level: getBreadcrumbLogLevelFromHttpStatusCode(data.status_code),\n };\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint as FetchHint);\n\n addBreadcrumb(breadcrumb, hint);\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?.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 type { IntegrationFn, WrappedFunction } from '@sentry/core';\nimport { defineIntegration, fill, getFunctionName, getOriginalFunction } from '@sentry/core';\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 = 'BrowserApiErrors';\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\ninterface BrowserApiErrorsOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n\n /**\n * If you experience issues with this integration causing double-invocations of event listeners,\n * try setting this option to `true`. It will unregister the original callbacks from the event targets\n * before adding the instrumented callback.\n *\n * @default false\n */\n unregisterOriginalCallbacks: boolean;\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 unregisterOriginalCallbacks: false,\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(target => _wrapEventTarget(target, _options));\n }\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Wrap timer functions and event targets to catch errors and provide better meta data.\n */\nexport const browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration);\n\nfunction _wrapTimeFunction(original: () => void): () => number {\n return function (this: unknown, ...args: unknown[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n handled: false,\n type: `auto.browser.browserapierrors.${getFunctionName(original)}`,\n },\n });\n return original.apply(this, args);\n };\n}\n\nfunction _wrapRAF(original: () => void): (callback: () => void) => unknown {\n return function (this: unknown, callback: () => void): () => void {\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'auto.browser.browserapierrors.requestAnimationFrame',\n },\n }),\n ]);\n };\n}\n\nfunction _wrapXHR(originalSend: () => void): () => void {\n return function (this: XMLHttpRequest, ...args: unknown[]): 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 fill(xhr, prop, function (original) {\n const wrapOptions = {\n mechanism: {\n data: {\n handler: getFunctionName(original),\n },\n handled: false,\n type: `auto.browser.browserapierrors.xhr.${prop}`,\n },\n };\n\n // If Instrument integration has been called before BrowserApiErrors, 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, integrationOptions: BrowserApiErrorsOptions): void {\n const globalObject = WINDOW as unknown as Record;\n const proto = globalObject[target]?.prototype;\n\n // eslint-disable-next-line no-prototype-builtins\n if (!proto?.hasOwnProperty?.('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: VoidFunction): (\n ...args: Parameters\n ) => ReturnType {\n return function (this: unknown, eventName, fn, options): VoidFunction {\n try {\n if (isEventListenerObject(fn)) {\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 handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'auto.browser.browserapierrors.handleEvent',\n },\n });\n }\n } catch {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n if (integrationOptions.unregisterOriginalCallbacks) {\n unregisterOriginalCallback(this, eventName, fn);\n }\n\n return original.apply(this, [\n eventName,\n wrap(fn, {\n mechanism: {\n data: {\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'auto.browser.browserapierrors.addEventListener',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(proto, 'removeEventListener', function (originalRemoveEventListener: VoidFunction): (\n this: unknown,\n ...args: Parameters\n ) => ReturnType {\n return function (this: unknown, eventName, fn, options): VoidFunction {\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 try {\n const originalEventHandler = (fn as WrappedFunction).__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, fn, options);\n };\n });\n}\n\nfunction isEventListenerObject(obj: unknown): obj is EventListenerObject {\n return typeof (obj as EventListenerObject).handleEvent === 'function';\n}\n\nfunction unregisterOriginalCallback(target: unknown, eventName: string, fn: EventListenerOrEventListenerObject): void {\n if (\n target &&\n typeof target === 'object' &&\n 'removeEventListener' in target &&\n typeof target.removeEventListener === 'function'\n ) {\n target.removeEventListener(eventName, fn);\n }\n}\n", "import { captureSession, debug, defineIntegration, startSession } from '@sentry/core';\nimport { addHistoryInstrumentationHandler } from '@sentry-internal/browser-utils';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\n/**\n * When added, automatically creates sessions which allow you to track adoption and crashes (crash free rate) in your Releases in Sentry.\n * More information: https://docs.sentry.io/product/releases/health/\n *\n * Note: In order for session tracking to work, you need to set up Releases: https://docs.sentry.io/product/releases/\n */\nexport const browserSessionIntegration = defineIntegration(() => {\n return {\n name: 'BrowserSession',\n setupOnce() {\n if (typeof WINDOW.document === 'undefined') {\n DEBUG_BUILD &&\n debug.warn('Using the `browserSessionIntegration` in non-browser environments 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", "import type { Client, Event, IntegrationFn, Primitive, StackParser } from '@sentry/core';\nimport {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n captureEvent,\n debug,\n defineIntegration,\n getClient,\n getLocationHref,\n isPrimitive,\n isString,\n UNKNOWN_FUNCTION,\n} from '@sentry/core';\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\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 = _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: 'auto.browser.global_handlers.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);\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: 'auto.browser.global_handlers.onunhandledrejection',\n },\n });\n });\n}\n\n/**\n *\n */\nexport function _getUnhandledRejectionError(error: unknown): unknown {\n if (isPrimitive(error)) {\n return error;\n }\n\n // dig the object of the rejection out of known event types\n try {\n type ErrorWithReason = { reason: unknown };\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 (error as ErrorWithReason)) {\n return (error as ErrorWithReason).reason;\n }\n\n type CustomEventWithDetail = { detail: { reason: unknown } };\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 if ('detail' in (error as CustomEventWithDetail) && 'reason' in (error as CustomEventWithDetail).detail) {\n return (error as CustomEventWithDetail).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 */\nexport function _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\nfunction _enhanceEventWithInitialFrame(\n event: Event,\n url: string | undefined,\n line: number | undefined,\n column: number | undefined,\n): 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 = column;\n const lineno = line;\n const filename = getFilenameFromUrl(url) ?? getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: UNKNOWN_FUNCTION,\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n DEBUG_BUILD && debug.log(`Global Handler attached: ${type}`);\n}\n\nfunction getOptions(): { stackParser: StackParser; attachStacktrace?: boolean } {\n const client = getClient();\n const options = client?.getOptions() || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return options;\n}\n\nfunction getFilenameFromUrl(url: string | undefined): string | undefined {\n if (!isString(url) || url.length === 0) {\n return undefined;\n }\n\n // stack frame urls can be data urls, for example when initializing a Worker with a base64 encoded script\n // in this case we just show the data prefix and mime type to avoid too long raw data urls\n if (url.startsWith('data:')) {\n const match = url.match(/^data:([^;]+)/);\n const mimeType = match ? match[1] : 'text/javascript';\n const isBase64 = url.includes('base64,');\n return ``;\n }\n\n return url; // it's fine to not truncate it as it's not put in a regex (https://codeql.github.com/codeql-query-help/javascript/js-polynomial-redos)\n}\n", "import { defineIntegration } from '@sentry/core';\nimport { getHttpRequestData, WINDOW } from '../helpers';\n\n/**\n * Collects information about HTTP request headers and\n * attaches them to the event.\n */\nexport const httpContextIntegration = defineIntegration(() => {\n return {\n name: 'HttpContext',\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 const reqData = getHttpRequestData();\n const headers = {\n ...reqData.headers,\n ...event.request?.headers,\n };\n\n event.request = {\n ...reqData,\n ...event.request,\n headers,\n };\n },\n };\n});\n", "import type { IntegrationFn } from '@sentry/core';\nimport { applyAggregateErrorsToEvent, defineIntegration } from '@sentry/core';\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 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 key,\n limit,\n event,\n hint,\n );\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Aggregrate linked errors in an event.\n */\nexport const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n", "import { consoleSandbox, getLocationHref } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\ntype ExtensionRuntime = {\n runtime?: {\n id?: string;\n };\n};\ntype ExtensionProperties = {\n chrome?: ExtensionRuntime;\n browser?: ExtensionRuntime;\n nw?: unknown;\n};\n\n/**\n * Returns true if the SDK is running in an embedded browser extension.\n * Stand-alone browser extensions (which do not share the same data as the main browser page) are fine.\n */\nexport function checkAndWarnIfIsEmbeddedBrowserExtension(): boolean {\n if (_isEmbeddedBrowserExtension()) {\n if (DEBUG_BUILD) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(\n '[Sentry] You cannot use Sentry.init() in a browser extension, see: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/',\n );\n });\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction _isEmbeddedBrowserExtension(): boolean {\n if (typeof WINDOW.window === 'undefined') {\n // No need to show the error if we're not in a browser window environment (e.g. service workers)\n return false;\n }\n\n const _window = WINDOW as typeof WINDOW & ExtensionProperties;\n\n // Running the SDK in NW.js, which appears like a browser extension but isn't, is also fine\n // see: https://github.com/getsentry/sentry-javascript/issues/12668\n if (_window.nw) {\n return false;\n }\n\n const extensionObject = _window['chrome'] || _window['browser'];\n\n if (!extensionObject?.runtime?.id) {\n return false;\n }\n\n const href = getLocationHref();\n const extensionProtocols = ['chrome-extension', 'moz-extension', 'ms-browser-extension', 'safari-web-extension'];\n\n // Running the SDK in a dedicated extension page and calling Sentry.init is fine; no risk of data leakage\n const isDedicatedExtensionPage =\n WINDOW === WINDOW.top && extensionProtocols.some(protocol => href.startsWith(`${protocol}://`));\n\n return !isDedicatedExtensionPage;\n}\n", "import type { Client, Integration, Options } from '@sentry/core';\nimport {\n dedupeIntegration,\n functionToStringIntegration,\n getIntegrationsToSetup,\n inboundFiltersIntegration,\n initAndBind,\n stackParserFromStackParserOptions,\n} from '@sentry/core';\nimport type { BrowserClientOptions, BrowserOptions } from './client';\nimport { BrowserClient } from './client';\nimport { breadcrumbsIntegration } from './integrations/breadcrumbs';\nimport { browserApiErrorsIntegration } from './integrations/browserapierrors';\nimport { browserSessionIntegration } from './integrations/browsersession';\nimport { globalHandlersIntegration } from './integrations/globalhandlers';\nimport { httpContextIntegration } from './integrations/httpcontext';\nimport { linkedErrorsIntegration } from './integrations/linkederrors';\nimport { spotlightBrowserIntegration } from './integrations/spotlight';\nimport { defaultStackParser } from './stack-parsers';\nimport { makeFetchTransport } from './transports/fetch';\nimport { checkAndWarnIfIsEmbeddedBrowserExtension } from './utils/detectBrowserExtension';\n\n/** Get the default integrations for the browser SDK. */\nexport function getDefaultIntegrations(_options: Options): Integration[] {\n /**\n * Note: Please make sure this stays in sync with Angular SDK, which re-exports\n * `getDefaultIntegrations` but with an adjusted set of integrations.\n */\n return [\n // TODO(v11): Replace with `eventFiltersIntegration` once we remove the deprecated `inboundFiltersIntegration`\n // eslint-disable-next-line deprecation/deprecation\n inboundFiltersIntegration(),\n functionToStringIntegration(),\n browserApiErrorsIntegration(),\n breadcrumbsIntegration(),\n globalHandlersIntegration(),\n linkedErrorsIntegration(),\n dedupeIntegration(),\n httpContextIntegration(),\n browserSessionIntegration(),\n ];\n}\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 { 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 = {}): Client | undefined {\n const shouldDisableBecauseIsBrowserExtenstion =\n !options.skipBrowserExtensionCheck && checkAndWarnIfIsEmbeddedBrowserExtension();\n\n let defaultIntegrations =\n options.defaultIntegrations == null ? getDefaultIntegrations(options) : options.defaultIntegrations;\n\n /* rollup-include-development-only */\n if (options.spotlight) {\n if (!defaultIntegrations) {\n defaultIntegrations = [];\n }\n const args = typeof options.spotlight === 'string' ? { sidecarUrl: options.spotlight } : undefined;\n defaultIntegrations.push(spotlightBrowserIntegration(args));\n }\n /* rollup-include-development-only-end */\n\n const clientOptions: BrowserClientOptions = {\n ...options,\n enabled: shouldDisableBecauseIsBrowserExtenstion ? false : options.enabled,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup({\n integrations: options.integrations,\n defaultIntegrations,\n }),\n transport: options.transport || makeFetchTransport,\n };\n return initAndBind(BrowserClient, clientOptions);\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", "import { GLOBAL_OBJ } from '@sentry/core';\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\n/*\nThe max. allowed value that the minReplayDuration can be set to.\nThis needs to be below 60s, so we don't unintentionally drop buffered replays that are longer than 60s.\n*/\nexport const MIN_REPLAY_DURATION_LIMIT = 50_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 __defProp$1 = Object.defineProperty;\nvar __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nvar NodeType$2 = /* @__PURE__ */ ((NodeType2) => {\n NodeType2[NodeType2[\"Document\"] = 0] = \"Document\";\n NodeType2[NodeType2[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType2[NodeType2[\"Element\"] = 2] = \"Element\";\n NodeType2[NodeType2[\"Text\"] = 3] = \"Text\";\n NodeType2[NodeType2[\"CDATA\"] = 4] = \"CDATA\";\n NodeType2[NodeType2[\"Comment\"] = 5] = \"Comment\";\n return NodeType2;\n})(NodeType$2 || {});\nfunction isElement(n2) {\n return n2.nodeType === n2.ELEMENT_NODE;\n}\nfunction isShadowRoot(n2) {\n const host = n2?.host;\n return Boolean(host?.shadowRoot === n2);\n}\nfunction isNativeShadowDom(shadowRoot) {\n return Object.prototype.toString.call(shadowRoot) === \"[object ShadowRoot]\";\n}\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\n if (cssText.includes(\" background-clip: text;\") && !cssText.includes(\" -webkit-background-clip: text;\")) {\n cssText = cssText.replace(\n /\\sbackground-clip:\\s*text;/g,\n \" -webkit-background-clip: text; background-clip: text;\"\n );\n }\n return cssText;\n}\nfunction escapeImportStatement(rule) {\n const { cssText } = rule;\n if (cssText.split('\"').length < 3) return cssText;\n const statement = [\"@import\", `url(${JSON.stringify(rule.href)})`];\n if (rule.layerName === \"\") {\n statement.push(`layer`);\n } else if (rule.layerName) {\n statement.push(`layer(${rule.layerName})`);\n }\n if (rule.supportsText) {\n statement.push(`supports(${rule.supportsText})`);\n }\n if (rule.media.length) {\n statement.push(rule.media.mediaText);\n }\n return statement.join(\" \") + \";\";\n}\nfunction stringifyStylesheet(s2) {\n try {\n const rules2 = s2.rules || s2.cssRules;\n return rules2 ? fixBrowserCompatibilityIssuesInCSS(\n Array.from(rules2, stringifyRule).join(\"\")\n ) : null;\n } catch (error) {\n return null;\n }\n}\nfunction fixAllCssProperty(rule) {\n let styles = \"\";\n for (let i2 = 0; i2 < rule.style.length; i2++) {\n const styleDeclaration = rule.style;\n const attribute = styleDeclaration[i2];\n const isImportant = styleDeclaration.getPropertyPriority(attribute);\n styles += `${attribute}:${styleDeclaration.getPropertyValue(attribute)}${isImportant ? ` !important` : \"\"};`;\n }\n return `${rule.selectorText} { ${styles} }`;\n}\nfunction stringifyRule(rule) {\n let importStringified;\n if (isCSSImportRule(rule)) {\n try {\n importStringified = // for same-origin stylesheets,\n // we can access the imported stylesheet rules directly\n stringifyStylesheet(rule.styleSheet) || // work around browser issues with the raw string `@import url(...)` statement\n escapeImportStatement(rule);\n } catch (error) {\n }\n } else if (isCSSStyleRule(rule)) {\n let cssText = rule.cssText;\n const needsSafariColonFix = rule.selectorText.includes(\":\");\n const needsAllFix = typeof rule.style[\"all\"] === \"string\" && rule.style[\"all\"];\n if (needsAllFix) {\n cssText = fixAllCssProperty(rule);\n }\n if (needsSafariColonFix) {\n cssText = fixSafariColons(cssText);\n }\n if (needsSafariColonFix || needsAllFix) {\n return cssText;\n }\n }\n return importStringified || rule.cssText;\n}\nfunction fixSafariColons(cssStringified) {\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n return cssStringified.replace(regex, \"$1\\\\$2\");\n}\nfunction isCSSImportRule(rule) {\n return \"styleSheet\" in rule;\n}\nfunction isCSSStyleRule(rule) {\n return \"selectorText\" in rule;\n}\nclass Mirror {\n constructor() {\n __publicField$1(this, \"idNodeMap\", /* @__PURE__ */ new Map());\n __publicField$1(this, \"nodeMetaMap\", /* @__PURE__ */ new WeakMap());\n }\n getId(n2) {\n if (!n2) return -1;\n const id = this.getMeta(n2)?.id;\n return id ?? -1;\n }\n getNode(id) {\n return this.idNodeMap.get(id) || null;\n }\n getIds() {\n return Array.from(this.idNodeMap.keys());\n }\n getMeta(n2) {\n return this.nodeMetaMap.get(n2) || null;\n }\n // removes the node from idNodeMap\n // doesn't remove the node from nodeMetaMap\n removeNodeFromMap(n2) {\n const id = this.getId(n2);\n this.idNodeMap.delete(id);\n if (n2.childNodes) {\n n2.childNodes.forEach(\n (childNode) => this.removeNodeFromMap(childNode)\n );\n }\n }\n has(id) {\n return this.idNodeMap.has(id);\n }\n hasNode(node) {\n return this.nodeMetaMap.has(node);\n }\n add(n2, meta) {\n const id = meta.id;\n this.idNodeMap.set(id, n2);\n this.nodeMetaMap.set(n2, meta);\n }\n replace(id, n2) {\n const oldNode = this.getNode(id);\n if (oldNode) {\n const meta = this.nodeMetaMap.get(oldNode);\n if (meta) this.nodeMetaMap.set(n2, meta);\n }\n this.idNodeMap.set(id, n2);\n }\n reset() {\n this.idNodeMap = /* @__PURE__ */ new Map();\n this.nodeMetaMap = /* @__PURE__ */ new WeakMap();\n }\n}\nfunction createMirror$2() {\n return new Mirror();\n}\nfunction shouldMaskInput({\n maskInputOptions,\n tagName,\n type\n}) {\n if (tagName === \"OPTION\") {\n tagName = \"SELECT\";\n }\n return Boolean(\n maskInputOptions[tagName.toLowerCase()] || type && maskInputOptions[type] || type === \"password\" || // Default to \"text\" option for inputs without a \"type\" attribute defined\n tagName === \"INPUT\" && !type && maskInputOptions[\"text\"]\n );\n}\nfunction maskInputValue({\n isMasked,\n element,\n value,\n maskInputFn\n}) {\n let text = value || \"\";\n if (!isMasked) {\n return text;\n }\n if (maskInputFn) {\n text = maskInputFn(text, element);\n }\n return \"*\".repeat(text.length);\n}\nfunction toLowerCase(str) {\n return str.toLowerCase();\n}\nfunction toUpperCase(str) {\n return str.toUpperCase();\n}\nconst ORIGINAL_ATTRIBUTE_NAME = \"__rrweb_original__\";\nfunction is2DCanvasBlank(canvas) {\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return true;\n const chunkSize = 50;\n for (let x = 0; x < canvas.width; x += chunkSize) {\n for (let y = 0; y < canvas.height; y += chunkSize) {\n const getImageData = ctx.getImageData;\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;\n const pixelBuffer = new Uint32Array(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n originalGetImageData.call(\n ctx,\n x,\n y,\n Math.min(chunkSize, canvas.width - x),\n Math.min(chunkSize, canvas.height - y)\n ).data.buffer\n );\n if (pixelBuffer.some((pixel) => pixel !== 0)) return false;\n }\n }\n return true;\n}\nfunction isNodeMetaEqual(a2, b) {\n if (!a2 || !b || a2.type !== b.type) return false;\n if (a2.type === NodeType$2.Document)\n return a2.compatMode === b.compatMode;\n else if (a2.type === NodeType$2.DocumentType)\n return a2.name === b.name && a2.publicId === b.publicId && a2.systemId === b.systemId;\n else if (a2.type === NodeType$2.Comment || a2.type === NodeType$2.Text || a2.type === NodeType$2.CDATA)\n return a2.textContent === b.textContent;\n else if (a2.type === NodeType$2.Element)\n return a2.tagName === b.tagName && JSON.stringify(a2.attributes) === JSON.stringify(b.attributes) && a2.isSVG === b.isSVG && a2.needBlock === b.needBlock;\n return false;\n}\nfunction getInputType(element) {\n const type = element.type;\n return element.hasAttribute(\"data-rr-is-password\") ? \"password\" : type ? (\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n toLowerCase(type)\n ) : null;\n}\nfunction getInputValue(el, tagName, type) {\n if (tagName === \"INPUT\" && (type === \"radio\" || type === \"checkbox\")) {\n return el.getAttribute(\"value\") || \"\";\n }\n return el.value;\n}\nfunction extractFileExtension(path, baseURL) {\n let url;\n try {\n url = new URL(path, baseURL ?? window.location.href);\n } catch (err) {\n return null;\n }\n const regex = /\\.([0-9a-z]+)(?:$)/i;\n const match = url.pathname.match(regex);\n return match?.[1] ?? null;\n}\nconst cachedImplementations$1 = {};\nfunction getImplementation$1(name) {\n const cached = cachedImplementations$1[name];\n if (cached) {\n return cached;\n }\n const document2 = window.document;\n let impl = window[name];\n if (document2 && typeof document2.createElement === \"function\") {\n try {\n const sandbox = document2.createElement(\"iframe\");\n sandbox.hidden = true;\n document2.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow[name]) {\n impl = // eslint-disable-next-line @typescript-eslint/unbound-method\n contentWindow[name];\n }\n document2.head.removeChild(sandbox);\n } catch (e2) {\n }\n }\n return cachedImplementations$1[name] = impl.bind(\n window\n );\n}\nfunction setTimeout$2(...rest) {\n return getImplementation$1(\"setTimeout\")(...rest);\n}\nfunction clearTimeout$1(...rest) {\n return getImplementation$1(\"clearTimeout\")(...rest);\n}\nfunction getIframeContentDocument(iframe) {\n try {\n return iframe.contentDocument;\n } catch (e2) {\n }\n}\nlet _id = 1;\nconst tagNameRegex = new RegExp(\"[^a-z0-9-_:]\");\nconst IGNORED_NODE = -2;\nfunction genId() {\n return _id++;\n}\nfunction getValidTagName$1(element) {\n if (element instanceof HTMLFormElement) {\n return \"form\";\n }\n const processedTagName = toLowerCase(element.tagName);\n if (tagNameRegex.test(processedTagName)) {\n return \"div\";\n }\n return processedTagName;\n}\nfunction extractOrigin(url) {\n let origin = \"\";\n if (url.indexOf(\"//\") > -1) {\n origin = url.split(\"/\").slice(0, 3).join(\"/\");\n } else {\n origin = url.split(\"/\")[0];\n }\n origin = origin.split(\"?\")[0];\n return origin;\n}\nlet canvasService;\nlet canvasCtx;\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\nconst URL_WWW_MATCH = /^www\\..*/i;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction filterCSSPropertiesFromInlineStyle(cssText, ignoredProperties) {\n if (!cssText || ignoredProperties.size === 0) {\n return cssText;\n }\n try {\n const properties = cssText.split(\";\");\n const filteredProperties = [];\n for (let property of properties) {\n property = property.trim();\n if (!property) continue;\n const colonIndex = property.indexOf(\":\");\n if (colonIndex === -1) {\n filteredProperties.push(property);\n continue;\n }\n const propertyName = property.slice(0, colonIndex).trim();\n if (!ignoredProperties.has(propertyName)) {\n filteredProperties.push(property);\n }\n }\n return filteredProperties.join(\"; \") + (filteredProperties.length > 0 && cssText.endsWith(\";\") ? \";\" : \"\");\n } catch (error) {\n console.warn(\"Error filtering CSS properties:\", error);\n return cssText;\n }\n}\nfunction absoluteToStylesheet(cssText, href) {\n return (cssText || \"\").replace(\n URL_IN_CSS_REF,\n (origin, quote1, path1, quote2, path2, path3) => {\n const filePath = path1 || path2 || path3;\n const maybeQuote = quote1 || quote2 || \"\";\n if (!filePath) {\n return origin;\n }\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (DATA_URI.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (filePath[0] === \"/\") {\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\n }\n const stack = href.split(\"/\");\n const parts = filePath.split(\"/\");\n stack.pop();\n for (const part of parts) {\n if (part === \".\") {\n continue;\n } else if (part === \"..\") {\n stack.pop();\n } else {\n stack.push(part);\n }\n }\n return `url(${maybeQuote}${stack.join(\"/\")}${maybeQuote})`;\n }\n );\n}\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n if (attributeValue.trim() === \"\") {\n return attributeValue;\n }\n let pos = 0;\n function collectCharacters(regEx) {\n let chars2;\n const match = regEx.exec(attributeValue.substring(pos));\n if (match) {\n chars2 = match[0];\n pos += chars2.length;\n return chars2;\n }\n return \"\";\n }\n const output = [];\n while (true) {\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\n if (pos >= attributeValue.length) {\n break;\n }\n let url = collectCharacters(SRCSET_NOT_SPACES);\n if (url.slice(-1) === \",\") {\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n output.push(url);\n } else {\n let descriptorsStr = \"\";\n url = absoluteToDoc(doc, url);\n let inParens = false;\n while (true) {\n const c2 = attributeValue.charAt(pos);\n if (c2 === \"\") {\n output.push((url + descriptorsStr).trim());\n break;\n } else if (!inParens) {\n if (c2 === \",\") {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n } else if (c2 === \"(\") {\n inParens = true;\n }\n } else {\n if (c2 === \")\") {\n inParens = false;\n }\n }\n descriptorsStr += c2;\n pos += 1;\n }\n }\n }\n return output.join(\", \");\n}\nconst cachedDocument = /* @__PURE__ */ new WeakMap();\nfunction absoluteToDoc(doc, attributeValue) {\n if (!attributeValue || attributeValue.trim() === \"\") {\n return attributeValue;\n }\n return getHref(doc, attributeValue);\n}\nfunction isSVGElement(el) {\n return Boolean(el.tagName === \"svg\" || el.ownerSVGElement);\n}\nfunction getHref(doc, customHref) {\n let a2 = cachedDocument.get(doc);\n if (!a2) {\n a2 = doc.createElement(\"a\");\n cachedDocument.set(doc, a2);\n }\n if (!customHref) {\n customHref = \"\";\n } else if (customHref.startsWith(\"blob:\") || customHref.startsWith(\"data:\")) {\n return customHref;\n }\n a2.setAttribute(\"href\", customHref);\n return a2.href;\n}\nfunction transformAttribute(doc, tagName, name, value, element, maskAttributeFn, ignoreCSSAttributes) {\n if (!value) {\n return value;\n }\n if (name === \"src\" || name === \"href\" && !(tagName === \"use\" && value[0] === \"#\")) {\n return absoluteToDoc(doc, value);\n } else if (name === \"xlink:href\" && value[0] !== \"#\") {\n return absoluteToDoc(doc, value);\n } else if (name === \"background\" && (tagName === \"table\" || tagName === \"td\" || tagName === \"th\")) {\n return absoluteToDoc(doc, value);\n } else if (name === \"srcset\") {\n return getAbsoluteSrcsetString(doc, value);\n } else if (name === \"style\") {\n let processedStyle = absoluteToStylesheet(value, getHref(doc));\n if (ignoreCSSAttributes && ignoreCSSAttributes.size > 0) {\n processedStyle = filterCSSPropertiesFromInlineStyle(\n processedStyle,\n ignoreCSSAttributes\n );\n }\n return processedStyle;\n } else if (tagName === \"object\" && name === \"data\") {\n return absoluteToDoc(doc, value);\n }\n if (typeof maskAttributeFn === \"function\") {\n return maskAttributeFn(name, value, element);\n }\n return value;\n}\nfunction ignoreAttribute(tagName, name, _value) {\n return (tagName === \"video\" || tagName === \"audio\") && name === \"autoplay\";\n}\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\n try {\n if (unblockSelector && element.matches(unblockSelector)) {\n return false;\n }\n if (typeof blockClass === \"string\") {\n if (element.classList.contains(blockClass)) {\n return true;\n }\n } else {\n for (let eIndex = element.classList.length; eIndex--; ) {\n const className = element.classList[eIndex];\n if (blockClass.test(className)) {\n return true;\n }\n }\n }\n if (blockSelector) {\n return element.matches(blockSelector);\n }\n } catch (e2) {\n }\n return false;\n}\nfunction elementClassMatchesRegex(el, regex) {\n for (let eIndex = el.classList.length; eIndex--; ) {\n const className = el.classList[eIndex];\n if (regex.test(className)) {\n return true;\n }\n }\n return false;\n}\nfunction distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\n if (!node) return -1;\n if (node.nodeType !== node.ELEMENT_NODE) return -1;\n if (distance > limit) return -1;\n if (matchPredicate(node)) return distance;\n return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1);\n}\nfunction createMatchPredicate(className, selector) {\n return (node) => {\n const el = node;\n if (el === null) return false;\n try {\n if (className) {\n if (typeof className === \"string\") {\n if (el.matches(`.${className}`)) return true;\n } else if (elementClassMatchesRegex(el, className)) {\n return true;\n }\n }\n if (selector && el.matches(selector)) return true;\n return false;\n } catch {\n return false;\n }\n };\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\n try {\n const el = node.nodeType === node.ELEMENT_NODE ? node : node.parentElement;\n if (el === null) return false;\n if (el.tagName === \"INPUT\") {\n const autocomplete = el.getAttribute(\"autocomplete\");\n const disallowedAutocompleteValues = [\n \"current-password\",\n \"new-password\",\n \"cc-number\",\n \"cc-exp\",\n \"cc-exp-month\",\n \"cc-exp-year\",\n \"cc-csc\"\n ];\n if (disallowedAutocompleteValues.includes(autocomplete)) {\n return true;\n }\n }\n let maskDistance = -1;\n let unmaskDistance = -1;\n if (maskAllText) {\n unmaskDistance = distanceToMatch(\n el,\n createMatchPredicate(unmaskTextClass, unmaskTextSelector)\n );\n if (unmaskDistance < 0) {\n return true;\n }\n maskDistance = distanceToMatch(\n el,\n createMatchPredicate(maskTextClass, maskTextSelector),\n unmaskDistance >= 0 ? unmaskDistance : Infinity\n );\n } else {\n maskDistance = distanceToMatch(\n el,\n createMatchPredicate(maskTextClass, maskTextSelector)\n );\n if (maskDistance < 0) {\n return false;\n }\n unmaskDistance = distanceToMatch(\n el,\n createMatchPredicate(unmaskTextClass, unmaskTextSelector),\n maskDistance >= 0 ? maskDistance : Infinity\n );\n }\n return maskDistance >= 0 ? unmaskDistance >= 0 ? maskDistance <= unmaskDistance : true : unmaskDistance >= 0 ? false : !!maskAllText;\n } catch (e2) {\n }\n return !!maskAllText;\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n const win = iframeEl.contentWindow;\n if (!win) {\n return;\n }\n let fired = false;\n let readyState;\n try {\n readyState = win.document.readyState;\n } catch (error) {\n return;\n }\n if (readyState !== \"complete\") {\n const timer = setTimeout$2(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, iframeLoadTimeout);\n iframeEl.addEventListener(\"load\", () => {\n clearTimeout$1(timer);\n fired = true;\n listener();\n });\n return;\n }\n const blankUrl = \"about:blank\";\n if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === \"\") {\n setTimeout$2(listener, 0);\n return iframeEl.addEventListener(\"load\", listener);\n }\n iframeEl.addEventListener(\"load\", listener);\n}\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\n let fired = false;\n let styleSheetLoaded;\n try {\n styleSheetLoaded = link.sheet;\n } catch (error) {\n return;\n }\n if (styleSheetLoaded) return;\n const timer = setTimeout$2(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, styleSheetLoadTimeout);\n link.addEventListener(\"load\", () => {\n clearTimeout$1(timer);\n fired = true;\n listener();\n });\n}\nfunction serializeNode(n2, options) {\n const {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskAttributeFn,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputOptions = {},\n maskTextFn,\n maskInputFn,\n dataURLOptions = {},\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement = false,\n ignoreCSSAttributes\n } = options;\n const rootId = getRootId(doc, mirror2);\n switch (n2.nodeType) {\n case n2.DOCUMENT_NODE:\n if (n2.compatMode !== \"CSS1Compat\") {\n return {\n type: NodeType$2.Document,\n childNodes: [],\n compatMode: n2.compatMode\n // probably \"BackCompat\"\n };\n } else {\n return {\n type: NodeType$2.Document,\n childNodes: []\n };\n }\n case n2.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType$2.DocumentType,\n name: n2.name,\n publicId: n2.publicId,\n systemId: n2.systemId,\n rootId\n };\n case n2.ELEMENT_NODE:\n return serializeElementNode(n2, {\n doc,\n blockClass,\n blockSelector,\n unblockSelector,\n inlineStylesheet,\n maskAttributeFn,\n maskInputOptions,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement,\n rootId,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n ignoreCSSAttributes\n });\n case n2.TEXT_NODE:\n return serializeTextNode(n2, {\n doc,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskTextFn,\n maskInputOptions,\n maskInputFn,\n rootId\n });\n case n2.CDATA_SECTION_NODE:\n return {\n type: NodeType$2.CDATA,\n textContent: \"\",\n rootId\n };\n case n2.COMMENT_NODE:\n return {\n type: NodeType$2.Comment,\n textContent: n2.textContent || \"\",\n rootId\n };\n default:\n return false;\n }\n}\nfunction getRootId(doc, mirror2) {\n if (!mirror2.hasNode(doc)) return void 0;\n const docId = mirror2.getId(doc);\n return docId === 1 ? void 0 : docId;\n}\nfunction serializeTextNode(n2, options) {\n const {\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskTextFn,\n maskInputOptions,\n maskInputFn,\n rootId\n } = options;\n const parentTagName = n2.parentNode && n2.parentNode.tagName;\n let textContent = n2.textContent;\n const isStyle = parentTagName === \"STYLE\" ? true : void 0;\n const isScript = parentTagName === \"SCRIPT\" ? true : void 0;\n const isTextarea = parentTagName === \"TEXTAREA\" ? true : void 0;\n if (isStyle && textContent) {\n try {\n if (n2.nextSibling || n2.previousSibling) {\n } else if (n2.parentNode.sheet?.cssRules) {\n textContent = stringifyStylesheet(\n n2.parentNode.sheet\n );\n }\n } catch (err) {\n console.warn(\n `Cannot get CSS styles from text's parentNode. Error: ${err}`,\n n2\n );\n }\n textContent = absoluteToStylesheet(textContent, getHref(options.doc));\n }\n if (isScript) {\n textContent = \"SCRIPT_PLACEHOLDER\";\n }\n const forceMask = needMaskingText(\n n2,\n maskTextClass,\n maskTextSelector,\n unmaskTextClass,\n unmaskTextSelector,\n maskAllText\n );\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\n textContent = maskTextFn ? maskTextFn(textContent, n2.parentElement) : textContent.replace(/[\\S]/g, \"*\");\n }\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\n textContent = maskInputFn ? maskInputFn(textContent, n2.parentNode) : textContent.replace(/[\\S]/g, \"*\");\n }\n if (parentTagName === \"OPTION\" && textContent) {\n const isInputMasked = shouldMaskInput({\n type: null,\n tagName: parentTagName,\n maskInputOptions\n });\n textContent = maskInputValue({\n isMasked: needMaskingText(\n n2,\n maskTextClass,\n maskTextSelector,\n unmaskTextClass,\n unmaskTextSelector,\n isInputMasked\n ),\n element: n2,\n value: textContent,\n maskInputFn\n });\n }\n return {\n type: NodeType$2.Text,\n textContent: textContent || \"\",\n isStyle,\n rootId\n };\n}\nfunction serializeElementNode(n2, options) {\n const {\n doc,\n blockClass,\n blockSelector,\n unblockSelector,\n inlineStylesheet,\n maskInputOptions = {},\n maskAttributeFn,\n maskInputFn,\n dataURLOptions = {},\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement = false,\n rootId,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n ignoreCSSAttributes\n } = options;\n const needBlock = _isBlockedElement(\n n2,\n blockClass,\n blockSelector,\n unblockSelector\n );\n const tagName = getValidTagName$1(n2);\n let attributes2 = {};\n const len = n2.attributes.length;\n for (let i2 = 0; i2 < len; i2++) {\n const attr = n2.attributes[i2];\n if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {\n attributes2[attr.name] = transformAttribute(\n doc,\n tagName,\n toLowerCase(attr.name),\n attr.value,\n n2,\n maskAttributeFn,\n ignoreCSSAttributes\n );\n }\n }\n if (tagName === \"link\" && inlineStylesheet) {\n const stylesheet = Array.from(doc.styleSheets).find((s2) => {\n return s2.href === n2.href;\n });\n let cssText = null;\n if (stylesheet) {\n cssText = stringifyStylesheet(stylesheet);\n }\n if (cssText) {\n attributes2.rel = null;\n attributes2.href = null;\n attributes2.crossorigin = null;\n attributes2._cssText = absoluteToStylesheet(cssText, stylesheet.href);\n }\n }\n if (tagName === \"style\" && n2.sheet && // TODO: Currently we only try to get dynamic stylesheet when it is an empty style element\n !(n2.innerText || n2.textContent || \"\").trim().length) {\n const cssText = stringifyStylesheet(\n n2.sheet\n );\n if (cssText) {\n attributes2._cssText = absoluteToStylesheet(cssText, getHref(doc));\n }\n }\n if (tagName === \"input\" || tagName === \"textarea\" || tagName === \"select\" || tagName === \"option\") {\n const el = n2;\n const type = getInputType(el);\n const value = getInputValue(el, toUpperCase(tagName), type);\n const checked = el.checked;\n if (type !== \"submit\" && type !== \"button\" && value) {\n const forceMask = needMaskingText(\n el,\n maskTextClass,\n maskTextSelector,\n unmaskTextClass,\n unmaskTextSelector,\n shouldMaskInput({\n type,\n tagName: toUpperCase(tagName),\n maskInputOptions\n })\n );\n attributes2.value = maskInputValue({\n isMasked: forceMask,\n element: el,\n value,\n maskInputFn\n });\n }\n if (checked) {\n attributes2.checked = checked;\n }\n }\n if (tagName === \"option\") {\n if (n2.selected && !maskInputOptions[\"select\"]) {\n attributes2.selected = true;\n } else {\n delete attributes2.selected;\n }\n }\n if (tagName === \"canvas\" && recordCanvas) {\n if (n2.__context === \"2d\") {\n if (!is2DCanvasBlank(n2)) {\n attributes2.rr_dataURL = n2.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n }\n } else if (!(\"__context\" in n2)) {\n const canvasDataURL = n2.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n const blankCanvas = doc.createElement(\"canvas\");\n blankCanvas.width = n2.width;\n blankCanvas.height = n2.height;\n const blankCanvasDataURL = blankCanvas.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes2.rr_dataURL = canvasDataURL;\n }\n }\n }\n if (tagName === \"img\" && inlineImages) {\n if (!canvasService) {\n canvasService = doc.createElement(\"canvas\");\n canvasCtx = canvasService.getContext(\"2d\");\n }\n const image = n2;\n const imageSrc = image.currentSrc || image.getAttribute(\"src\") || \"\";\n const priorCrossOrigin = image.crossOrigin;\n const recordInlineImage = () => {\n image.removeEventListener(\"load\", recordInlineImage);\n try {\n canvasService.width = image.naturalWidth;\n canvasService.height = image.naturalHeight;\n canvasCtx.drawImage(image, 0, 0);\n attributes2.rr_dataURL = canvasService.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n } catch (err) {\n if (image.crossOrigin !== \"anonymous\") {\n image.crossOrigin = \"anonymous\";\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else image.addEventListener(\"load\", recordInlineImage);\n return;\n } else {\n console.warn(\n `Cannot inline img src=${imageSrc}! Error: ${err}`\n );\n }\n }\n if (image.crossOrigin === \"anonymous\") {\n priorCrossOrigin ? attributes2.crossOrigin = priorCrossOrigin : image.removeAttribute(\"crossorigin\");\n }\n };\n if (image.complete && image.naturalWidth !== 0) recordInlineImage();\n else image.addEventListener(\"load\", recordInlineImage);\n }\n if (tagName === \"audio\" || tagName === \"video\") {\n attributes2.rr_mediaState = n2.paused ? \"paused\" : \"played\";\n attributes2.rr_mediaCurrentTime = n2.currentTime;\n }\n if (!newlyAddedElement) {\n if (n2.scrollLeft) {\n attributes2.rr_scrollLeft = n2.scrollLeft;\n }\n if (n2.scrollTop) {\n attributes2.rr_scrollTop = n2.scrollTop;\n }\n }\n if (needBlock) {\n const { width, height } = n2.getBoundingClientRect();\n attributes2 = {\n class: attributes2.class,\n rr_width: `${width}px`,\n rr_height: `${height}px`\n };\n }\n if (tagName === \"iframe\" && !keepIframeSrcFn(attributes2.src)) {\n if (!needBlock && !getIframeContentDocument(n2)) {\n attributes2.rr_src = attributes2.src;\n }\n delete attributes2.src;\n }\n let isCustomElement;\n try {\n if (customElements.get(tagName)) isCustomElement = true;\n } catch (e2) {\n }\n return {\n type: NodeType$2.Element,\n tagName,\n attributes: attributes2,\n childNodes: [],\n isSVG: isSVGElement(n2) || void 0,\n needBlock,\n rootId,\n isCustom: isCustomElement\n };\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === void 0 || maybeAttr === null) {\n return \"\";\n } else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType$2.Comment) {\n return true;\n } else if (sn.type === NodeType$2.Element) {\n if (slimDOMOptions.script && // script tag\n (sn.tagName === \"script\" || // (module)preload link\n sn.tagName === \"link\" && (sn.attributes.rel === \"preload\" || sn.attributes.rel === \"modulepreload\") || // prefetch link\n sn.tagName === \"link\" && sn.attributes.rel === \"prefetch\" && typeof sn.attributes.href === \"string\" && extractFileExtension(sn.attributes.href) === \"js\")) {\n return true;\n } else if (slimDOMOptions.headFavicon && (sn.tagName === \"link\" && sn.attributes.rel === \"shortcut icon\" || sn.tagName === \"meta\" && (lowerIfExists(sn.attributes.name).match(\n /^msapplication-tile(image|color)$/\n ) || lowerIfExists(sn.attributes.name) === \"application-name\" || lowerIfExists(sn.attributes.rel) === \"icon\" || lowerIfExists(sn.attributes.rel) === \"apple-touch-icon\" || lowerIfExists(sn.attributes.rel) === \"shortcut icon\"))) {\n return true;\n } else if (sn.tagName === \"meta\") {\n if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === \"pinterest\")) {\n return true;\n } else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === \"robots\" || lowerIfExists(sn.attributes.name) === \"googlebot\" || lowerIfExists(sn.attributes.name) === \"bingbot\")) {\n return true;\n } else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes[\"http-equiv\"] !== void 0) {\n return true;\n } else if (slimDOMOptions.headMetaAuthorship && (lowerIfExists(sn.attributes.name) === \"author\" || lowerIfExists(sn.attributes.name) === \"generator\" || lowerIfExists(sn.attributes.name) === \"framework\" || lowerIfExists(sn.attributes.name) === \"publisher\" || lowerIfExists(sn.attributes.name) === \"progid\" || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n } else if (slimDOMOptions.headMetaVerification && (lowerIfExists(sn.attributes.name) === \"google-site-verification\" || lowerIfExists(sn.attributes.name) === \"yandex-verification\" || lowerIfExists(sn.attributes.name) === \"csrf-token\" || lowerIfExists(sn.attributes.name) === \"p:domain_verify\" || lowerIfExists(sn.attributes.name) === \"verify-v1\" || lowerIfExists(sn.attributes.name) === \"verification\" || lowerIfExists(sn.attributes.name) === \"shopify-checkout-api-token\")) {\n return true;\n }\n }\n }\n return false;\n}\nfunction serializeNodeWithId(n2, options) {\n const {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild = false,\n inlineStylesheet = true,\n maskInputOptions = {},\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions = {},\n inlineImages = false,\n recordCanvas = false,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout = 5e3,\n onBlockedImageLoad,\n onStylesheetLoad,\n stylesheetLoadTimeout = 5e3,\n keepIframeSrcFn = () => false,\n newlyAddedElement = false,\n ignoreCSSAttributes\n } = options;\n let { preserveWhiteSpace = true } = options;\n const _serializedNode = serializeNode(n2, {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n maskAllText,\n unblockSelector,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement,\n ignoreCSSAttributes\n });\n if (!_serializedNode) {\n console.warn(n2, \"not serialized\");\n return null;\n }\n let id;\n if (mirror2.hasNode(n2)) {\n id = mirror2.getId(n2);\n } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType$2.Text && !_serializedNode.isStyle && !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, \"\").length) {\n id = IGNORED_NODE;\n } else {\n id = genId();\n }\n const serializedNode2 = Object.assign(_serializedNode, { id });\n mirror2.add(n2, serializedNode2);\n if (id === IGNORED_NODE) {\n return null;\n }\n if (onSerialize) {\n onSerialize(n2);\n }\n let recordChild = !skipChild;\n if (serializedNode2.type === NodeType$2.Element) {\n recordChild = recordChild && !serializedNode2.needBlock;\n const shadowRoot = n2.shadowRoot;\n if (shadowRoot && isNativeShadowDom(shadowRoot))\n serializedNode2.isShadowHost = true;\n }\n if ((serializedNode2.type === NodeType$2.Document || serializedNode2.type === NodeType$2.Element) && recordChild) {\n if (slimDOMOptions.headWhitespace && serializedNode2.type === NodeType$2.Element && serializedNode2.tagName === \"head\") {\n preserveWhiteSpace = false;\n }\n const bypassOptions = {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n maskAllText,\n unblockSelector,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onBlockedImageLoad,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n ignoreCSSAttributes\n };\n const childNodes = n2.childNodes ? Array.from(n2.childNodes) : [];\n for (const childN of childNodes) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode2.childNodes.push(serializedChildNode);\n }\n }\n if (isElement(n2) && n2.shadowRoot) {\n for (const childN of Array.from(n2.shadowRoot.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n isNativeShadowDom(n2.shadowRoot) && (serializedChildNode.isShadow = true);\n serializedNode2.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n if (n2.parentNode && isShadowRoot(n2.parentNode) && isNativeShadowDom(n2.parentNode)) {\n serializedNode2.isShadow = true;\n }\n if (serializedNode2.type === NodeType$2.Element && serializedNode2.tagName === \"iframe\" && !serializedNode2.needBlock) {\n onceIframeLoaded(\n n2,\n () => {\n const iframeDoc = getIframeContentDocument(n2);\n if (iframeDoc && onIframeLoad) {\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n doc: iframeDoc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n ignoreCSSAttributes\n });\n if (serializedIframeNode) {\n onIframeLoad(\n n2,\n serializedIframeNode\n );\n }\n }\n },\n iframeLoadTimeout\n );\n }\n if (serializedNode2.type === NodeType$2.Element && serializedNode2.tagName === \"img\" && !n2.complete && serializedNode2.needBlock) {\n const image = n2;\n const updateImageDimensions = () => {\n if (image.isConnected && !image.complete && onBlockedImageLoad) {\n try {\n const rect = image.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) {\n onBlockedImageLoad(image, serializedNode2, rect);\n }\n } catch (error) {\n }\n }\n image.removeEventListener(\"load\", updateImageDimensions);\n };\n if (image.isConnected) {\n image.addEventListener(\"load\", updateImageDimensions);\n }\n }\n if (serializedNode2.type === NodeType$2.Element && serializedNode2.tagName === \"link\" && typeof serializedNode2.attributes.rel === \"string\" && (serializedNode2.attributes.rel === \"stylesheet\" || serializedNode2.attributes.rel === \"preload\" && typeof serializedNode2.attributes.href === \"string\" && extractFileExtension(serializedNode2.attributes.href) === \"css\")) {\n onceStylesheetLoaded(\n n2,\n () => {\n if (onStylesheetLoad) {\n const serializedLinkNode = serializeNodeWithId(n2, {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n ignoreCSSAttributes\n });\n if (serializedLinkNode) {\n onStylesheetLoad(\n n2,\n serializedLinkNode\n );\n }\n }\n },\n stylesheetLoadTimeout\n );\n }\n if (serializedNode2.type === NodeType$2.Element) {\n delete serializedNode2.needBlock;\n }\n return serializedNode2;\n}\nfunction snapshot(n2, options) {\n const {\n mirror: mirror2 = new Mirror(),\n blockClass = \"rr-block\",\n blockSelector = null,\n unblockSelector = null,\n maskAllText = false,\n maskTextClass = \"rr-mask\",\n unmaskTextClass = null,\n maskTextSelector = null,\n unmaskTextSelector = null,\n inlineStylesheet = true,\n inlineImages = false,\n recordCanvas = false,\n maskAllInputs = false,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOM = false,\n dataURLOptions,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onBlockedImageLoad,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn = () => false,\n ignoreCSSAttributes = /* @__PURE__ */ new Set([])\n } = options || {};\n const maskInputOptions = maskAllInputs === true ? {\n color: true,\n date: true,\n \"datetime-local\": true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true\n } : maskAllInputs === false ? {} : maskAllInputs;\n const slimDOMOptions = slimDOM === true || slimDOM === \"all\" ? (\n // if true: set of sensible options that should not throw away any information\n {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaDescKeywords: slimDOM === \"all\",\n // destructive\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaAuthorship: true,\n headMetaVerification: true\n }\n ) : slimDOM === false ? {} : slimDOM;\n return serializeNodeWithId(n2, {\n doc: n2,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onBlockedImageLoad,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n newlyAddedElement: false,\n ignoreCSSAttributes\n });\n}\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\nfunction parse(css, options = {}) {\n let lineno = 1;\n let column = 1;\n function updatePosition(str) {\n const lines = str.match(/\\n/g);\n if (lines) {\n lineno += lines.length;\n }\n const i2 = str.lastIndexOf(\"\\n\");\n column = i2 === -1 ? column + str.length : str.length - i2;\n }\n function position() {\n const start = { line: lineno, column };\n return (node) => {\n node.position = new Position(start);\n whitespace();\n return node;\n };\n }\n const _Position = class _Position2 {\n constructor(start) {\n __publicField$1(this, \"content\");\n __publicField$1(this, \"start\");\n __publicField$1(this, \"end\");\n __publicField$1(this, \"source\");\n this.start = start;\n this.end = { line: lineno, column };\n this.source = options.source;\n this.content = _Position2.content;\n }\n };\n __publicField$1(_Position, \"content\");\n let Position = _Position;\n Position.content = css;\n const errorsList = [];\n function error(msg) {\n const err = new Error(\n `${options.source || \"\"}:${lineno}:${column}: ${msg}`\n );\n err.reason = msg;\n err.filename = options.source;\n err.line = lineno;\n err.column = column;\n err.source = css;\n if (options.silent) {\n errorsList.push(err);\n } else {\n throw err;\n }\n }\n function stylesheet() {\n const rulesList = rules2();\n return {\n type: \"stylesheet\",\n stylesheet: {\n source: options.source,\n rules: rulesList,\n parsingErrors: errorsList\n }\n };\n }\n function open() {\n return match(/^{\\s*/);\n }\n function close() {\n return match(/^}/);\n }\n function rules2() {\n let node;\n const rules22 = [];\n whitespace();\n comments(rules22);\n while (css.length && css.charAt(0) !== \"}\" && (node = atrule() || rule())) {\n if (node) {\n rules22.push(node);\n comments(rules22);\n }\n }\n return rules22;\n }\n function match(re) {\n const m = re.exec(css);\n if (!m) {\n return;\n }\n const str = m[0];\n updatePosition(str);\n css = css.slice(str.length);\n return m;\n }\n function whitespace() {\n match(/^\\s*/);\n }\n function comments(rules22 = []) {\n let c2;\n while (c2 = comment()) {\n if (c2) {\n rules22.push(c2);\n }\n c2 = comment();\n }\n return rules22;\n }\n function comment() {\n const pos = position();\n if (\"/\" !== css.charAt(0) || \"*\" !== css.charAt(1)) {\n return;\n }\n let i2 = 2;\n while (\"\" !== css.charAt(i2) && (\"*\" !== css.charAt(i2) || \"/\" !== css.charAt(i2 + 1))) {\n ++i2;\n }\n i2 += 2;\n if (\"\" === css.charAt(i2 - 1)) {\n return error(\"End of comment missing\");\n }\n const str = css.slice(2, i2 - 2);\n column += 2;\n updatePosition(str);\n css = css.slice(i2);\n column += 2;\n return pos({\n type: \"comment\",\n comment: str\n });\n }\n function selector() {\n const m = match(/^([^{]+)/);\n if (!m) {\n return;\n }\n const splitSelectors = trim(m[0]).replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, \"\").replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m2) => {\n return m2.replace(/,/g, \"‌\");\n }).split(/\\s*(?![^(]*\\)),\\s*/);\n if (splitSelectors.length <= 1) {\n return splitSelectors.map((s2) => {\n return s2.replace(/\\u200C/g, \",\");\n });\n }\n let i2 = 0;\n let j = 0;\n const len = splitSelectors.length;\n const finalSelectors = [];\n while (i2 < len) {\n const openingParensCount = (splitSelectors[i2].match(/\\(/g) || []).length;\n const closingParensCount = (splitSelectors[i2].match(/\\)/g) || []).length;\n let unbalancedParens = openingParensCount - closingParensCount;\n if (unbalancedParens >= 1) {\n let foundClosingSelector = false;\n j = i2 + 1;\n while (j < len) {\n const nextOpeningParensCount = (splitSelectors[j].match(/\\(/g) || []).length;\n const nextClosingParensCount = (splitSelectors[j].match(/\\)/g) || []).length;\n const nextUnbalancedParens = nextClosingParensCount - nextOpeningParensCount;\n if (nextUnbalancedParens === unbalancedParens) {\n finalSelectors.push(splitSelectors.slice(i2, j + 1).join(\",\"));\n i2 = j + 1;\n foundClosingSelector = true;\n break;\n }\n j++;\n unbalancedParens -= nextUnbalancedParens;\n }\n if (foundClosingSelector) {\n continue;\n }\n splitSelectors.slice(i2, len).forEach((selector2) => selector2 && finalSelectors.push(selector2));\n break;\n }\n splitSelectors[i2] && finalSelectors.push(splitSelectors[i2]);\n i2++;\n }\n return finalSelectors.map((s2) => {\n return s2.replace(/\\u200C/g, \",\");\n });\n }\n function declaration() {\n const pos = position();\n const propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\n if (!propMatch) {\n return;\n }\n const prop = trim(propMatch[0]);\n if (!match(/^:\\s*/)) {\n return error(`property missing ':'`);\n }\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\n const ret = pos({\n type: \"declaration\",\n property: prop.replace(commentre, \"\"),\n value: val ? trim(val[0]).replace(commentre, \"\") : \"\"\n });\n match(/^[;\\s]*/);\n return ret;\n }\n function declarations() {\n const decls = [];\n if (!open()) {\n return error(`missing '{'`);\n }\n comments(decls);\n let decl;\n while (decl = declaration()) {\n if (decl !== false) {\n decls.push(decl);\n comments(decls);\n }\n decl = declaration();\n }\n if (!close()) {\n return error(`missing '}'`);\n }\n return decls;\n }\n function keyframe() {\n let m;\n const vals = [];\n const pos = position();\n while (m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/)) {\n vals.push(m[1]);\n match(/^,\\s*/);\n }\n if (!vals.length) {\n return;\n }\n return pos({\n type: \"keyframe\",\n values: vals,\n declarations: declarations()\n });\n }\n function atkeyframes() {\n const pos = position();\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\n if (!m) {\n return;\n }\n const vendor = m[1];\n m = match(/^([-\\w]+)\\s*/);\n if (!m) {\n return error(\"@keyframes missing name\");\n }\n const name = m[1];\n if (!open()) {\n return error(`@keyframes missing '{'`);\n }\n let frame;\n let frames = comments();\n while (frame = keyframe()) {\n frames.push(frame);\n frames = frames.concat(comments());\n }\n if (!close()) {\n return error(`@keyframes missing '}'`);\n }\n return pos({\n type: \"keyframes\",\n name,\n vendor,\n keyframes: frames\n });\n }\n function atsupports() {\n const pos = position();\n const m = match(/^@supports *([^{]+)/);\n if (!m) {\n return;\n }\n const supports = trim(m[1]);\n if (!open()) {\n return error(`@supports missing '{'`);\n }\n const style = comments().concat(rules2());\n if (!close()) {\n return error(`@supports missing '}'`);\n }\n return pos({\n type: \"supports\",\n supports,\n rules: style\n });\n }\n function athost() {\n const pos = position();\n const m = match(/^@host\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(`@host missing '{'`);\n }\n const style = comments().concat(rules2());\n if (!close()) {\n return error(`@host missing '}'`);\n }\n return pos({\n type: \"host\",\n rules: style\n });\n }\n function atmedia() {\n const pos = position();\n const m = match(/^@media *([^{]+)/);\n if (!m) {\n return;\n }\n const media = trim(m[1]);\n if (!open()) {\n return error(`@media missing '{'`);\n }\n const style = comments().concat(rules2());\n if (!close()) {\n return error(`@media missing '}'`);\n }\n return pos({\n type: \"media\",\n media,\n rules: style\n });\n }\n function atcustommedia() {\n const pos = position();\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\n if (!m) {\n return;\n }\n return pos({\n type: \"custom-media\",\n name: trim(m[1]),\n media: trim(m[2])\n });\n }\n function atpage() {\n const pos = position();\n const m = match(/^@page */);\n if (!m) {\n return;\n }\n const sel = selector() || [];\n if (!open()) {\n return error(`@page missing '{'`);\n }\n let decls = comments();\n let decl;\n while (decl = declaration()) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(`@page missing '}'`);\n }\n return pos({\n type: \"page\",\n selectors: sel,\n declarations: decls\n });\n }\n function atdocument() {\n const pos = position();\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\n if (!m) {\n return;\n }\n const vendor = trim(m[1]);\n const doc = trim(m[2]);\n if (!open()) {\n return error(`@document missing '{'`);\n }\n const style = comments().concat(rules2());\n if (!close()) {\n return error(`@document missing '}'`);\n }\n return pos({\n type: \"document\",\n document: doc,\n vendor,\n rules: style\n });\n }\n function atfontface() {\n const pos = position();\n const m = match(/^@font-face\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(`@font-face missing '{'`);\n }\n let decls = comments();\n let decl;\n while (decl = declaration()) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(`@font-face missing '}'`);\n }\n return pos({\n type: \"font-face\",\n declarations: decls\n });\n }\n const atimport = _compileAtrule(\"import\");\n const atcharset = _compileAtrule(\"charset\");\n const atnamespace = _compileAtrule(\"namespace\");\n function _compileAtrule(name) {\n const re = new RegExp(\n \"^@\" + name + \"\\\\s*((?:\" + [\n /[^\\\\]\"(?:\\\\\"|[^\"])*\"/.source,\n // consume any quoted parts (checking that the double quote isn't itself escaped)\n /[^\\\\]'(?:\\\\'|[^'])*'/.source,\n // same but for single quotes\n \"[^;]\"\n ].join(\"|\") + \")+);\"\n );\n return () => {\n const pos = position();\n const m = match(re);\n if (!m) {\n return;\n }\n const ret = { type: name };\n ret[name] = m[1].trim();\n return pos(ret);\n };\n }\n function atrule() {\n if (css[0] !== \"@\") {\n return;\n }\n return atkeyframes() || atmedia() || atcustommedia() || atsupports() || atimport() || atcharset() || atnamespace() || atdocument() || atpage() || athost() || atfontface();\n }\n function rule() {\n const pos = position();\n const sel = selector();\n if (!sel) {\n return error(\"selector missing\");\n }\n comments();\n return pos({\n type: \"rule\",\n selectors: sel,\n declarations: declarations()\n });\n }\n return addParent(stylesheet());\n}\nfunction trim(str) {\n return str ? str.replace(/^\\s+|\\s+$/g, \"\") : \"\";\n}\nfunction addParent(obj, parent) {\n const isNode = obj && typeof obj.type === \"string\";\n const childParent = isNode ? obj : parent;\n for (const k of Object.keys(obj)) {\n const value = obj[k];\n if (Array.isArray(value)) {\n value.forEach((v2) => {\n addParent(v2, childParent);\n });\n } else if (value && typeof value === \"object\") {\n addParent(value, childParent);\n }\n }\n if (isNode) {\n Object.defineProperty(obj, \"parent\", {\n configurable: true,\n writable: true,\n enumerable: false,\n value: parent || null\n });\n }\n return obj;\n}\nconst tagMap = {\n script: \"noscript\",\n // camel case svg element tag names\n altglyph: \"altGlyph\",\n altglyphdef: \"altGlyphDef\",\n altglyphitem: \"altGlyphItem\",\n animatecolor: \"animateColor\",\n animatemotion: \"animateMotion\",\n animatetransform: \"animateTransform\",\n clippath: \"clipPath\",\n feblend: \"feBlend\",\n fecolormatrix: \"feColorMatrix\",\n fecomponenttransfer: \"feComponentTransfer\",\n fecomposite: \"feComposite\",\n feconvolvematrix: \"feConvolveMatrix\",\n fediffuselighting: \"feDiffuseLighting\",\n fedisplacementmap: \"feDisplacementMap\",\n fedistantlight: \"feDistantLight\",\n fedropshadow: \"feDropShadow\",\n feflood: \"feFlood\",\n fefunca: \"feFuncA\",\n fefuncb: \"feFuncB\",\n fefuncg: \"feFuncG\",\n fefuncr: \"feFuncR\",\n fegaussianblur: \"feGaussianBlur\",\n feimage: \"feImage\",\n femerge: \"feMerge\",\n femergenode: \"feMergeNode\",\n femorphology: \"feMorphology\",\n feoffset: \"feOffset\",\n fepointlight: \"fePointLight\",\n fespecularlighting: \"feSpecularLighting\",\n fespotlight: \"feSpotLight\",\n fetile: \"feTile\",\n feturbulence: \"feTurbulence\",\n foreignobject: \"foreignObject\",\n glyphref: \"glyphRef\",\n lineargradient: \"linearGradient\",\n radialgradient: \"radialGradient\"\n};\nfunction getTagName(n2) {\n let tagName = tagMap[n2.tagName] ? tagMap[n2.tagName] : n2.tagName;\n if (tagName === \"link\" && n2.attributes._cssText) {\n tagName = \"style\";\n }\n return tagName;\n}\nfunction escapeRegExp(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, \"g\");\nfunction addHoverClass(cssText, cache) {\n const cachedStyle = cache?.stylesWithHoverClass.get(cssText);\n if (cachedStyle) return cachedStyle;\n if (cssText.length >= 1e6) {\n return cssText;\n }\n const ast = parse(cssText, {\n silent: true\n });\n if (!ast.stylesheet) {\n return cssText;\n }\n const selectors = [];\n ast.stylesheet.rules.forEach((rule) => {\n if (\"selectors\" in rule) {\n (rule.selectors || []).forEach((selector) => {\n if (HOVER_SELECTOR.test(selector)) {\n selectors.push(selector);\n }\n });\n }\n });\n if (selectors.length === 0) {\n return cssText;\n }\n const selectorMatcher = new RegExp(\n selectors.filter((selector, index) => selectors.indexOf(selector) === index).sort((a2, b) => b.length - a2.length).map((selector) => {\n return escapeRegExp(selector);\n }).join(\"|\"),\n \"g\"\n );\n const result = cssText.replace(selectorMatcher, (selector) => {\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, \"$1.\\\\:hover\");\n return `${selector}, ${newSelector}`;\n });\n cache?.stylesWithHoverClass.set(cssText, result);\n return result;\n}\nfunction createCache() {\n const stylesWithHoverClass = /* @__PURE__ */ new Map();\n return {\n stylesWithHoverClass\n };\n}\nfunction buildNode(n2, options) {\n const { doc, hackCss, cache } = options;\n switch (n2.type) {\n case NodeType$2.Document:\n return doc.implementation.createDocument(null, \"\", null);\n case NodeType$2.DocumentType:\n return doc.implementation.createDocumentType(\n n2.name || \"html\",\n n2.publicId,\n n2.systemId\n );\n case NodeType$2.Element: {\n const tagName = getTagName(n2);\n let node;\n if (n2.isSVG) {\n node = doc.createElementNS(\"http://www.w3.org/2000/svg\", tagName);\n } else {\n if (\n // If the tag name is a custom element name\n n2.isCustom && // If the browser supports custom elements\n doc.defaultView?.customElements && // If the custom element hasn't been defined yet\n !doc.defaultView.customElements.get(n2.tagName)\n )\n doc.defaultView.customElements.define(\n n2.tagName,\n class extends doc.defaultView.HTMLElement {\n }\n );\n node = doc.createElement(tagName);\n }\n const specialAttributes = {};\n for (const name in n2.attributes) {\n if (!Object.prototype.hasOwnProperty.call(n2.attributes, name)) {\n continue;\n }\n let value = n2.attributes[name];\n if (tagName === \"option\" && name === \"selected\" && value === false) {\n continue;\n }\n if (value === null) {\n continue;\n }\n if (value === true) value = \"\";\n if (name.startsWith(\"rr_\")) {\n specialAttributes[name] = value;\n continue;\n }\n const isTextarea = tagName === \"textarea\" && name === \"value\";\n const isRemoteOrDynamicCss = tagName === \"style\" && name === \"_cssText\";\n if (isRemoteOrDynamicCss && hackCss && typeof value === \"string\") {\n value = addHoverClass(value, cache);\n }\n if ((isTextarea || isRemoteOrDynamicCss) && typeof value === \"string\") {\n const child = doc.createTextNode(value);\n for (const c2 of Array.from(node.childNodes)) {\n if (c2.nodeType === node.TEXT_NODE) {\n node.removeChild(c2);\n }\n }\n node.appendChild(child);\n continue;\n }\n try {\n if (n2.isSVG && name === \"xlink:href\") {\n node.setAttributeNS(\n \"http://www.w3.org/1999/xlink\",\n name,\n value.toString()\n );\n } else if (name === \"onload\" || name === \"onclick\" || name.substring(0, 7) === \"onmouse\") {\n node.setAttribute(\"_\" + name, value.toString());\n } else if (tagName === \"meta\" && n2.attributes[\"http-equiv\"] === \"Content-Security-Policy\" && name === \"content\") {\n node.setAttribute(\"csp-content\", value.toString());\n continue;\n } else if (tagName === \"link\" && (n2.attributes.rel === \"preload\" || n2.attributes.rel === \"modulepreload\")) {\n } else if (tagName === \"link\" && n2.attributes.rel === \"prefetch\" && typeof n2.attributes.href === \"string\" && extractFileExtension(n2.attributes.href) === \"js\") {\n } else if (tagName === \"img\" && n2.attributes.srcset && n2.attributes.rr_dataURL) {\n node.setAttribute(\n \"rrweb-original-srcset\",\n n2.attributes.srcset\n );\n } else {\n node.setAttribute(name, value.toString());\n }\n } catch (error) {\n }\n }\n for (const name in specialAttributes) {\n const value = specialAttributes[name];\n if (tagName === \"canvas\" && name === \"rr_dataURL\") {\n const image = doc.createElement(\"img\");\n image.onload = () => {\n const ctx = node.getContext(\"2d\");\n if (ctx) {\n ctx.drawImage(image, 0, 0, image.width, image.height);\n }\n };\n image.src = value.toString();\n if (node.RRNodeType)\n node.rr_dataURL = value.toString();\n } else if (tagName === \"img\" && name === \"rr_dataURL\") {\n const image = node;\n if (!image.currentSrc.startsWith(\"data:\")) {\n image.setAttribute(\n \"rrweb-original-src\",\n n2.attributes.src\n );\n image.src = value.toString();\n }\n }\n if (name === \"rr_width\") {\n node.style.setProperty(\"width\", value.toString());\n } else if (name === \"rr_height\") {\n node.style.setProperty(\"height\", value.toString());\n } else if (name === \"rr_mediaCurrentTime\" && typeof value === \"number\") {\n node.currentTime = value;\n } else if (name === \"rr_mediaState\") {\n switch (value) {\n case \"played\":\n node.play().catch((e2) => console.warn(\"media playback error\", e2));\n break;\n case \"paused\":\n node.pause();\n break;\n }\n }\n }\n if (n2.isShadowHost) {\n if (!node.shadowRoot) {\n node.attachShadow({ mode: \"open\" });\n } else {\n while (node.shadowRoot.firstChild) {\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\n }\n }\n }\n return node;\n }\n case NodeType$2.Text:\n return doc.createTextNode(\n n2.isStyle && hackCss ? addHoverClass(n2.textContent, cache) : n2.textContent\n );\n case NodeType$2.CDATA:\n if (!(doc instanceof XMLDocument)) {\n return null;\n }\n return doc.createCDATASection(n2.textContent);\n case NodeType$2.Comment:\n return doc.createComment(n2.textContent);\n default:\n return null;\n }\n}\nfunction buildNodeWithSN(n2, options) {\n const {\n doc,\n mirror: mirror2,\n skipChild = false,\n hackCss = true,\n afterAppend,\n cache\n } = options;\n if (mirror2.has(n2.id)) {\n const nodeInMirror = mirror2.getNode(n2.id);\n const meta = mirror2.getMeta(nodeInMirror);\n if (isNodeMetaEqual(meta, n2)) return mirror2.getNode(n2.id);\n }\n let node = buildNode(n2, { doc, hackCss, cache });\n if (!node) {\n return null;\n }\n if (n2.rootId && mirror2.getNode(n2.rootId) !== doc) {\n mirror2.replace(n2.rootId, doc);\n }\n if (n2.type === NodeType$2.Document) {\n doc.close();\n doc.open();\n if (n2.compatMode === \"BackCompat\" && n2.childNodes && n2.childNodes[0].type !== NodeType$2.DocumentType) {\n if (n2.childNodes[0].type === NodeType$2.Element && \"xmlns\" in n2.childNodes[0].attributes && n2.childNodes[0].attributes.xmlns === \"http://www.w3.org/1999/xhtml\") {\n doc.write(\n ''\n );\n } else {\n doc.write(\n ''\n );\n }\n }\n node = doc;\n }\n mirror2.add(node, n2);\n if ((n2.type === NodeType$2.Document || n2.type === NodeType$2.Element) && !skipChild) {\n for (const childN of n2.childNodes) {\n const childNode = buildNodeWithSN(childN, {\n doc,\n mirror: mirror2,\n skipChild: false,\n hackCss,\n afterAppend,\n cache\n });\n if (!childNode) {\n console.warn(\"Failed to rebuild\", childN);\n continue;\n }\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\n node.shadowRoot.appendChild(childNode);\n } else if (n2.type === NodeType$2.Document && childN.type == NodeType$2.Element) {\n const htmlElement = childNode;\n let body = null;\n htmlElement.childNodes.forEach((child) => {\n if (child.nodeName === \"BODY\") body = child;\n });\n if (body) {\n htmlElement.removeChild(body);\n node.appendChild(childNode);\n htmlElement.appendChild(body);\n } else {\n node.appendChild(childNode);\n }\n } else {\n node.appendChild(childNode);\n }\n if (afterAppend) {\n afterAppend(childNode, childN.id);\n }\n }\n }\n return node;\n}\nfunction visit(mirror2, onVisit) {\n function walk(node) {\n onVisit(node);\n }\n for (const id of mirror2.getIds()) {\n if (mirror2.has(id)) {\n walk(mirror2.getNode(id));\n }\n }\n}\nfunction handleScroll(node, mirror2) {\n const n2 = mirror2.getMeta(node);\n if (n2?.type !== NodeType$2.Element) {\n return;\n }\n const el = node;\n for (const name in n2.attributes) {\n if (!(Object.prototype.hasOwnProperty.call(n2.attributes, name) && name.startsWith(\"rr_\"))) {\n continue;\n }\n const value = n2.attributes[name];\n if (name === \"rr_scrollLeft\") {\n el.scrollLeft = value;\n }\n if (name === \"rr_scrollTop\") {\n el.scrollTop = value;\n }\n }\n}\nfunction rebuild(n2, options) {\n const {\n doc,\n onVisit,\n hackCss = true,\n afterAppend,\n cache,\n mirror: mirror2 = new Mirror()\n } = options;\n const node = buildNodeWithSN(n2, {\n doc,\n mirror: mirror2,\n skipChild: false,\n hackCss,\n afterAppend,\n cache\n });\n visit(mirror2, (visitedNode) => {\n if (onVisit) {\n onVisit(visitedNode);\n }\n handleScroll(visitedNode, mirror2);\n });\n return node;\n}\nfunction on(type, fn, target = document) {\n const options = { capture: true, passive: true };\n target.addEventListener(type, fn, options);\n return () => target.removeEventListener(type, fn, options);\n}\nconst DEPARTED_MIRROR_ACCESS_WARNING = \"Please stop import mirror directly. Instead of that,\\r\\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\\r\\nor you can use record.mirror to access the mirror instance during recording.\";\nlet _mirror = {\n map: {},\n getId() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return -1;\n },\n getNode() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return null;\n },\n removeNodeFromMap() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n has() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return false;\n },\n reset() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n};\nif (typeof window !== \"undefined\" && window.Proxy && window.Reflect) {\n _mirror = new Proxy(_mirror, {\n get(target, prop, receiver) {\n if (prop === \"map\") {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n return Reflect.get(target, prop, receiver);\n }\n });\n}\nfunction throttle(func, wait, options = {}) {\n let timeout = null;\n let previous = 0;\n return function(...args) {\n const now = Date.now();\n if (!previous && options.leading === false) {\n previous = now;\n }\n const remaining = wait - (now - previous);\n const context = this;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n previous = now;\n func.apply(context, args);\n } else if (!timeout && options.trailing !== false) {\n timeout = setTimeout$1(() => {\n previous = options.leading === false ? 0 : Date.now();\n timeout = null;\n func.apply(context, args);\n }, remaining);\n }\n };\n}\nfunction hookSetter(target, key, d, isRevoked, win = window) {\n const original = win.Object.getOwnPropertyDescriptor(target, key);\n win.Object.defineProperty(\n target,\n key,\n isRevoked ? d : {\n set(value) {\n setTimeout$1(() => {\n d.set.call(this, value);\n }, 0);\n if (original && original.set) {\n original.set.call(this, value);\n }\n }\n }\n );\n return () => hookSetter(target, key, original || {}, true);\n}\nfunction patch(source, name, replacement) {\n try {\n if (!(name in source)) {\n return () => {\n };\n }\n const original = source[name];\n const wrapped = replacement(original);\n if (typeof wrapped === \"function\") {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __rrweb_original__: {\n enumerable: false,\n value: original\n }\n });\n }\n source[name] = wrapped;\n return () => {\n source[name] = original;\n };\n } catch {\n return () => {\n };\n }\n}\nlet nowTimestamp = Date.now;\nif (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())) {\n nowTimestamp = () => (/* @__PURE__ */ new Date()).getTime();\n}\nfunction getWindowScroll(win) {\n const doc = win.document;\n return {\n left: doc.scrollingElement ? doc.scrollingElement.scrollLeft : win.pageXOffset !== void 0 ? win.pageXOffset : doc?.documentElement.scrollLeft || doc?.body?.parentElement?.scrollLeft || doc?.body?.scrollLeft || 0,\n top: doc.scrollingElement ? doc.scrollingElement.scrollTop : win.pageYOffset !== void 0 ? win.pageYOffset : doc?.documentElement.scrollTop || doc?.body?.parentElement?.scrollTop || doc?.body?.scrollTop || 0\n };\n}\nfunction getWindowHeight() {\n return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;\n}\nfunction getWindowWidth() {\n return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;\n}\nfunction closestElementOfNode(node) {\n if (!node) {\n return null;\n }\n try {\n const el = node.nodeType === node.ELEMENT_NODE ? node : node.parentElement;\n return el;\n } catch (error) {\n return null;\n }\n}\nfunction isBlocked(node, blockClass, blockSelector, unblockSelector, checkAncestors) {\n if (!node) {\n return false;\n }\n const el = closestElementOfNode(node);\n if (!el) {\n return false;\n }\n const blockedPredicate = createMatchPredicate(blockClass, blockSelector);\n if (!checkAncestors) {\n const isUnblocked = unblockSelector && el.matches(unblockSelector);\n return blockedPredicate(el) && !isUnblocked;\n }\n const blockDistance = distanceToMatch(el, blockedPredicate);\n let unblockDistance = -1;\n if (blockDistance < 0) {\n return false;\n }\n if (unblockSelector) {\n unblockDistance = distanceToMatch(\n el,\n createMatchPredicate(null, unblockSelector)\n );\n }\n if (blockDistance > -1 && unblockDistance < 0) {\n return true;\n }\n return blockDistance < unblockDistance;\n}\nfunction isSerialized(n2, mirror2) {\n return mirror2.getId(n2) !== -1;\n}\nfunction isIgnored(n2, mirror2) {\n return mirror2.getId(n2) === IGNORED_NODE;\n}\nfunction isAncestorRemoved(target, mirror2) {\n if (isShadowRoot(target)) {\n return false;\n }\n const id = mirror2.getId(target);\n if (!mirror2.has(id)) {\n return true;\n }\n if (target.parentNode && target.parentNode.nodeType === target.DOCUMENT_NODE) {\n return false;\n }\n if (!target.parentNode) {\n return true;\n }\n return isAncestorRemoved(target.parentNode, mirror2);\n}\nfunction legacy_isTouchEvent(event) {\n return Boolean(event.changedTouches);\n}\nfunction polyfill$1(win = window) {\n if (\"NodeList\" in win && !win.NodeList.prototype.forEach) {\n win.NodeList.prototype.forEach = Array.prototype.forEach;\n }\n if (\"DOMTokenList\" in win && !win.DOMTokenList.prototype.forEach) {\n win.DOMTokenList.prototype.forEach = Array.prototype.forEach;\n }\n if (!Node.prototype.contains) {\n Node.prototype.contains = (...args) => {\n let node = args[0];\n if (!(0 in args)) {\n throw new TypeError(\"1 argument is required\");\n }\n do {\n if (this === node) {\n return true;\n }\n } while (node = node && node.parentNode);\n return false;\n };\n }\n}\nfunction queueToResolveTrees(queue) {\n const queueNodeMap = {};\n const putIntoMap = (m, parent) => {\n const nodeInTree = {\n value: m,\n parent,\n children: []\n };\n queueNodeMap[m.node.id] = nodeInTree;\n return nodeInTree;\n };\n const queueNodeTrees = [];\n for (const mutation of queue) {\n const { nextId, parentId } = mutation;\n if (nextId && nextId in queueNodeMap) {\n const nextInTree = queueNodeMap[nextId];\n if (nextInTree.parent) {\n const idx = nextInTree.parent.children.indexOf(nextInTree);\n nextInTree.parent.children.splice(\n idx,\n 0,\n putIntoMap(mutation, nextInTree.parent)\n );\n } else {\n const idx = queueNodeTrees.indexOf(nextInTree);\n queueNodeTrees.splice(idx, 0, putIntoMap(mutation, null));\n }\n continue;\n }\n if (parentId in queueNodeMap) {\n const parentInTree = queueNodeMap[parentId];\n parentInTree.children.push(putIntoMap(mutation, parentInTree));\n continue;\n }\n queueNodeTrees.push(putIntoMap(mutation, null));\n }\n return queueNodeTrees;\n}\nfunction iterateResolveTree(tree, cb) {\n cb(tree.value);\n for (let i2 = tree.children.length - 1; i2 >= 0; i2--) {\n iterateResolveTree(tree.children[i2], cb);\n }\n}\nfunction isSerializedIframe(n2, mirror2) {\n return Boolean(n2.nodeName === \"IFRAME\" && mirror2.getMeta(n2));\n}\nfunction isSerializedStylesheet(n2, mirror2) {\n return Boolean(\n n2.nodeName === \"LINK\" && n2.nodeType === n2.ELEMENT_NODE && n2.getAttribute && n2.getAttribute(\"rel\") === \"stylesheet\" && mirror2.getMeta(n2)\n );\n}\nfunction getBaseDimension(node, rootIframe) {\n const frameElement = node.ownerDocument?.defaultView?.frameElement;\n if (!frameElement || frameElement === rootIframe) {\n return {\n x: 0,\n y: 0,\n relativeScale: 1,\n absoluteScale: 1\n };\n }\n const frameDimension = frameElement.getBoundingClientRect();\n const frameBaseDimension = getBaseDimension(frameElement, rootIframe);\n const relativeScale = frameDimension.height / frameElement.clientHeight;\n return {\n x: frameDimension.x * frameBaseDimension.relativeScale + frameBaseDimension.x,\n y: frameDimension.y * frameBaseDimension.relativeScale + frameBaseDimension.y,\n relativeScale,\n absoluteScale: frameBaseDimension.absoluteScale * relativeScale\n };\n}\nfunction hasShadowRoot(n2) {\n return Boolean(n2?.shadowRoot);\n}\nfunction getNestedRule(rules2, position) {\n const rule = rules2[position[0]];\n if (position.length === 1) {\n return rule;\n } else {\n return getNestedRule(\n rule.cssRules[position[1]].cssRules,\n position.slice(2)\n );\n }\n}\nfunction getPositionsAndIndex(nestedIndex) {\n const positions = [...nestedIndex];\n const index = positions.pop();\n return { positions, index };\n}\nfunction uniqueTextMutations(mutations) {\n const idSet = /* @__PURE__ */ new Set();\n const uniqueMutations = [];\n for (let i2 = mutations.length; i2--; ) {\n const mutation = mutations[i2];\n if (!idSet.has(mutation.id)) {\n uniqueMutations.push(mutation);\n idSet.add(mutation.id);\n }\n }\n return uniqueMutations;\n}\nclass StyleSheetMirror {\n constructor() {\n this.id = 1;\n this.styleIDMap = /* @__PURE__ */ new WeakMap();\n this.idStyleMap = /* @__PURE__ */ new Map();\n }\n getId(stylesheet) {\n return this.styleIDMap.get(stylesheet) ?? -1;\n }\n has(stylesheet) {\n return this.styleIDMap.has(stylesheet);\n }\n /**\n * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id.\n */\n add(stylesheet, id) {\n if (this.has(stylesheet)) return this.getId(stylesheet);\n let newId;\n if (id === void 0) {\n newId = this.id++;\n } else newId = id;\n this.styleIDMap.set(stylesheet, newId);\n this.idStyleMap.set(newId, stylesheet);\n return newId;\n }\n getStyle(id) {\n return this.idStyleMap.get(id) || null;\n }\n reset() {\n this.styleIDMap = /* @__PURE__ */ new WeakMap();\n this.idStyleMap = /* @__PURE__ */ new Map();\n this.id = 1;\n }\n generateId() {\n return this.id++;\n }\n}\nfunction getShadowHost(n2) {\n let shadowHost = null;\n if (n2.getRootNode?.()?.nodeType === Node.DOCUMENT_FRAGMENT_NODE && n2.getRootNode().host)\n shadowHost = n2.getRootNode().host;\n return shadowHost;\n}\nfunction getRootShadowHost(n2) {\n let rootShadowHost = n2;\n let shadowHost;\n while (shadowHost = getShadowHost(rootShadowHost))\n rootShadowHost = shadowHost;\n return rootShadowHost;\n}\nfunction shadowHostInDom(n2) {\n const doc = n2.ownerDocument;\n if (!doc) return false;\n const shadowHost = getRootShadowHost(n2);\n return doc.contains(shadowHost);\n}\nfunction inDom(n2) {\n const doc = n2.ownerDocument;\n if (!doc) return false;\n return doc.contains(n2) || shadowHostInDom(n2);\n}\nconst cachedImplementations = {};\nfunction getImplementation(name) {\n const cached = cachedImplementations[name];\n if (cached) {\n return cached;\n }\n const document2 = window.document;\n let impl = window[name];\n if (document2 && typeof document2.createElement === \"function\") {\n try {\n const sandbox = document2.createElement(\"iframe\");\n sandbox.hidden = true;\n document2.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow[name]) {\n impl = // eslint-disable-next-line @typescript-eslint/unbound-method\n contentWindow[name];\n }\n document2.head.removeChild(sandbox);\n } catch (e2) {\n }\n }\n return cachedImplementations[name] = impl.bind(\n window\n );\n}\nfunction onRequestAnimationFrame(...rest) {\n return getImplementation(\"requestAnimationFrame\")(...rest);\n}\nfunction setTimeout$1(...rest) {\n return getImplementation(\"setTimeout\")(...rest);\n}\nfunction clearTimeout(...rest) {\n return getImplementation(\"clearTimeout\")(...rest);\n}\nconst utils = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({\n __proto__: null,\n StyleSheetMirror,\n get _mirror() {\n return _mirror;\n },\n clearTimeout,\n closestElementOfNode,\n getBaseDimension,\n getNestedRule,\n getPositionsAndIndex,\n getRootShadowHost,\n getShadowHost,\n getWindowHeight,\n getWindowScroll,\n getWindowWidth,\n hasShadowRoot,\n hookSetter,\n inDom,\n isAncestorRemoved,\n isBlocked,\n isIgnored,\n isSerialized,\n isSerializedIframe,\n isSerializedStylesheet,\n iterateResolveTree,\n legacy_isTouchEvent,\n get nowTimestamp() {\n return nowTimestamp;\n },\n on,\n onRequestAnimationFrame,\n patch,\n polyfill: polyfill$1,\n queueToResolveTrees,\n setTimeout: setTimeout$1,\n shadowHostInDom,\n throttle,\n uniqueTextMutations\n}, Symbol.toStringTag, { value: \"Module\" }));\nvar 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 MediaInteractions = /* @__PURE__ */ ((MediaInteractions2) => {\n MediaInteractions2[MediaInteractions2[\"Play\"] = 0] = \"Play\";\n MediaInteractions2[MediaInteractions2[\"Pause\"] = 1] = \"Pause\";\n MediaInteractions2[MediaInteractions2[\"Seeked\"] = 2] = \"Seeked\";\n MediaInteractions2[MediaInteractions2[\"VolumeChange\"] = 3] = \"VolumeChange\";\n MediaInteractions2[MediaInteractions2[\"RateChange\"] = 4] = \"RateChange\";\n return MediaInteractions2;\n})(MediaInteractions || {});\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 || {});\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nvar __defProp2 = Object.defineProperty;\nvar __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nvar NodeType$1 = /* @__PURE__ */ ((NodeType2) => {\n NodeType2[NodeType2[\"Document\"] = 0] = \"Document\";\n NodeType2[NodeType2[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType2[NodeType2[\"Element\"] = 2] = \"Element\";\n NodeType2[NodeType2[\"Text\"] = 3] = \"Text\";\n NodeType2[NodeType2[\"CDATA\"] = 4] = \"CDATA\";\n NodeType2[NodeType2[\"Comment\"] = 5] = \"Comment\";\n return NodeType2;\n})(NodeType$1 || {});\nlet Mirror$1 = class Mirror2 {\n constructor() {\n __publicField2(this, \"idNodeMap\", /* @__PURE__ */ new Map());\n __publicField2(this, \"nodeMetaMap\", /* @__PURE__ */ new WeakMap());\n }\n getId(n2) {\n if (!n2) return -1;\n const id = this.getMeta(n2)?.id;\n return id ?? -1;\n }\n getNode(id) {\n return this.idNodeMap.get(id) || null;\n }\n getIds() {\n return Array.from(this.idNodeMap.keys());\n }\n getMeta(n2) {\n return this.nodeMetaMap.get(n2) || null;\n }\n // removes the node from idNodeMap\n // doesn't remove the node from nodeMetaMap\n removeNodeFromMap(n2) {\n const id = this.getId(n2);\n this.idNodeMap.delete(id);\n if (n2.childNodes) {\n n2.childNodes.forEach(\n (childNode) => this.removeNodeFromMap(childNode)\n );\n }\n }\n has(id) {\n return this.idNodeMap.has(id);\n }\n hasNode(node) {\n return this.nodeMetaMap.has(node);\n }\n add(n2, meta) {\n const id = meta.id;\n this.idNodeMap.set(id, n2);\n this.nodeMetaMap.set(n2, meta);\n }\n replace(id, n2) {\n const oldNode = this.getNode(id);\n if (oldNode) {\n const meta = this.nodeMetaMap.get(oldNode);\n if (meta) this.nodeMetaMap.set(n2, meta);\n }\n this.idNodeMap.set(id, n2);\n }\n reset() {\n this.idNodeMap = /* @__PURE__ */ new Map();\n this.nodeMetaMap = /* @__PURE__ */ new WeakMap();\n }\n};\nfunction createMirror$1() {\n return new Mirror$1();\n}\nfunction parseCSSText(cssText) {\n const res = {};\n const listDelimiter = /;(?![^(]*\\))/g;\n const propertyDelimiter = /:(.+)/;\n const comment = /\\/\\*.*?\\*\\//g;\n cssText.replace(comment, \"\").split(listDelimiter).forEach(function(item) {\n if (item) {\n const tmp = item.split(propertyDelimiter);\n tmp.length > 1 && (res[camelize(tmp[0].trim())] = tmp[1].trim());\n }\n });\n return res;\n}\nfunction toCSSText(style) {\n const properties = [];\n for (const name in style) {\n const value = style[name];\n if (typeof value !== \"string\") continue;\n const normalizedName = hyphenate(name);\n properties.push(`${normalizedName}: ${value};`);\n }\n return properties.join(\" \");\n}\nconst camelizeRE = /-([a-z])/g;\nconst CUSTOM_PROPERTY_REGEX = /^--[a-zA-Z0-9-]+$/;\nconst camelize = (str) => {\n if (CUSTOM_PROPERTY_REGEX.test(str)) return str;\n return str.replace(camelizeRE, (_, c2) => c2 ? c2.toUpperCase() : \"\");\n};\nconst hyphenateRE = /\\B([A-Z])/g;\nconst hyphenate = (str) => {\n return str.replace(hyphenateRE, \"-$1\").toLowerCase();\n};\nclass BaseRRNode {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any\n constructor(..._args) {\n __publicField(this, \"parentElement\", null);\n __publicField(this, \"parentNode\", null);\n __publicField(this, \"ownerDocument\");\n __publicField(this, \"firstChild\", null);\n __publicField(this, \"lastChild\", null);\n __publicField(this, \"previousSibling\", null);\n __publicField(this, \"nextSibling\", null);\n __publicField(this, \"ELEMENT_NODE\", 1);\n __publicField(this, \"TEXT_NODE\", 3);\n __publicField(this, \"nodeType\");\n __publicField(this, \"nodeName\");\n __publicField(this, \"RRNodeType\");\n }\n get childNodes() {\n const childNodes = [];\n let childIterator = this.firstChild;\n while (childIterator) {\n childNodes.push(childIterator);\n childIterator = childIterator.nextSibling;\n }\n return childNodes;\n }\n contains(node) {\n if (!(node instanceof BaseRRNode)) return false;\n else if (node.ownerDocument !== this.ownerDocument) return false;\n else if (node === this) return true;\n while (node.parentNode) {\n if (node.parentNode === this) return true;\n node = node.parentNode;\n }\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n appendChild(_newChild) {\n throw new Error(\n `RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.`\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n insertBefore(_newChild, _refChild) {\n throw new Error(\n `RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.`\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n removeChild(_node) {\n throw new Error(\n `RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.`\n );\n }\n toString() {\n return \"RRNode\";\n }\n}\nclass BaseRRDocument extends BaseRRNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(...args) {\n super(args);\n __publicField(this, \"nodeType\", 9);\n __publicField(this, \"nodeName\", \"#document\");\n __publicField(this, \"compatMode\", \"CSS1Compat\");\n __publicField(this, \"RRNodeType\", NodeType$1.Document);\n __publicField(this, \"textContent\", null);\n this.ownerDocument = this;\n }\n get documentElement() {\n return this.childNodes.find(\n (node) => node.RRNodeType === NodeType$1.Element && node.tagName === \"HTML\"\n ) || null;\n }\n get body() {\n return this.documentElement?.childNodes.find(\n (node) => node.RRNodeType === NodeType$1.Element && node.tagName === \"BODY\"\n ) || null;\n }\n get head() {\n return this.documentElement?.childNodes.find(\n (node) => node.RRNodeType === NodeType$1.Element && node.tagName === \"HEAD\"\n ) || null;\n }\n get implementation() {\n return this;\n }\n get firstElementChild() {\n return this.documentElement;\n }\n appendChild(newChild) {\n const nodeType = newChild.RRNodeType;\n if (nodeType === NodeType$1.Element || nodeType === NodeType$1.DocumentType) {\n if (this.childNodes.some((s2) => s2.RRNodeType === nodeType)) {\n throw new Error(\n `RRDomException: Failed to execute 'appendChild' on 'RRNode': Only one ${nodeType === NodeType$1.Element ? \"RRElement\" : \"RRDoctype\"} on RRDocument allowed.`\n );\n }\n }\n const child = appendChild(this, newChild);\n child.parentElement = null;\n return child;\n }\n insertBefore(newChild, refChild) {\n const nodeType = newChild.RRNodeType;\n if (nodeType === NodeType$1.Element || nodeType === NodeType$1.DocumentType) {\n if (this.childNodes.some((s2) => s2.RRNodeType === nodeType)) {\n throw new Error(\n `RRDomException: Failed to execute 'insertBefore' on 'RRNode': Only one ${nodeType === NodeType$1.Element ? \"RRElement\" : \"RRDoctype\"} on RRDocument allowed.`\n );\n }\n }\n const child = insertBefore(this, newChild, refChild);\n child.parentElement = null;\n return child;\n }\n removeChild(node) {\n return removeChild(this, node);\n }\n open() {\n this.firstChild = null;\n this.lastChild = null;\n }\n close() {\n }\n /**\n * Adhoc implementation for setting xhtml namespace in rebuilt.ts (rrweb-snapshot).\n * There are two lines used this function:\n * 1. doc.write('\\')\n * 2. doc.write('\\')\n */\n write(content) {\n let publicId;\n if (content === '')\n publicId = \"-//W3C//DTD XHTML 1.0 Transitional//EN\";\n else if (content === '')\n publicId = \"-//W3C//DTD HTML 4.0 Transitional//EN\";\n if (publicId) {\n const doctype = this.createDocumentType(\"html\", publicId, \"\");\n this.open();\n this.appendChild(doctype);\n }\n }\n createDocument(_namespace, _qualifiedName, _doctype) {\n return new BaseRRDocument();\n }\n createDocumentType(qualifiedName, publicId, systemId) {\n const doctype = new BaseRRDocumentType(qualifiedName, publicId, systemId);\n doctype.ownerDocument = this;\n return doctype;\n }\n createElement(tagName) {\n const element = new BaseRRElement(tagName);\n element.ownerDocument = this;\n return element;\n }\n createElementNS(_namespaceURI, qualifiedName) {\n return this.createElement(qualifiedName);\n }\n createTextNode(data) {\n const text = new BaseRRText(data);\n text.ownerDocument = this;\n return text;\n }\n createComment(data) {\n const comment = new BaseRRComment(data);\n comment.ownerDocument = this;\n return comment;\n }\n createCDATASection(data) {\n const CDATASection = new BaseRRCDATASection(data);\n CDATASection.ownerDocument = this;\n return CDATASection;\n }\n toString() {\n return \"RRDocument\";\n }\n}\nclass BaseRRDocumentType extends BaseRRNode {\n constructor(qualifiedName, publicId, systemId) {\n super();\n __publicField(this, \"nodeType\", 10);\n __publicField(this, \"RRNodeType\", NodeType$1.DocumentType);\n __publicField(this, \"name\");\n __publicField(this, \"publicId\");\n __publicField(this, \"systemId\");\n __publicField(this, \"textContent\", null);\n this.name = qualifiedName;\n this.publicId = publicId;\n this.systemId = systemId;\n this.nodeName = qualifiedName;\n }\n toString() {\n return \"RRDocumentType\";\n }\n}\nclass BaseRRElement extends BaseRRNode {\n constructor(tagName) {\n super();\n __publicField(this, \"nodeType\", 1);\n __publicField(this, \"RRNodeType\", NodeType$1.Element);\n __publicField(this, \"tagName\");\n __publicField(this, \"attributes\", {});\n __publicField(this, \"shadowRoot\", null);\n __publicField(this, \"scrollLeft\");\n __publicField(this, \"scrollTop\");\n this.tagName = tagName.toUpperCase();\n this.nodeName = tagName.toUpperCase();\n }\n get textContent() {\n let result = \"\";\n this.childNodes.forEach((node) => result += node.textContent);\n return result;\n }\n set textContent(textContent) {\n this.firstChild = null;\n this.lastChild = null;\n this.appendChild(this.ownerDocument.createTextNode(textContent));\n }\n get classList() {\n return new ClassList(\n this.attributes.class,\n (newClassName) => {\n this.attributes.class = newClassName;\n }\n );\n }\n get id() {\n return this.attributes.id || \"\";\n }\n get className() {\n return this.attributes.class || \"\";\n }\n get style() {\n const style = this.attributes.style ? parseCSSText(this.attributes.style) : {};\n const hyphenateRE2 = /\\B([A-Z])/g;\n style.setProperty = (name, value, priority) => {\n if (hyphenateRE2.test(name)) return;\n const normalizedName = camelize(name);\n if (!value) delete style[normalizedName];\n else style[normalizedName] = value;\n if (priority === \"important\") style[normalizedName] += \" !important\";\n this.attributes.style = toCSSText(style);\n };\n style.removeProperty = (name) => {\n if (hyphenateRE2.test(name)) return \"\";\n const normalizedName = camelize(name);\n const value = style[normalizedName] || \"\";\n delete style[normalizedName];\n this.attributes.style = toCSSText(style);\n return value;\n };\n return style;\n }\n getAttribute(name) {\n return this.attributes[name] || null;\n }\n setAttribute(name, attribute) {\n this.attributes[name] = attribute;\n }\n setAttributeNS(_namespace, qualifiedName, value) {\n this.setAttribute(qualifiedName, value);\n }\n removeAttribute(name) {\n delete this.attributes[name];\n }\n appendChild(newChild) {\n return appendChild(this, newChild);\n }\n insertBefore(newChild, refChild) {\n return insertBefore(this, newChild, refChild);\n }\n removeChild(node) {\n return removeChild(this, node);\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n attachShadow(_init) {\n const shadowRoot = this.ownerDocument.createElement(\"SHADOWROOT\");\n this.shadowRoot = shadowRoot;\n return shadowRoot;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dispatchEvent(_event) {\n return true;\n }\n toString() {\n let attributeString = \"\";\n for (const attribute in this.attributes) {\n attributeString += `${attribute}=\"${this.attributes[attribute]}\" `;\n }\n return `${this.tagName} ${attributeString}`;\n }\n}\nclass BaseRRMediaElement extends BaseRRElement {\n constructor() {\n super(...arguments);\n __publicField(this, \"currentTime\");\n __publicField(this, \"volume\");\n __publicField(this, \"paused\");\n __publicField(this, \"muted\");\n __publicField(this, \"playbackRate\");\n __publicField(this, \"loop\");\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n attachShadow(_init) {\n throw new Error(\n `RRDomException: Failed to execute 'attachShadow' on 'RRElement': This RRElement does not support attachShadow`\n );\n }\n play() {\n this.paused = false;\n }\n pause() {\n this.paused = true;\n }\n}\nclass BaseRRText extends BaseRRNode {\n constructor(data) {\n super();\n __publicField(this, \"nodeType\", 3);\n __publicField(this, \"nodeName\", \"#text\");\n __publicField(this, \"RRNodeType\", NodeType$1.Text);\n __publicField(this, \"data\");\n this.data = data;\n }\n get textContent() {\n return this.data;\n }\n set textContent(textContent) {\n this.data = textContent;\n }\n toString() {\n return `RRText text=${JSON.stringify(this.data)}`;\n }\n}\nclass BaseRRComment extends BaseRRNode {\n constructor(data) {\n super();\n __publicField(this, \"nodeType\", 8);\n __publicField(this, \"nodeName\", \"#comment\");\n __publicField(this, \"RRNodeType\", NodeType$1.Comment);\n __publicField(this, \"data\");\n this.data = data;\n }\n get textContent() {\n return this.data;\n }\n set textContent(textContent) {\n this.data = textContent;\n }\n toString() {\n return `RRComment text=${JSON.stringify(this.data)}`;\n }\n}\nclass BaseRRCDATASection extends BaseRRNode {\n constructor(data) {\n super();\n __publicField(this, \"nodeName\", \"#cdata-section\");\n __publicField(this, \"nodeType\", 4);\n __publicField(this, \"RRNodeType\", NodeType$1.CDATA);\n __publicField(this, \"data\");\n this.data = data;\n }\n get textContent() {\n return this.data;\n }\n set textContent(textContent) {\n this.data = textContent;\n }\n toString() {\n return `RRCDATASection data=${JSON.stringify(this.data)}`;\n }\n}\nclass ClassList {\n constructor(classText, onChange) {\n __publicField(this, \"onChange\");\n __publicField(this, \"classes\", []);\n __publicField(this, \"add\", (...classNames) => {\n for (const item of classNames) {\n const className = String(item);\n if (this.classes.indexOf(className) >= 0) continue;\n this.classes.push(className);\n }\n this.onChange && this.onChange(this.classes.join(\" \"));\n });\n __publicField(this, \"remove\", (...classNames) => {\n this.classes = this.classes.filter(\n (item) => classNames.indexOf(item) === -1\n );\n this.onChange && this.onChange(this.classes.join(\" \"));\n });\n if (classText) {\n const classes = classText.trim().split(/\\s+/);\n this.classes.push(...classes);\n }\n this.onChange = onChange;\n }\n}\nfunction appendChild(parent, newChild) {\n if (newChild.parentNode) newChild.parentNode.removeChild(newChild);\n if (parent.lastChild) {\n parent.lastChild.nextSibling = newChild;\n newChild.previousSibling = parent.lastChild;\n } else {\n parent.firstChild = newChild;\n newChild.previousSibling = null;\n }\n parent.lastChild = newChild;\n newChild.nextSibling = null;\n newChild.parentNode = parent;\n newChild.parentElement = parent;\n newChild.ownerDocument = parent.ownerDocument;\n return newChild;\n}\nfunction insertBefore(parent, newChild, refChild) {\n if (!refChild) return appendChild(parent, newChild);\n if (refChild.parentNode !== parent)\n throw new Error(\n \"Failed to execute 'insertBefore' on 'RRNode': The RRNode before which the new node is to be inserted is not a child of this RRNode.\"\n );\n if (newChild === refChild) return newChild;\n if (newChild.parentNode) newChild.parentNode.removeChild(newChild);\n newChild.previousSibling = refChild.previousSibling;\n refChild.previousSibling = newChild;\n newChild.nextSibling = refChild;\n if (newChild.previousSibling) newChild.previousSibling.nextSibling = newChild;\n else parent.firstChild = newChild;\n newChild.parentElement = parent;\n newChild.parentNode = parent;\n newChild.ownerDocument = parent.ownerDocument;\n return newChild;\n}\nfunction removeChild(parent, child) {\n if (child.parentNode !== parent)\n throw new Error(\n \"Failed to execute 'removeChild' on 'RRNode': The RRNode to be removed is not a child of this RRNode.\"\n );\n if (child.previousSibling)\n child.previousSibling.nextSibling = child.nextSibling;\n else parent.firstChild = child.nextSibling;\n if (child.nextSibling)\n child.nextSibling.previousSibling = child.previousSibling;\n else parent.lastChild = child.previousSibling;\n child.previousSibling = null;\n child.nextSibling = null;\n child.parentElement = null;\n child.parentNode = null;\n return child;\n}\nvar NodeType = /* @__PURE__ */ ((NodeType2) => {\n NodeType2[NodeType2[\"PLACEHOLDER\"] = 0] = \"PLACEHOLDER\";\n NodeType2[NodeType2[\"ELEMENT_NODE\"] = 1] = \"ELEMENT_NODE\";\n NodeType2[NodeType2[\"ATTRIBUTE_NODE\"] = 2] = \"ATTRIBUTE_NODE\";\n NodeType2[NodeType2[\"TEXT_NODE\"] = 3] = \"TEXT_NODE\";\n NodeType2[NodeType2[\"CDATA_SECTION_NODE\"] = 4] = \"CDATA_SECTION_NODE\";\n NodeType2[NodeType2[\"ENTITY_REFERENCE_NODE\"] = 5] = \"ENTITY_REFERENCE_NODE\";\n NodeType2[NodeType2[\"ENTITY_NODE\"] = 6] = \"ENTITY_NODE\";\n NodeType2[NodeType2[\"PROCESSING_INSTRUCTION_NODE\"] = 7] = \"PROCESSING_INSTRUCTION_NODE\";\n NodeType2[NodeType2[\"COMMENT_NODE\"] = 8] = \"COMMENT_NODE\";\n NodeType2[NodeType2[\"DOCUMENT_NODE\"] = 9] = \"DOCUMENT_NODE\";\n NodeType2[NodeType2[\"DOCUMENT_TYPE_NODE\"] = 10] = \"DOCUMENT_TYPE_NODE\";\n NodeType2[NodeType2[\"DOCUMENT_FRAGMENT_NODE\"] = 11] = \"DOCUMENT_FRAGMENT_NODE\";\n return NodeType2;\n})(NodeType || {});\nfunction getIFrameContentDocument(iframe) {\n try {\n return iframe.contentDocument;\n } catch (e2) {\n }\n}\nfunction getIFrameContentWindow(iframe) {\n try {\n return iframe.contentWindow;\n } catch (e2) {\n }\n}\nconst NAMESPACES = {\n svg: \"http://www.w3.org/2000/svg\",\n \"xlink:href\": \"http://www.w3.org/1999/xlink\",\n xmlns: \"http://www.w3.org/2000/xmlns/\"\n};\nconst SVGTagMap = {\n altglyph: \"altGlyph\",\n altglyphdef: \"altGlyphDef\",\n altglyphitem: \"altGlyphItem\",\n animatecolor: \"animateColor\",\n animatemotion: \"animateMotion\",\n animatetransform: \"animateTransform\",\n clippath: \"clipPath\",\n feblend: \"feBlend\",\n fecolormatrix: \"feColorMatrix\",\n fecomponenttransfer: \"feComponentTransfer\",\n fecomposite: \"feComposite\",\n feconvolvematrix: \"feConvolveMatrix\",\n fediffuselighting: \"feDiffuseLighting\",\n fedisplacementmap: \"feDisplacementMap\",\n fedistantlight: \"feDistantLight\",\n fedropshadow: \"feDropShadow\",\n feflood: \"feFlood\",\n fefunca: \"feFuncA\",\n fefuncb: \"feFuncB\",\n fefuncg: \"feFuncG\",\n fefuncr: \"feFuncR\",\n fegaussianblur: \"feGaussianBlur\",\n feimage: \"feImage\",\n femerge: \"feMerge\",\n femergenode: \"feMergeNode\",\n femorphology: \"feMorphology\",\n feoffset: \"feOffset\",\n fepointlight: \"fePointLight\",\n fespecularlighting: \"feSpecularLighting\",\n fespotlight: \"feSpotLight\",\n fetile: \"feTile\",\n feturbulence: \"feTurbulence\",\n foreignobject: \"foreignObject\",\n glyphref: \"glyphRef\",\n lineargradient: \"linearGradient\",\n radialgradient: \"radialGradient\"\n};\nlet createdNodeSet = null;\nfunction diff(oldTree, newTree, replayer, rrnodeMirror = newTree.mirror || newTree.ownerDocument.mirror) {\n oldTree = diffBeforeUpdatingChildren(\n oldTree,\n newTree,\n replayer,\n rrnodeMirror\n );\n diffChildren(oldTree, newTree, replayer, rrnodeMirror);\n diffAfterUpdatingChildren(oldTree, newTree, replayer);\n}\nfunction diffBeforeUpdatingChildren(oldTree, newTree, replayer, rrnodeMirror) {\n if (replayer.afterAppend && !createdNodeSet) {\n createdNodeSet = /* @__PURE__ */ new WeakSet();\n setTimeout(() => {\n createdNodeSet = null;\n }, 0);\n }\n if (!sameNodeType(oldTree, newTree)) {\n const calibratedOldTree = createOrGetNode(\n newTree,\n replayer.mirror,\n rrnodeMirror\n );\n oldTree.parentNode?.replaceChild(calibratedOldTree, oldTree);\n oldTree = calibratedOldTree;\n }\n switch (newTree.RRNodeType) {\n case NodeType$1.Document: {\n if (!nodeMatching(oldTree, newTree, replayer.mirror, rrnodeMirror)) {\n const newMeta = rrnodeMirror.getMeta(newTree);\n if (newMeta) {\n replayer.mirror.removeNodeFromMap(oldTree);\n oldTree.close();\n oldTree.open();\n replayer.mirror.add(oldTree, newMeta);\n createdNodeSet?.add(oldTree);\n }\n }\n break;\n }\n case NodeType$1.Element: {\n const oldElement = oldTree;\n const newRRElement = newTree;\n switch (newRRElement.tagName) {\n case \"IFRAME\": {\n const oldContentDocument = getIFrameContentDocument(\n oldTree\n );\n if (!oldContentDocument) break;\n diff(\n oldContentDocument,\n newTree.contentDocument,\n replayer,\n rrnodeMirror\n );\n break;\n }\n }\n if (newRRElement.shadowRoot) {\n if (!oldElement.shadowRoot) oldElement.attachShadow({ mode: \"open\" });\n diffChildren(\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n oldElement.shadowRoot,\n newRRElement.shadowRoot,\n replayer,\n rrnodeMirror\n );\n }\n diffProps(oldElement, newRRElement, rrnodeMirror);\n break;\n }\n }\n return oldTree;\n}\nfunction diffAfterUpdatingChildren(oldTree, newTree, replayer) {\n switch (newTree.RRNodeType) {\n case NodeType$1.Document: {\n const scrollData = newTree.scrollData;\n scrollData && replayer.applyScroll(scrollData, true);\n break;\n }\n case NodeType$1.Element: {\n const oldElement = oldTree;\n const newRRElement = newTree;\n newRRElement.scrollData && replayer.applyScroll(newRRElement.scrollData, true);\n newRRElement.inputData && replayer.applyInput(newRRElement.inputData);\n switch (newRRElement.tagName) {\n case \"AUDIO\":\n case \"VIDEO\": {\n const oldMediaElement = oldTree;\n const newMediaRRElement = newRRElement;\n if (newMediaRRElement.paused !== void 0) {\n const maybePromise = newMediaRRElement.paused ? oldMediaElement.pause() : oldMediaElement.play();\n if (typeof maybePromise?.catch === \"function\") {\n maybePromise.catch((e2) => {\n console.warn(e2);\n });\n }\n }\n if (newMediaRRElement.muted !== void 0)\n oldMediaElement.muted = newMediaRRElement.muted;\n if (newMediaRRElement.volume !== void 0)\n oldMediaElement.volume = newMediaRRElement.volume;\n if (newMediaRRElement.currentTime !== void 0)\n oldMediaElement.currentTime = newMediaRRElement.currentTime;\n if (newMediaRRElement.playbackRate !== void 0)\n oldMediaElement.playbackRate = newMediaRRElement.playbackRate;\n break;\n }\n case \"CANVAS\": {\n const rrCanvasElement = newTree;\n if (rrCanvasElement.rr_dataURL !== null) {\n const image = document.createElement(\"img\");\n image.onload = () => {\n const ctx = oldElement.getContext(\"2d\");\n if (ctx) {\n ctx.drawImage(image, 0, 0, image.width, image.height);\n }\n };\n image.src = rrCanvasElement.rr_dataURL;\n }\n rrCanvasElement.canvasMutations.forEach(\n (canvasMutation2) => replayer.applyCanvas(\n canvasMutation2.event,\n canvasMutation2.mutation,\n oldTree\n )\n );\n break;\n }\n case \"STYLE\": {\n const styleSheet = oldElement.sheet;\n styleSheet && newTree.rules.forEach(\n (data) => replayer.applyStyleSheetMutation(data, styleSheet)\n );\n break;\n }\n }\n break;\n }\n case NodeType$1.Text:\n case NodeType$1.Comment:\n case NodeType$1.CDATA: {\n if (oldTree.textContent !== newTree.data)\n oldTree.textContent = newTree.data;\n break;\n }\n }\n if (createdNodeSet?.has(oldTree)) {\n createdNodeSet.delete(oldTree);\n replayer.afterAppend?.(oldTree, replayer.mirror.getId(oldTree));\n }\n}\nfunction diffProps(oldTree, newTree, rrnodeMirror) {\n const oldAttributes = oldTree.attributes;\n const newAttributes = newTree.attributes;\n for (const name in newAttributes) {\n const newValue = newAttributes[name];\n const sn = rrnodeMirror.getMeta(newTree);\n if (sn?.isSVG && NAMESPACES[name])\n oldTree.setAttributeNS(NAMESPACES[name], name, newValue);\n else if (newTree.tagName === \"CANVAS\" && name === \"rr_dataURL\") {\n const image = document.createElement(\"img\");\n image.src = newValue;\n image.onload = () => {\n const ctx = oldTree.getContext(\"2d\");\n if (ctx) {\n ctx.drawImage(image, 0, 0, image.width, image.height);\n }\n };\n } else if (newTree.tagName === \"IFRAME\" && name === \"srcdoc\") continue;\n else {\n try {\n oldTree.setAttribute(name, newValue);\n } catch (err) {\n console.warn(err);\n }\n }\n }\n for (const { name } of Array.from(oldAttributes))\n if (!(name in newAttributes)) oldTree.removeAttribute(name);\n newTree.scrollLeft && (oldTree.scrollLeft = newTree.scrollLeft);\n newTree.scrollTop && (oldTree.scrollTop = newTree.scrollTop);\n}\nfunction diffChildren(oldTree, newTree, replayer, rrnodeMirror) {\n const oldChildren = Array.from(oldTree.childNodes);\n const newChildren = newTree.childNodes;\n if (oldChildren.length === 0 && newChildren.length === 0) return;\n let oldStartIndex = 0, oldEndIndex = oldChildren.length - 1, newStartIndex = 0, newEndIndex = newChildren.length - 1;\n let oldStartNode = oldChildren[oldStartIndex], oldEndNode = oldChildren[oldEndIndex], newStartNode = newChildren[newStartIndex], newEndNode = newChildren[newEndIndex];\n let oldIdToIndex = void 0, indexInOld = void 0;\n while (oldStartIndex <= oldEndIndex && newStartIndex <= newEndIndex) {\n if (oldStartNode === void 0) {\n oldStartNode = oldChildren[++oldStartIndex];\n } else if (oldEndNode === void 0) {\n oldEndNode = oldChildren[--oldEndIndex];\n } else if (\n // same first node?\n nodeMatching(oldStartNode, newStartNode, replayer.mirror, rrnodeMirror)\n ) {\n oldStartNode = oldChildren[++oldStartIndex];\n newStartNode = newChildren[++newStartIndex];\n } else if (\n // same last node?\n nodeMatching(oldEndNode, newEndNode, replayer.mirror, rrnodeMirror)\n ) {\n oldEndNode = oldChildren[--oldEndIndex];\n newEndNode = newChildren[--newEndIndex];\n } else if (\n // is the first old node the same as the last new node?\n nodeMatching(oldStartNode, newEndNode, replayer.mirror, rrnodeMirror)\n ) {\n try {\n handleInsertBefore(oldTree, oldStartNode, oldEndNode.nextSibling);\n } catch (e2) {\n console.warn(e2);\n }\n oldStartNode = oldChildren[++oldStartIndex];\n newEndNode = newChildren[--newEndIndex];\n } else if (\n // is the last old node the same as the first new node?\n nodeMatching(oldEndNode, newStartNode, replayer.mirror, rrnodeMirror)\n ) {\n try {\n handleInsertBefore(oldTree, oldEndNode, oldStartNode);\n } catch (e2) {\n console.warn(e2);\n }\n oldEndNode = oldChildren[--oldEndIndex];\n newStartNode = newChildren[++newStartIndex];\n } else {\n if (!oldIdToIndex) {\n oldIdToIndex = {};\n for (let i2 = oldStartIndex; i2 <= oldEndIndex; i2++) {\n const oldChild2 = oldChildren[i2];\n if (oldChild2 && replayer.mirror.hasNode(oldChild2))\n oldIdToIndex[replayer.mirror.getId(oldChild2)] = i2;\n }\n }\n indexInOld = oldIdToIndex[rrnodeMirror.getId(newStartNode)];\n const nodeToMove = oldChildren[indexInOld];\n if (indexInOld !== void 0 && nodeToMove && nodeMatching(nodeToMove, newStartNode, replayer.mirror, rrnodeMirror)) {\n try {\n handleInsertBefore(oldTree, nodeToMove, oldStartNode);\n } catch (e2) {\n console.warn(e2);\n }\n oldChildren[indexInOld] = void 0;\n } else {\n const newNode = createOrGetNode(\n newStartNode,\n replayer.mirror,\n rrnodeMirror\n );\n if (oldTree.nodeName === \"#document\" && oldStartNode && /**\n * Special case 1: one document isn't allowed to have two doctype nodes at the same time, so we need to remove the old one first before inserting the new one.\n * How this case happens: A parent document in the old tree already has a doctype node with an id e.g. #1. A new full snapshot rebuilds the replayer with a new doctype node with another id #2. According to the algorithm, the new doctype node will be inserted before the old one, which is not allowed by the Document standard.\n */\n (newNode.nodeType === newNode.DOCUMENT_TYPE_NODE && oldStartNode.nodeType === oldStartNode.DOCUMENT_TYPE_NODE || /**\n * Special case 2: one document isn't allowed to have two HTMLElements at the same time, so we need to remove the old one first before inserting the new one.\n * How this case happens: A mounted iframe element has an automatically created HTML element. We should delete it before inserting a serialized one. Otherwise, an error 'Only one element on document allowed' will be thrown.\n */\n newNode.nodeType === newNode.ELEMENT_NODE && oldStartNode.nodeType === oldStartNode.ELEMENT_NODE)) {\n oldTree.removeChild(oldStartNode);\n replayer.mirror.removeNodeFromMap(oldStartNode);\n oldStartNode = oldChildren[++oldStartIndex];\n }\n try {\n handleInsertBefore(oldTree, newNode, oldStartNode || null);\n } catch (e2) {\n console.warn(e2);\n }\n }\n newStartNode = newChildren[++newStartIndex];\n }\n }\n if (oldStartIndex > oldEndIndex) {\n const referenceRRNode = newChildren[newEndIndex + 1];\n let referenceNode = null;\n if (referenceRRNode)\n referenceNode = replayer.mirror.getNode(\n rrnodeMirror.getId(referenceRRNode)\n );\n for (; newStartIndex <= newEndIndex; ++newStartIndex) {\n const newNode = createOrGetNode(\n newChildren[newStartIndex],\n replayer.mirror,\n rrnodeMirror\n );\n try {\n handleInsertBefore(oldTree, newNode, referenceNode);\n } catch (e2) {\n console.warn(e2);\n }\n }\n } else if (newStartIndex > newEndIndex) {\n for (; oldStartIndex <= oldEndIndex; oldStartIndex++) {\n const node = oldChildren[oldStartIndex];\n if (!node || node.parentNode !== oldTree) continue;\n try {\n oldTree.removeChild(node);\n replayer.mirror.removeNodeFromMap(node);\n } catch (e2) {\n console.warn(e2);\n }\n }\n }\n let oldChild = oldTree.firstChild;\n let newChild = newTree.firstChild;\n while (oldChild !== null && newChild !== null) {\n diff(oldChild, newChild, replayer, rrnodeMirror);\n oldChild = oldChild.nextSibling;\n newChild = newChild.nextSibling;\n }\n}\nfunction createOrGetNode(rrNode, domMirror, rrnodeMirror) {\n const nodeId = rrnodeMirror.getId(rrNode);\n const sn = rrnodeMirror.getMeta(rrNode);\n let node = null;\n if (nodeId > -1) node = domMirror.getNode(nodeId);\n if (node !== null && sameNodeType(node, rrNode)) return node;\n switch (rrNode.RRNodeType) {\n case NodeType$1.Document:\n node = new Document();\n break;\n case NodeType$1.DocumentType:\n node = document.implementation.createDocumentType(\n rrNode.name,\n rrNode.publicId,\n rrNode.systemId\n );\n break;\n case NodeType$1.Element: {\n let tagName = rrNode.tagName.toLowerCase();\n tagName = SVGTagMap[tagName] || tagName;\n if (sn && \"isSVG\" in sn && sn?.isSVG) {\n node = document.createElementNS(NAMESPACES[\"svg\"], tagName);\n } else node = document.createElement(rrNode.tagName);\n break;\n }\n case NodeType$1.Text:\n node = document.createTextNode(rrNode.data);\n break;\n case NodeType$1.Comment:\n node = document.createComment(rrNode.data);\n break;\n case NodeType$1.CDATA:\n node = document.createCDATASection(rrNode.data);\n break;\n }\n if (sn) domMirror.add(node, { ...sn });\n try {\n createdNodeSet?.add(node);\n } catch (e2) {\n }\n return node;\n}\nfunction sameNodeType(node1, node2) {\n if (node1.nodeType !== node2.nodeType) return false;\n return node1.nodeType !== node1.ELEMENT_NODE || node1.tagName.toUpperCase() === node2.tagName;\n}\nfunction nodeMatching(node1, node2, domMirror, rrdomMirror) {\n const node1Id = domMirror.getId(node1);\n const node2Id = rrdomMirror.getId(node2);\n if (node1Id === -1 || node1Id !== node2Id) return false;\n return sameNodeType(node1, node2);\n}\nfunction getInsertedStylesFromElement(styleElement) {\n const elementCssRules = styleElement.sheet?.cssRules;\n if (!elementCssRules || !elementCssRules.length) return;\n const tempStyleSheet = new CSSStyleSheet();\n tempStyleSheet.replaceSync(styleElement.innerText);\n const innerTextStylesMap = {};\n for (let i2 = 0; i2 < tempStyleSheet.cssRules.length; i2++) {\n innerTextStylesMap[tempStyleSheet.cssRules[i2].cssText] = tempStyleSheet.cssRules[i2];\n }\n const insertedStylesStyleSheet = [];\n for (let i2 = 0; i2 < elementCssRules?.length; i2++) {\n const cssRuleText = elementCssRules[i2].cssText;\n if (!innerTextStylesMap[cssRuleText]) {\n insertedStylesStyleSheet.push({\n index: i2,\n cssRuleText\n });\n }\n }\n return insertedStylesStyleSheet;\n}\nfunction handleInsertBefore(oldTree, nodeToMove, insertBeforeNode) {\n let insertedStyles;\n if (nodeToMove.nodeName === \"STYLE\") {\n insertedStyles = getInsertedStylesFromElement(\n nodeToMove\n );\n }\n oldTree.insertBefore(nodeToMove, insertBeforeNode);\n if (insertedStyles && insertedStyles.length) {\n insertedStyles.forEach(({ cssRuleText, index }) => {\n nodeToMove.sheet?.insertRule(cssRuleText, index);\n });\n }\n}\nclass RRDocument extends BaseRRDocument {\n constructor(mirror2) {\n super();\n __publicField(this, \"UNSERIALIZED_STARTING_ID\", -2);\n __publicField(this, \"_unserializedId\", this.UNSERIALIZED_STARTING_ID);\n __publicField(this, \"mirror\", createMirror());\n __publicField(this, \"scrollData\", null);\n if (mirror2) {\n this.mirror = mirror2;\n }\n }\n /**\n * Every time the id is used, it will minus 1 automatically to avoid collisions.\n */\n get unserializedId() {\n return this._unserializedId--;\n }\n createDocument(_namespace, _qualifiedName, _doctype) {\n return new RRDocument();\n }\n createDocumentType(qualifiedName, publicId, systemId) {\n const documentTypeNode = new RRDocumentType(\n qualifiedName,\n publicId,\n systemId\n );\n documentTypeNode.ownerDocument = this;\n return documentTypeNode;\n }\n createElement(tagName) {\n const upperTagName = tagName.toUpperCase();\n let element;\n switch (upperTagName) {\n case \"AUDIO\":\n case \"VIDEO\":\n element = new RRMediaElement(upperTagName);\n break;\n case \"IFRAME\":\n element = new RRIFrameElement(upperTagName, this.mirror);\n break;\n case \"CANVAS\":\n element = new RRCanvasElement(upperTagName);\n break;\n case \"STYLE\":\n element = new RRStyleElement(upperTagName);\n break;\n default:\n element = new RRElement(upperTagName);\n break;\n }\n element.ownerDocument = this;\n return element;\n }\n createComment(data) {\n const commentNode = new RRComment(data);\n commentNode.ownerDocument = this;\n return commentNode;\n }\n createCDATASection(data) {\n const sectionNode = new RRCDATASection(data);\n sectionNode.ownerDocument = this;\n return sectionNode;\n }\n createTextNode(data) {\n const textNode = new RRText(data);\n textNode.ownerDocument = this;\n return textNode;\n }\n destroyTree() {\n this.firstChild = null;\n this.lastChild = null;\n this.mirror.reset();\n }\n open() {\n super.open();\n this._unserializedId = this.UNSERIALIZED_STARTING_ID;\n }\n}\nconst RRDocumentType = BaseRRDocumentType;\nclass RRElement extends BaseRRElement {\n constructor() {\n super(...arguments);\n __publicField(this, \"inputData\", null);\n __publicField(this, \"scrollData\", null);\n }\n}\nclass RRMediaElement extends BaseRRMediaElement {\n}\nclass RRCanvasElement extends RRElement {\n constructor() {\n super(...arguments);\n __publicField(this, \"rr_dataURL\", null);\n __publicField(this, \"canvasMutations\", []);\n }\n /**\n * This is a dummy implementation to distinguish RRCanvasElement from real HTMLCanvasElement.\n */\n getContext() {\n return null;\n }\n}\nclass RRStyleElement extends RRElement {\n constructor() {\n super(...arguments);\n __publicField(this, \"rules\", []);\n }\n}\nclass RRIFrameElement extends RRElement {\n constructor(upperTagName, mirror2) {\n super(upperTagName);\n __publicField(this, \"contentDocument\", new RRDocument());\n this.contentDocument.mirror = mirror2;\n }\n}\nconst RRText = BaseRRText;\nconst RRComment = BaseRRComment;\nconst RRCDATASection = BaseRRCDATASection;\nfunction getValidTagName(element) {\n if (element instanceof HTMLFormElement) {\n return \"FORM\";\n }\n return element.tagName.toUpperCase();\n}\nfunction buildFromNode(node, rrdom, domMirror, parentRRNode) {\n let rrNode;\n switch (node.nodeType) {\n case NodeType.DOCUMENT_NODE:\n if (parentRRNode && parentRRNode.nodeName === \"IFRAME\")\n rrNode = parentRRNode.contentDocument;\n else {\n rrNode = rrdom;\n rrNode.compatMode = node.compatMode;\n }\n break;\n case NodeType.DOCUMENT_TYPE_NODE: {\n const documentType = node;\n rrNode = rrdom.createDocumentType(\n documentType.name,\n documentType.publicId,\n documentType.systemId\n );\n break;\n }\n case NodeType.ELEMENT_NODE: {\n const elementNode = node;\n const tagName = getValidTagName(elementNode);\n rrNode = rrdom.createElement(tagName);\n const rrElement = rrNode;\n for (const { name, value } of Array.from(elementNode.attributes)) {\n rrElement.attributes[name] = value;\n }\n elementNode.scrollLeft && (rrElement.scrollLeft = elementNode.scrollLeft);\n elementNode.scrollTop && (rrElement.scrollTop = elementNode.scrollTop);\n break;\n }\n case NodeType.TEXT_NODE:\n rrNode = rrdom.createTextNode(node.textContent || \"\");\n break;\n case NodeType.CDATA_SECTION_NODE:\n rrNode = rrdom.createCDATASection(node.data);\n break;\n case NodeType.COMMENT_NODE:\n rrNode = rrdom.createComment(node.textContent || \"\");\n break;\n case NodeType.DOCUMENT_FRAGMENT_NODE:\n rrNode = parentRRNode.attachShadow({ mode: \"open\" });\n break;\n default:\n return null;\n }\n let sn = domMirror.getMeta(node);\n if (rrdom instanceof RRDocument) {\n if (!sn) {\n sn = getDefaultSN(rrNode, rrdom.unserializedId);\n domMirror.add(node, sn);\n }\n rrdom.mirror.add(rrNode, { ...sn });\n }\n return rrNode;\n}\nfunction buildFromDom(dom, domMirror = createMirror$1(), rrdom = new RRDocument()) {\n function walk2(node, parentRRNode) {\n const rrNode = buildFromNode(node, rrdom, domMirror, parentRRNode);\n if (rrNode === null) return;\n if (\n // if the parentRRNode isn't a RRIFrameElement\n parentRRNode?.nodeName !== \"IFRAME\" && // if node isn't a shadow root\n node.nodeType !== NodeType.DOCUMENT_FRAGMENT_NODE\n ) {\n parentRRNode?.appendChild(rrNode);\n rrNode.parentNode = parentRRNode;\n rrNode.parentElement = parentRRNode;\n }\n if (node.nodeName === \"IFRAME\") {\n const iframeDoc = getIFrameContentDocument(node);\n iframeDoc && walk2(iframeDoc, rrNode);\n } else if (node.nodeType === NodeType.DOCUMENT_NODE || node.nodeType === NodeType.ELEMENT_NODE || node.nodeType === NodeType.DOCUMENT_FRAGMENT_NODE) {\n if (node.nodeType === NodeType.ELEMENT_NODE && node.shadowRoot)\n walk2(node.shadowRoot, rrNode);\n node.childNodes.forEach((childNode) => walk2(childNode, rrNode));\n }\n }\n walk2(dom, null);\n return rrdom;\n}\nfunction createMirror() {\n return new Mirror22();\n}\nclass Mirror22 {\n constructor() {\n __publicField(this, \"idNodeMap\", /* @__PURE__ */ new Map());\n __publicField(this, \"nodeMetaMap\", /* @__PURE__ */ new WeakMap());\n }\n getId(n2) {\n if (!n2) return -1;\n const id = this.getMeta(n2)?.id;\n return id ?? -1;\n }\n getNode(id) {\n return this.idNodeMap.get(id) || null;\n }\n getIds() {\n return Array.from(this.idNodeMap.keys());\n }\n getMeta(n2) {\n return this.nodeMetaMap.get(n2) || null;\n }\n // removes the node from idNodeMap\n // doesn't remove the node from nodeMetaMap\n removeNodeFromMap(n2) {\n const id = this.getId(n2);\n this.idNodeMap.delete(id);\n if (n2.childNodes) {\n n2.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));\n }\n }\n has(id) {\n return this.idNodeMap.has(id);\n }\n hasNode(node) {\n return this.nodeMetaMap.has(node);\n }\n add(n2, meta) {\n const id = meta.id;\n this.idNodeMap.set(id, n2);\n this.nodeMetaMap.set(n2, meta);\n }\n replace(id, n2) {\n const oldNode = this.getNode(id);\n if (oldNode) {\n const meta = this.nodeMetaMap.get(oldNode);\n if (meta) this.nodeMetaMap.set(n2, meta);\n }\n this.idNodeMap.set(id, n2);\n }\n reset() {\n this.idNodeMap = /* @__PURE__ */ new Map();\n this.nodeMetaMap = /* @__PURE__ */ new WeakMap();\n }\n}\nfunction getDefaultSN(node, id) {\n switch (node.RRNodeType) {\n case NodeType$1.Document:\n return {\n id,\n type: node.RRNodeType,\n childNodes: []\n };\n case NodeType$1.DocumentType: {\n const doctype = node;\n return {\n id,\n type: node.RRNodeType,\n name: doctype.name,\n publicId: doctype.publicId,\n systemId: doctype.systemId\n };\n }\n case NodeType$1.Element:\n return {\n id,\n type: node.RRNodeType,\n tagName: node.tagName.toLowerCase(),\n // In rrweb data, all tagNames are lowercase.\n attributes: {},\n childNodes: []\n };\n case NodeType$1.Text:\n return {\n id,\n type: node.RRNodeType,\n textContent: node.textContent || \"\"\n };\n case NodeType$1.Comment:\n return {\n id,\n type: node.RRNodeType,\n textContent: node.textContent || \"\"\n };\n case NodeType$1.CDATA:\n return {\n id,\n type: node.RRNodeType,\n textContent: \"\"\n };\n }\n}\nfunction isNodeInLinkedList(n2) {\n return \"__ln\" in n2;\n}\nclass DoubleLinkedList {\n constructor() {\n this.length = 0;\n this.head = null;\n this.tail = null;\n }\n get(position) {\n if (position >= this.length) {\n throw new Error(\"Position outside of list range\");\n }\n let current = this.head;\n for (let index = 0; index < position; index++) {\n current = current?.next || null;\n }\n return current;\n }\n addNode(n2) {\n const node = {\n value: n2,\n previous: null,\n next: null\n };\n n2.__ln = node;\n if (n2.previousSibling && isNodeInLinkedList(n2.previousSibling)) {\n const current = n2.previousSibling.__ln.next;\n node.next = current;\n node.previous = n2.previousSibling.__ln;\n n2.previousSibling.__ln.next = node;\n if (current) {\n current.previous = node;\n }\n } else if (n2.nextSibling && isNodeInLinkedList(n2.nextSibling) && n2.nextSibling.__ln.previous) {\n const current = n2.nextSibling.__ln.previous;\n node.previous = current;\n node.next = n2.nextSibling.__ln;\n n2.nextSibling.__ln.previous = node;\n if (current) {\n current.next = node;\n }\n } else {\n if (this.head) {\n this.head.previous = node;\n }\n node.next = this.head;\n this.head = node;\n }\n if (node.next === null) {\n this.tail = node;\n }\n this.length++;\n }\n removeNode(n2) {\n const current = n2.__ln;\n if (!this.head) {\n return;\n }\n if (!current.previous) {\n this.head = current.next;\n if (this.head) {\n this.head.previous = null;\n } else {\n this.tail = null;\n }\n } else {\n current.previous.next = current.next;\n if (current.next) {\n current.next.previous = current.previous;\n } else {\n this.tail = current.previous;\n }\n }\n if (n2.__ln) {\n delete n2.__ln;\n }\n this.length--;\n }\n}\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\nclass MutationBuffer {\n constructor() {\n this.frozen = false;\n this.locked = false;\n this.texts = [];\n this.attributes = [];\n this.attributeMap = /* @__PURE__ */ new WeakMap();\n this.removes = [];\n this.mapRemoves = [];\n this.movedMap = {};\n this.addedSet = /* @__PURE__ */ new Set();\n this.movedSet = /* @__PURE__ */ new Set();\n this.droppedSet = /* @__PURE__ */ new Set();\n this.processMutations = (mutations) => {\n mutations.forEach(this.processMutation);\n this.emit();\n };\n this.emit = () => {\n if (this.frozen || this.locked) {\n return;\n }\n const adds = [];\n const addedIds = /* @__PURE__ */ new Set();\n const addList = new DoubleLinkedList();\n const getNextId = (n2) => {\n let ns = n2;\n let nextId = IGNORED_NODE;\n while (nextId === IGNORED_NODE) {\n ns = ns && ns.nextSibling;\n nextId = ns && this.mirror.getId(ns);\n }\n return nextId;\n };\n const pushAdd = (n2) => {\n if (!n2.parentNode || !inDom(n2)) {\n return;\n }\n const parentId = isShadowRoot(n2.parentNode) ? this.mirror.getId(getShadowHost(n2)) : this.mirror.getId(n2.parentNode);\n const nextId = getNextId(n2);\n if (parentId === -1 || nextId === -1) {\n return addList.addNode(n2);\n }\n const sn = serializeNodeWithId(n2, {\n doc: this.doc,\n mirror: this.mirror,\n blockClass: this.blockClass,\n blockSelector: this.blockSelector,\n maskAllText: this.maskAllText,\n unblockSelector: this.unblockSelector,\n maskTextClass: this.maskTextClass,\n unmaskTextClass: this.unmaskTextClass,\n maskTextSelector: this.maskTextSelector,\n unmaskTextSelector: this.unmaskTextSelector,\n skipChild: true,\n newlyAddedElement: true,\n inlineStylesheet: this.inlineStylesheet,\n maskInputOptions: this.maskInputOptions,\n maskAttributeFn: this.maskAttributeFn,\n maskTextFn: this.maskTextFn,\n maskInputFn: this.maskInputFn,\n slimDOMOptions: this.slimDOMOptions,\n dataURLOptions: this.dataURLOptions,\n recordCanvas: this.recordCanvas,\n inlineImages: this.inlineImages,\n onSerialize: (currentN) => {\n if (isSerializedIframe(currentN, this.mirror) && !isBlocked(\n currentN,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n false\n )) {\n this.iframeManager.addIframe(currentN);\n }\n if (isSerializedStylesheet(currentN, this.mirror)) {\n this.stylesheetManager.trackLinkElement(\n currentN\n );\n }\n if (hasShadowRoot(n2)) {\n this.shadowDomManager.addShadowRoot(n2.shadowRoot, this.doc);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n if (isBlocked(\n iframe,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n false\n )) {\n return;\n }\n this.iframeManager.attachIframe(iframe, childSn);\n if (iframe.contentWindow) {\n this.canvasManager.addWindow(iframe.contentWindow);\n }\n this.shadowDomManager.observeAttachShadow(iframe);\n },\n onStylesheetLoad: (link, childSn) => {\n this.stylesheetManager.attachLinkElement(link, childSn);\n },\n onBlockedImageLoad: (_imageEl, serializedNode, { width, height }) => {\n this.mutationCb({\n adds: [],\n removes: [],\n texts: [],\n attributes: [\n {\n id: serializedNode.id,\n attributes: {\n style: {\n width: `${width}px`,\n height: `${height}px`\n }\n }\n }\n ]\n });\n },\n ignoreCSSAttributes: this.ignoreCSSAttributes\n });\n if (sn) {\n adds.push({\n parentId,\n nextId,\n node: sn\n });\n addedIds.add(sn.id);\n }\n };\n while (this.mapRemoves.length) {\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\n }\n for (const n2 of this.movedSet) {\n if (isParentRemoved(this.removes, n2, this.mirror) && !this.movedSet.has(n2.parentNode)) {\n continue;\n }\n pushAdd(n2);\n }\n for (const n2 of this.addedSet) {\n if (!isAncestorInSet(this.droppedSet, n2) && !isParentRemoved(this.removes, n2, this.mirror)) {\n pushAdd(n2);\n } else if (isAncestorInSet(this.movedSet, n2)) {\n pushAdd(n2);\n } else {\n this.droppedSet.add(n2);\n }\n }\n let candidate = null;\n while (addList.length) {\n let node = null;\n if (candidate) {\n const parentId = this.mirror.getId(candidate.value.parentNode);\n const nextId = getNextId(candidate.value);\n if (parentId !== -1 && nextId !== -1) {\n node = candidate;\n }\n }\n if (!node) {\n let tailNode = addList.tail;\n while (tailNode) {\n const _node = tailNode;\n tailNode = tailNode.previous;\n if (_node) {\n const parentId = this.mirror.getId(_node.value.parentNode);\n const nextId = getNextId(_node.value);\n if (nextId === -1) continue;\n else if (parentId !== -1) {\n node = _node;\n break;\n } else {\n const unhandledNode = _node.value;\n if (unhandledNode.parentNode && unhandledNode.parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {\n const shadowHost = unhandledNode.parentNode.host;\n const parentId2 = this.mirror.getId(shadowHost);\n if (parentId2 !== -1) {\n node = _node;\n break;\n }\n }\n }\n }\n }\n }\n if (!node) {\n while (addList.head) {\n addList.removeNode(addList.head.value);\n }\n break;\n }\n candidate = node.previous;\n addList.removeNode(node.value);\n pushAdd(node.value);\n }\n const payload = {\n texts: this.texts.map((text) => ({\n id: this.mirror.getId(text.node),\n value: text.value\n })).filter((text) => !addedIds.has(text.id)).filter((text) => this.mirror.has(text.id)),\n attributes: this.attributes.map((attribute) => {\n const { attributes } = attribute;\n if (typeof attributes.style === \"string\") {\n const diffAsStr = JSON.stringify(attribute.styleDiff);\n const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\n if (diffAsStr.length < attributes.style.length) {\n if ((diffAsStr + unchangedAsStr).split(\"var(\").length === attributes.style.split(\"var(\").length) {\n attributes.style = attribute.styleDiff;\n }\n }\n }\n return {\n id: this.mirror.getId(attribute.node),\n attributes\n };\n }).filter((attribute) => !addedIds.has(attribute.id)).filter((attribute) => this.mirror.has(attribute.id)),\n removes: this.removes,\n adds\n };\n if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) {\n return;\n }\n this.texts = [];\n this.attributes = [];\n this.attributeMap = /* @__PURE__ */ new WeakMap();\n this.removes = [];\n this.addedSet = /* @__PURE__ */ new Set();\n this.movedSet = /* @__PURE__ */ new Set();\n this.droppedSet = /* @__PURE__ */ new Set();\n this.movedMap = {};\n this.mutationCb(payload);\n };\n this.processMutation = (m) => {\n if (isIgnored(m.target, this.mirror)) {\n return;\n }\n switch (m.type) {\n case \"characterData\": {\n const value = m.target.textContent;\n if (!isBlocked(\n m.target,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n false\n ) && value !== m.oldValue) {\n this.texts.push({\n value: needMaskingText(\n m.target,\n this.maskTextClass,\n this.maskTextSelector,\n this.unmaskTextClass,\n this.unmaskTextSelector,\n this.maskAllText\n ) && value ? this.maskTextFn ? this.maskTextFn(value, closestElementOfNode(m.target)) : value.replace(/[\\S]/g, \"*\") : value,\n node: m.target\n });\n }\n break;\n }\n case \"attributes\": {\n const target = m.target;\n let attributeName = m.attributeName;\n let value = m.target.getAttribute(attributeName);\n if (attributeName === \"value\") {\n const type = getInputType(target);\n const tagName = target.tagName;\n value = getInputValue(target, tagName, type);\n const isInputMasked = shouldMaskInput({\n maskInputOptions: this.maskInputOptions,\n tagName,\n type\n });\n const forceMask = needMaskingText(\n m.target,\n this.maskTextClass,\n this.maskTextSelector,\n this.unmaskTextClass,\n this.unmaskTextSelector,\n isInputMasked\n );\n value = maskInputValue({\n isMasked: forceMask,\n element: target,\n value,\n maskInputFn: this.maskInputFn\n });\n }\n if (isBlocked(\n m.target,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n false\n ) || value === m.oldValue) {\n return;\n }\n let item = this.attributeMap.get(m.target);\n if (target.tagName === \"IFRAME\" && attributeName === \"src\" && !this.keepIframeSrcFn(value)) {\n const iframeDoc = getIFrameContentDocument(\n target\n );\n if (!iframeDoc) {\n attributeName = \"rr_src\";\n } else {\n return;\n }\n }\n if (!item) {\n item = {\n node: m.target,\n attributes: {},\n styleDiff: {},\n _unchangedStyles: {}\n };\n this.attributes.push(item);\n this.attributeMap.set(m.target, item);\n }\n if (attributeName === \"type\" && target.tagName === \"INPUT\" && (m.oldValue || \"\").toLowerCase() === \"password\") {\n target.setAttribute(\"data-rr-is-password\", \"true\");\n }\n if (!ignoreAttribute(target.tagName, attributeName)) {\n item.attributes[attributeName] = transformAttribute(\n this.doc,\n toLowerCase(target.tagName),\n toLowerCase(attributeName),\n value,\n target,\n this.maskAttributeFn\n );\n if (attributeName === \"style\") {\n if (!this.unattachedDoc) {\n try {\n this.unattachedDoc = document.implementation.createHTMLDocument();\n } catch (e2) {\n this.unattachedDoc = this.doc;\n }\n }\n const old = this.unattachedDoc.createElement(\"span\");\n if (m.oldValue) {\n old.setAttribute(\"style\", m.oldValue);\n }\n for (const pname of Array.from(target.style)) {\n const newValue = target.style.getPropertyValue(pname);\n const newPriority = target.style.getPropertyPriority(pname);\n if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) {\n if (newPriority === \"\") {\n item.styleDiff[pname] = newValue;\n } else {\n item.styleDiff[pname] = [newValue, newPriority];\n }\n } else {\n item._unchangedStyles[pname] = [newValue, newPriority];\n }\n }\n for (const pname of Array.from(old.style)) {\n if (target.style.getPropertyValue(pname) === \"\") {\n item.styleDiff[pname] = false;\n }\n }\n }\n }\n break;\n }\n case \"childList\": {\n if (isBlocked(\n m.target,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n true\n )) {\n return;\n }\n m.addedNodes.forEach((n2) => this.genAdds(n2, m.target));\n m.removedNodes.forEach((n2) => {\n const nodeId = this.mirror.getId(n2);\n const parentId = isShadowRoot(m.target) ? this.mirror.getId(m.target.host) : this.mirror.getId(m.target);\n if (isBlocked(\n m.target,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n false\n ) || isIgnored(n2, this.mirror) || !isSerialized(n2, this.mirror)) {\n return;\n }\n if (this.addedSet.has(n2)) {\n deepDelete(this.addedSet, n2);\n this.droppedSet.add(n2);\n } else if (this.addedSet.has(m.target) && nodeId === -1) ;\n else if (isAncestorRemoved(m.target, this.mirror)) ;\n else if (this.movedSet.has(n2) && this.movedMap[moveKey(nodeId, parentId)]) {\n deepDelete(this.movedSet, n2);\n } else {\n this.removes.push({\n parentId,\n id: nodeId,\n isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0\n });\n }\n this.mapRemoves.push(n2);\n });\n break;\n }\n }\n };\n this.genAdds = (n2, target) => {\n if (this.processedNodeManager.inOtherBuffer(n2, this)) return;\n if (this.addedSet.has(n2) || this.movedSet.has(n2)) return;\n if (this.mirror.hasNode(n2)) {\n if (isIgnored(n2, this.mirror)) {\n return;\n }\n this.movedSet.add(n2);\n let targetId = null;\n if (target && this.mirror.hasNode(target)) {\n targetId = this.mirror.getId(target);\n }\n if (targetId && targetId !== -1) {\n this.movedMap[moveKey(this.mirror.getId(n2), targetId)] = true;\n }\n } else {\n this.addedSet.add(n2);\n this.droppedSet.delete(n2);\n }\n if (!isBlocked(\n n2,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n false\n )) {\n if (n2.childNodes) {\n n2.childNodes.forEach((childN) => this.genAdds(childN));\n }\n if (hasShadowRoot(n2)) {\n n2.shadowRoot.childNodes.forEach((childN) => {\n this.processedNodeManager.add(childN, this);\n this.genAdds(childN, n2);\n });\n }\n }\n };\n }\n init(options) {\n [\n \"mutationCb\",\n \"blockClass\",\n \"blockSelector\",\n \"unblockSelector\",\n \"maskAllText\",\n \"maskTextClass\",\n \"unmaskTextClass\",\n \"maskTextSelector\",\n \"unmaskTextSelector\",\n \"inlineStylesheet\",\n \"maskInputOptions\",\n \"maskAttributeFn\",\n \"maskTextFn\",\n \"maskInputFn\",\n \"keepIframeSrcFn\",\n \"recordCanvas\",\n \"inlineImages\",\n \"slimDOMOptions\",\n \"dataURLOptions\",\n \"doc\",\n \"mirror\",\n \"iframeManager\",\n \"stylesheetManager\",\n \"shadowDomManager\",\n \"canvasManager\",\n \"processedNodeManager\",\n \"ignoreCSSAttributes\"\n ].forEach((key) => {\n this[key] = options[key];\n });\n }\n freeze() {\n this.frozen = true;\n this.canvasManager.freeze();\n }\n unfreeze() {\n this.frozen = false;\n this.canvasManager.unfreeze();\n this.emit();\n }\n isFrozen() {\n return this.frozen;\n }\n lock() {\n this.locked = true;\n this.canvasManager.lock();\n }\n unlock() {\n this.locked = false;\n this.canvasManager.unlock();\n this.emit();\n }\n reset() {\n this.shadowDomManager.reset();\n this.canvasManager.reset();\n }\n}\nfunction deepDelete(addsSet, n2) {\n addsSet.delete(n2);\n n2.childNodes?.forEach((childN) => deepDelete(addsSet, childN));\n}\nfunction isParentRemoved(removes, n2, mirror2) {\n if (removes.length === 0) return false;\n return _isParentRemoved(removes, n2, mirror2);\n}\nfunction _isParentRemoved(removes, n2, mirror2) {\n let node = n2.parentNode;\n while (node) {\n const parentId = mirror2.getId(node);\n if (removes.some((r2) => r2.id === parentId)) {\n return true;\n }\n node = node.parentNode;\n }\n return false;\n}\nfunction isAncestorInSet(set, n2) {\n if (set.size === 0) return false;\n return _isAncestorInSet(set, n2);\n}\nfunction _isAncestorInSet(set, n2) {\n const { parentNode } = n2;\n if (!parentNode) {\n return false;\n }\n if (set.has(parentNode)) {\n return true;\n }\n return _isAncestorInSet(set, parentNode);\n}\nlet errorHandler;\nfunction registerErrorHandler(handler) {\n errorHandler = handler;\n}\nfunction unregisterErrorHandler() {\n errorHandler = void 0;\n}\nconst callbackWrapper = (cb) => {\n if (!errorHandler) {\n return cb;\n }\n const rrwebWrapped = (...rest) => {\n try {\n return cb(...rest);\n } catch (error) {\n if (errorHandler && errorHandler(error) === true) {\n return () => {\n };\n }\n throw error;\n }\n };\n return rrwebWrapped;\n};\nconst mutationBuffers = [];\nfunction getEventTarget(event) {\n try {\n if (\"composedPath\" in event) {\n const path = event.composedPath();\n if (path.length) {\n return path[0];\n }\n } else if (\"path\" in event && event.path.length) {\n return event.path[0];\n }\n } catch {\n }\n return event && event.target;\n}\nfunction initMutationObserver(options, rootEl) {\n const mutationBuffer = new MutationBuffer();\n mutationBuffers.push(mutationBuffer);\n mutationBuffer.init(options);\n let mutationObserverCtor = window.MutationObserver || /**\n * Some websites may disable MutationObserver by removing it from the window object.\n * If someone is using rrweb to build a browser extention or things like it, they\n * could not change the website's code but can have an opportunity to inject some\n * code before the website executing its JS logic.\n * Then they can do this to store the native MutationObserver:\n * window.__rrMutationObserver = MutationObserver\n */\n window.__rrMutationObserver;\n const angularZoneSymbol = window?.Zone?.__symbol__?.(\"MutationObserver\");\n if (angularZoneSymbol && window[angularZoneSymbol]) {\n mutationObserverCtor = window[angularZoneSymbol];\n }\n const observer = new mutationObserverCtor(\n callbackWrapper((mutations) => {\n if (options.onMutation && options.onMutation(mutations) === false) {\n return;\n }\n mutationBuffer.processMutations.bind(mutationBuffer)(mutations);\n })\n );\n observer.observe(rootEl, {\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true\n });\n return observer;\n}\nfunction initMoveObserver({\n mousemoveCb,\n sampling,\n doc,\n mirror: mirror2\n}) {\n if (sampling.mousemove === false) {\n return () => {\n };\n }\n const threshold = typeof sampling.mousemove === \"number\" ? sampling.mousemove : 50;\n const callbackThreshold = typeof sampling.mousemoveCallback === \"number\" ? sampling.mousemoveCallback : 500;\n let positions = [];\n let timeBaseline;\n const wrappedCb = throttle(\n callbackWrapper(\n (source) => {\n const totalOffset = Date.now() - timeBaseline;\n mousemoveCb(\n positions.map((p) => {\n p.timeOffset -= totalOffset;\n return p;\n }),\n source\n );\n positions = [];\n timeBaseline = null;\n }\n ),\n callbackThreshold\n );\n const updatePosition = callbackWrapper(\n throttle(\n callbackWrapper((evt) => {\n const target = getEventTarget(evt);\n const { clientX, clientY } = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt;\n if (!timeBaseline) {\n timeBaseline = nowTimestamp();\n }\n positions.push({\n x: clientX,\n y: clientY,\n id: mirror2.getId(target),\n timeOffset: nowTimestamp() - timeBaseline\n });\n wrappedCb(\n typeof DragEvent !== \"undefined\" && evt instanceof DragEvent ? IncrementalSource.Drag : evt instanceof MouseEvent ? IncrementalSource.MouseMove : IncrementalSource.TouchMove\n );\n }),\n threshold,\n {\n trailing: false\n }\n )\n );\n const handlers = [\n on(\"mousemove\", updatePosition, doc),\n on(\"touchmove\", updatePosition, doc),\n on(\"drag\", updatePosition, doc)\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initMouseInteractionObserver({\n mouseInteractionCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n sampling\n}) {\n if (sampling.mouseInteraction === false) {\n return () => {\n };\n }\n const disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;\n const handlers = [];\n let currentPointerType = null;\n const getHandler = (eventKey) => {\n return (event) => {\n const target = getEventTarget(event);\n if (isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\n return;\n }\n let pointerType = null;\n let thisEventKey = eventKey;\n if (\"pointerType\" in event) {\n switch (event.pointerType) {\n case \"mouse\":\n pointerType = PointerTypes.Mouse;\n break;\n case \"touch\":\n pointerType = PointerTypes.Touch;\n break;\n case \"pen\":\n pointerType = PointerTypes.Pen;\n break;\n }\n if (pointerType === PointerTypes.Touch) {\n if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\n thisEventKey = \"TouchStart\";\n } else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\n thisEventKey = \"TouchEnd\";\n }\n } else if (pointerType === PointerTypes.Pen) ;\n } else if (legacy_isTouchEvent(event)) {\n pointerType = PointerTypes.Touch;\n }\n if (pointerType !== null) {\n currentPointerType = pointerType;\n if (thisEventKey.startsWith(\"Touch\") && pointerType === PointerTypes.Touch || thisEventKey.startsWith(\"Mouse\") && pointerType === PointerTypes.Mouse) {\n pointerType = null;\n }\n } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\n pointerType = currentPointerType;\n currentPointerType = null;\n }\n const e2 = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\n if (!e2) {\n return;\n }\n const id = mirror2.getId(target);\n const { clientX, clientY } = e2;\n callbackWrapper(mouseInteractionCb)({\n type: MouseInteractions[thisEventKey],\n id,\n x: clientX,\n y: clientY,\n ...pointerType !== null && { pointerType }\n });\n };\n };\n Object.keys(MouseInteractions).filter(\n (key) => Number.isNaN(Number(key)) && !key.endsWith(\"_Departed\") && disableMap[key] !== false\n ).forEach((eventKey) => {\n let eventName = toLowerCase(eventKey);\n const handler = getHandler(eventKey);\n if (window.PointerEvent) {\n switch (MouseInteractions[eventKey]) {\n case MouseInteractions.MouseDown:\n case MouseInteractions.MouseUp:\n eventName = eventName.replace(\n \"mouse\",\n \"pointer\"\n );\n break;\n case MouseInteractions.TouchStart:\n case MouseInteractions.TouchEnd:\n return;\n }\n }\n handlers.push(on(eventName, handler, doc));\n });\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initScrollObserver({\n scrollCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n sampling\n}) {\n const updatePosition = callbackWrapper(\n throttle(\n callbackWrapper((evt) => {\n const target = getEventTarget(evt);\n if (!target || isBlocked(\n target,\n blockClass,\n blockSelector,\n unblockSelector,\n true\n )) {\n return;\n }\n const id = mirror2.getId(target);\n if (target === doc && doc.defaultView) {\n const scrollLeftTop = getWindowScroll(doc.defaultView);\n scrollCb({\n id,\n x: scrollLeftTop.left,\n y: scrollLeftTop.top\n });\n } else {\n scrollCb({\n id,\n x: target.scrollLeft,\n y: target.scrollTop\n });\n }\n }),\n sampling.scroll || 100\n )\n );\n return on(\"scroll\", updatePosition, doc);\n}\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\n let lastH = -1;\n let lastW = -1;\n const updateDimension = callbackWrapper(\n throttle(\n callbackWrapper(() => {\n const height = getWindowHeight();\n const width = getWindowWidth();\n if (lastH !== height || lastW !== width) {\n viewportResizeCb({\n width: Number(width),\n height: Number(height)\n });\n lastH = height;\n lastW = width;\n }\n }),\n 200\n )\n );\n return on(\"resize\", updateDimension, win);\n}\nconst INPUT_TAGS = [\"INPUT\", \"TEXTAREA\", \"SELECT\"];\nconst lastInputValueMap = /* @__PURE__ */ new WeakMap();\nfunction initInputObserver({\n inputCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n ignoreClass,\n ignoreSelector,\n maskInputOptions,\n maskInputFn,\n sampling,\n userTriggeredOnInput,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector\n}) {\n function eventHandler(event) {\n let target = getEventTarget(event);\n const userTriggered = event.isTrusted;\n const tagName = target && toUpperCase(target.tagName);\n if (tagName === \"OPTION\") target = target.parentElement;\n if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked(\n target,\n blockClass,\n blockSelector,\n unblockSelector,\n true\n )) {\n return;\n }\n const el = target;\n if (el.classList.contains(ignoreClass) || ignoreSelector && el.matches(ignoreSelector)) {\n return;\n }\n const type = getInputType(target);\n let text = getInputValue(el, tagName, type);\n let isChecked = false;\n const isInputMasked = shouldMaskInput({\n maskInputOptions,\n tagName,\n type\n });\n const forceMask = needMaskingText(\n target,\n maskTextClass,\n maskTextSelector,\n unmaskTextClass,\n unmaskTextSelector,\n isInputMasked\n );\n if (type === \"radio\" || type === \"checkbox\") {\n isChecked = target.checked;\n }\n text = maskInputValue({\n isMasked: forceMask,\n element: target,\n value: text,\n maskInputFn\n });\n cbWithDedup(\n target,\n userTriggeredOnInput ? { text, isChecked, userTriggered } : { text, isChecked }\n );\n const name = target.name;\n if (type === \"radio\" && name && isChecked) {\n doc.querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`).forEach((el2) => {\n if (el2 !== target) {\n const text2 = maskInputValue({\n // share mask behavior of `target`\n isMasked: forceMask,\n element: el2,\n value: getInputValue(el2, tagName, type),\n maskInputFn\n });\n cbWithDedup(\n el2,\n userTriggeredOnInput ? { text: text2, isChecked: !isChecked, userTriggered: false } : { text: text2, isChecked: !isChecked }\n );\n }\n });\n }\n }\n function cbWithDedup(target, v2) {\n const lastInputValue = lastInputValueMap.get(target);\n if (!lastInputValue || lastInputValue.text !== v2.text || lastInputValue.isChecked !== v2.isChecked) {\n lastInputValueMap.set(target, v2);\n const id = mirror2.getId(target);\n callbackWrapper(inputCb)({\n ...v2,\n id\n });\n }\n }\n const events = sampling.input === \"last\" ? [\"change\"] : [\"input\", \"change\"];\n const handlers = events.map(\n (eventName) => on(eventName, callbackWrapper(eventHandler), doc)\n );\n const currentWindow = doc.defaultView;\n if (!currentWindow) {\n return () => {\n handlers.forEach((h) => h());\n };\n }\n const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(\n currentWindow.HTMLInputElement.prototype,\n \"value\"\n );\n const hookProperties = [\n [currentWindow.HTMLInputElement.prototype, \"value\"],\n [currentWindow.HTMLInputElement.prototype, \"checked\"],\n [currentWindow.HTMLSelectElement.prototype, \"value\"],\n [currentWindow.HTMLTextAreaElement.prototype, \"value\"],\n // Some UI library use selectedIndex to set select value\n [currentWindow.HTMLSelectElement.prototype, \"selectedIndex\"],\n [currentWindow.HTMLOptionElement.prototype, \"selected\"]\n ];\n if (propertyDescriptor && propertyDescriptor.set) {\n handlers.push(\n ...hookProperties.map(\n (p) => hookSetter(\n p[0],\n p[1],\n {\n set() {\n callbackWrapper(eventHandler)({\n target: this,\n isTrusted: false\n // userTriggered to false as this could well be programmatic\n });\n }\n },\n false,\n currentWindow\n )\n )\n );\n }\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction getNestedCSSRulePositions(rule) {\n const positions = [];\n function recurse(childRule, pos) {\n if (hasNestedCSSRule(\"CSSGroupingRule\") && childRule.parentRule instanceof CSSGroupingRule || hasNestedCSSRule(\"CSSMediaRule\") && childRule.parentRule instanceof CSSMediaRule || hasNestedCSSRule(\"CSSSupportsRule\") && childRule.parentRule instanceof CSSSupportsRule || hasNestedCSSRule(\"CSSConditionRule\") && childRule.parentRule instanceof CSSConditionRule) {\n const rules2 = Array.from(\n childRule.parentRule.cssRules\n );\n const index = rules2.indexOf(childRule);\n pos.unshift(index);\n } else if (childRule.parentStyleSheet) {\n const rules2 = Array.from(childRule.parentStyleSheet.cssRules);\n const index = rules2.indexOf(childRule);\n pos.unshift(index);\n }\n return pos;\n }\n return recurse(rule, positions);\n}\nfunction getIdAndStyleId(sheet, mirror2, styleMirror) {\n let id, styleId;\n if (!sheet) return {};\n if (sheet.ownerNode) id = mirror2.getId(sheet.ownerNode);\n else styleId = styleMirror.getId(sheet);\n return {\n styleId,\n id\n };\n}\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror: mirror2, stylesheetManager }, { win }) {\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\n return () => {\n };\n }\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n adds: [{ rule, index }]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n removes: [{ index }]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n let replace;\n if (win.CSSStyleSheet.prototype.replace) {\n replace = win.CSSStyleSheet.prototype.replace;\n win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n replace: text\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n }\n let replaceSync;\n if (win.CSSStyleSheet.prototype.replaceSync) {\n replaceSync = win.CSSStyleSheet.prototype.replaceSync;\n win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n replaceSync: text\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n }\n const supportedNestedCSSRuleTypes = {};\n if (canMonkeyPatchNestedCSSRule(\"CSSGroupingRule\")) {\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n } else {\n if (canMonkeyPatchNestedCSSRule(\"CSSMediaRule\")) {\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\n }\n if (canMonkeyPatchNestedCSSRule(\"CSSConditionRule\")) {\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\n }\n if (canMonkeyPatchNestedCSSRule(\"CSSSupportsRule\")) {\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\n }\n }\n const unmodifiedFunctions = {};\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n unmodifiedFunctions[typeKey] = {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n insertRule: type.prototype.insertRule,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n deleteRule: type.prototype.deleteRule\n };\n type.prototype.insertRule = new Proxy(\n unmodifiedFunctions[typeKey].insertRule,\n {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n adds: [\n {\n rule,\n index: [\n ...getNestedCSSRulePositions(thisArg),\n index || 0\n // defaults to 0\n ]\n }\n ]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n }\n );\n type.prototype.deleteRule = new Proxy(\n unmodifiedFunctions[typeKey].deleteRule,\n {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n removes: [\n { index: [...getNestedCSSRulePositions(thisArg), index] }\n ]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n }\n );\n });\n return callbackWrapper(() => {\n win.CSSStyleSheet.prototype.insertRule = insertRule;\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\n replace && (win.CSSStyleSheet.prototype.replace = replace);\n replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\n });\n });\n}\nfunction initAdoptedStyleSheetObserver({\n mirror: mirror2,\n stylesheetManager\n}, host) {\n let hostId = null;\n if (host.nodeName === \"#document\") hostId = mirror2.getId(host);\n else hostId = mirror2.getId(host.host);\n const patchTarget = host.nodeName === \"#document\" ? host.defaultView?.Document : host.ownerDocument?.defaultView?.ShadowRoot;\n const originalPropertyDescriptor = patchTarget?.prototype ? Object.getOwnPropertyDescriptor(\n patchTarget?.prototype,\n \"adoptedStyleSheets\"\n ) : void 0;\n if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor)\n return () => {\n };\n Object.defineProperty(host, \"adoptedStyleSheets\", {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n get() {\n return originalPropertyDescriptor.get?.call(this);\n },\n set(sheets) {\n const result = originalPropertyDescriptor.set?.call(this, sheets);\n if (hostId !== null && hostId !== -1) {\n try {\n stylesheetManager.adoptStyleSheets(sheets, hostId);\n } catch (e2) {\n }\n }\n return result;\n }\n });\n return callbackWrapper(() => {\n Object.defineProperty(host, \"adoptedStyleSheets\", {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n get: originalPropertyDescriptor.get,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n set: originalPropertyDescriptor.set\n });\n });\n}\nfunction initStyleDeclarationObserver({\n styleDeclarationCb,\n mirror: mirror2,\n ignoreCSSAttributes,\n stylesheetManager\n}, { win }) {\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [property, value, priority] = argumentsList;\n if (ignoreCSSAttributes.has(property)) {\n return setProperty.apply(thisArg, [property, value, priority]);\n }\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentRule?.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleDeclarationCb({\n id,\n styleId,\n set: {\n property,\n value,\n priority\n },\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n index: getNestedCSSRulePositions(thisArg.parentRule)\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [property] = argumentsList;\n if (ignoreCSSAttributes.has(property)) {\n return removeProperty.apply(thisArg, [property]);\n }\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentRule?.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleDeclarationCb({\n id,\n styleId,\n remove: {\n property\n },\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n index: getNestedCSSRulePositions(thisArg.parentRule)\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n return callbackWrapper(() => {\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n });\n}\nfunction initMediaInteractionObserver({\n mediaInteractionCb,\n blockClass,\n blockSelector,\n unblockSelector,\n mirror: mirror2,\n sampling,\n doc\n}) {\n const handler = callbackWrapper(\n (type) => throttle(\n callbackWrapper((event) => {\n const target = getEventTarget(event);\n if (!target || isBlocked(\n target,\n blockClass,\n blockSelector,\n unblockSelector,\n true\n )) {\n return;\n }\n const { currentTime, volume, muted, playbackRate } = target;\n mediaInteractionCb({\n type,\n id: mirror2.getId(target),\n currentTime,\n volume,\n muted,\n playbackRate\n });\n }),\n sampling.media || 500\n )\n );\n const handlers = [\n on(\"play\", handler(MediaInteractions.Play), doc),\n on(\"pause\", handler(MediaInteractions.Pause), doc),\n on(\"seeked\", handler(MediaInteractions.Seeked), doc),\n on(\"volumechange\", handler(MediaInteractions.VolumeChange), doc),\n on(\"ratechange\", handler(MediaInteractions.RateChange), doc)\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initFontObserver({ fontCb, doc }) {\n const win = doc.defaultView;\n if (!win) {\n return () => {\n };\n }\n const handlers = [];\n const fontMap = /* @__PURE__ */ new WeakMap();\n const originalFontFace = win.FontFace;\n win.FontFace = function FontFace2(family, source, descriptors) {\n const fontFace = new originalFontFace(family, source, descriptors);\n fontMap.set(fontFace, {\n family,\n buffer: typeof source !== \"string\",\n descriptors,\n fontSource: typeof source === \"string\" ? source : JSON.stringify(Array.from(new Uint8Array(source)))\n });\n return fontFace;\n };\n const restoreHandler = patch(\n doc.fonts,\n \"add\",\n function(original) {\n return function(fontFace) {\n setTimeout$1(\n callbackWrapper(() => {\n const p = fontMap.get(fontFace);\n if (p) {\n fontCb(p);\n fontMap.delete(fontFace);\n }\n }),\n 0\n );\n return original.apply(this, [fontFace]);\n };\n }\n );\n handlers.push(() => {\n win.FontFace = originalFontFace;\n });\n handlers.push(restoreHandler);\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initSelectionObserver(param) {\n const {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n selectionCb\n } = param;\n let collapsed = true;\n const updateSelection = callbackWrapper(() => {\n const selection = doc.getSelection();\n if (!selection || collapsed && selection?.isCollapsed) return;\n collapsed = selection.isCollapsed || false;\n const ranges = [];\n const count = selection.rangeCount || 0;\n for (let i2 = 0; i2 < count; i2++) {\n const range = selection.getRangeAt(i2);\n const { startContainer, startOffset, endContainer, endOffset } = range;\n const blocked = isBlocked(\n startContainer,\n blockClass,\n blockSelector,\n unblockSelector,\n true\n ) || isBlocked(\n endContainer,\n blockClass,\n blockSelector,\n unblockSelector,\n true\n );\n if (blocked) continue;\n ranges.push({\n start: mirror2.getId(startContainer),\n startOffset,\n end: mirror2.getId(endContainer),\n endOffset\n });\n }\n selectionCb({ ranges });\n });\n updateSelection();\n return on(\"selectionchange\", updateSelection);\n}\nfunction initCustomElementObserver({\n doc,\n customElementCb\n}) {\n const win = doc.defaultView;\n if (!win || !win.customElements) return () => {\n };\n const restoreHandler = patch(\n win.customElements,\n \"define\",\n function(original) {\n return function(name, constructor, options) {\n try {\n customElementCb({\n define: {\n name\n }\n });\n } catch (e2) {\n }\n return original.apply(this, [name, constructor, options]);\n };\n }\n );\n return restoreHandler;\n}\nfunction initObservers(o2, _hooks = {}) {\n const currentWindow = o2.doc.defaultView;\n if (!currentWindow) {\n return () => {\n };\n }\n let mutationObserver;\n if (o2.recordDOM) {\n mutationObserver = initMutationObserver(o2, o2.doc);\n }\n const mousemoveHandler = initMoveObserver(o2);\n const mouseInteractionHandler = initMouseInteractionObserver(o2);\n const scrollHandler = initScrollObserver(o2);\n const viewportResizeHandler = initViewportResizeObserver(o2, {\n win: currentWindow\n });\n const inputHandler = initInputObserver(o2);\n const mediaInteractionHandler = initMediaInteractionObserver(o2);\n let styleSheetObserver = () => {\n };\n let adoptedStyleSheetObserver = () => {\n };\n let styleDeclarationObserver = () => {\n };\n let fontObserver = () => {\n };\n if (o2.recordDOM) {\n styleSheetObserver = initStyleSheetObserver(o2, { win: currentWindow });\n adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o2, o2.doc);\n styleDeclarationObserver = initStyleDeclarationObserver(o2, {\n win: currentWindow\n });\n if (o2.collectFonts) {\n fontObserver = initFontObserver(o2);\n }\n }\n const selectionObserver = initSelectionObserver(o2);\n const customElementObserver = initCustomElementObserver(o2);\n const pluginHandlers = [];\n for (const plugin of o2.plugins) {\n pluginHandlers.push(\n plugin.observer(plugin.callback, currentWindow, plugin.options)\n );\n }\n return callbackWrapper(() => {\n mutationBuffers.forEach((b) => b.reset());\n mutationObserver?.disconnect();\n mousemoveHandler();\n mouseInteractionHandler();\n scrollHandler();\n viewportResizeHandler();\n inputHandler();\n mediaInteractionHandler();\n styleSheetObserver();\n adoptedStyleSheetObserver();\n styleDeclarationObserver();\n fontObserver();\n selectionObserver();\n customElementObserver();\n pluginHandlers.forEach((h) => h());\n });\n}\nfunction hasNestedCSSRule(prop) {\n return typeof window[prop] !== \"undefined\";\n}\nfunction canMonkeyPatchNestedCSSRule(prop) {\n return Boolean(\n typeof window[prop] !== \"undefined\" && // Note: Generally, this check _shouldn't_ be necessary\n // However, in some scenarios (e.g. jsdom) this can sometimes fail, so we check for it here\n window[prop].prototype && \"insertRule\" in window[prop].prototype && \"deleteRule\" in window[prop].prototype\n );\n}\nclass CrossOriginIframeMirror {\n constructor(generateIdFn) {\n this.generateIdFn = generateIdFn;\n this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();\n this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();\n }\n getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {\n const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\n const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\n let id = idToRemoteIdMap.get(remoteId);\n if (!id) {\n id = this.generateIdFn();\n idToRemoteIdMap.set(remoteId, id);\n remoteIdToIdMap.set(id, remoteId);\n }\n return id;\n }\n getIds(iframe, remoteId) {\n const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n return remoteId.map(\n (id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap)\n );\n }\n getRemoteId(iframe, id, map) {\n const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\n if (typeof id !== \"number\") return id;\n const remoteId = remoteIdToIdMap.get(id);\n if (!remoteId) return -1;\n return remoteId;\n }\n getRemoteIds(iframe, ids) {\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\n }\n reset(iframe) {\n if (!iframe) {\n this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();\n this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();\n return;\n }\n this.iframeIdToRemoteIdMap.delete(iframe);\n this.iframeRemoteIdToIdMap.delete(iframe);\n }\n getIdToRemoteIdMap(iframe) {\n let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\n if (!idToRemoteIdMap) {\n idToRemoteIdMap = /* @__PURE__ */ new Map();\n this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\n }\n return idToRemoteIdMap;\n }\n getRemoteIdToIdMap(iframe) {\n let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\n if (!remoteIdToIdMap) {\n remoteIdToIdMap = /* @__PURE__ */ new Map();\n this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\n }\n return remoteIdToIdMap;\n }\n}\nclass IframeManagerNoop {\n constructor() {\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\n this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap();\n }\n addIframe() {\n }\n addLoadListener() {\n }\n attachIframe() {\n }\n}\nclass IframeManager {\n constructor(options) {\n this.iframes = /* @__PURE__ */ new WeakMap();\n this.crossOriginIframeMap = /* @__PURE__ */ new WeakMap();\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\n this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap();\n this.mutationCb = options.mutationCb;\n this.wrappedEmit = options.wrappedEmit;\n this.stylesheetManager = options.stylesheetManager;\n this.recordCrossOriginIframes = options.recordCrossOriginIframes;\n this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(\n this.stylesheetManager.styleMirror.generateId.bind(\n this.stylesheetManager.styleMirror\n )\n );\n this.mirror = options.mirror;\n if (this.recordCrossOriginIframes) {\n window.addEventListener(\"message\", this.handleMessage.bind(this));\n }\n }\n addIframe(iframeEl) {\n this.iframes.set(iframeEl, true);\n if (iframeEl.contentWindow)\n this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\n }\n addLoadListener(cb) {\n this.loadListener = cb;\n }\n attachIframe(iframeEl, childSn) {\n this.mutationCb({\n adds: [\n {\n parentId: this.mirror.getId(iframeEl),\n nextId: null,\n node: childSn\n }\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true\n });\n if (this.recordCrossOriginIframes)\n iframeEl.contentWindow?.addEventListener(\n \"message\",\n this.handleMessage.bind(this)\n );\n this.loadListener?.(iframeEl);\n const iframeDoc = getIFrameContentDocument(iframeEl);\n if (iframeDoc && iframeDoc.adoptedStyleSheets && iframeDoc.adoptedStyleSheets.length > 0)\n this.stylesheetManager.adoptStyleSheets(\n iframeDoc.adoptedStyleSheets,\n this.mirror.getId(iframeDoc)\n );\n }\n handleMessage(message) {\n const crossOriginMessageEvent = message;\n if (crossOriginMessageEvent.data.type !== \"rrweb\" || // To filter out the rrweb messages which are forwarded by some sites.\n crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\n return;\n const iframeSourceWindow = message.source;\n if (!iframeSourceWindow) return;\n const iframeEl = this.crossOriginIframeMap.get(message.source);\n if (!iframeEl) return;\n const transformedEvent = this.transformCrossOriginEvent(\n iframeEl,\n crossOriginMessageEvent.data.event\n );\n if (transformedEvent)\n this.wrappedEmit(\n transformedEvent,\n crossOriginMessageEvent.data.isCheckout\n );\n }\n transformCrossOriginEvent(iframeEl, e2) {\n switch (e2.type) {\n case EventType.FullSnapshot: {\n this.crossOriginIframeMirror.reset(iframeEl);\n this.crossOriginIframeStyleMirror.reset(iframeEl);\n this.replaceIdOnNode(e2.data.node, iframeEl);\n const rootId = e2.data.node.id;\n this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\n this.patchRootIdOnNode(e2.data.node, rootId);\n return {\n timestamp: e2.timestamp,\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Mutation,\n adds: [\n {\n parentId: this.mirror.getId(iframeEl),\n nextId: null,\n node: e2.data.node\n }\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true\n }\n };\n }\n case EventType.Meta:\n case EventType.Load:\n case EventType.DomContentLoaded: {\n return false;\n }\n case EventType.Plugin: {\n return e2;\n }\n case EventType.Custom: {\n this.replaceIds(\n e2.data.payload,\n iframeEl,\n [\"id\", \"parentId\", \"previousId\", \"nextId\"]\n );\n return e2;\n }\n case EventType.IncrementalSnapshot: {\n switch (e2.data.source) {\n case IncrementalSource.Mutation: {\n e2.data.adds.forEach((n2) => {\n this.replaceIds(n2, iframeEl, [\n \"parentId\",\n \"nextId\",\n \"previousId\"\n ]);\n this.replaceIdOnNode(n2.node, iframeEl);\n const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\n rootId && this.patchRootIdOnNode(n2.node, rootId);\n });\n e2.data.removes.forEach((n2) => {\n this.replaceIds(n2, iframeEl, [\"parentId\", \"id\"]);\n });\n e2.data.attributes.forEach((n2) => {\n this.replaceIds(n2, iframeEl, [\"id\"]);\n });\n e2.data.texts.forEach((n2) => {\n this.replaceIds(n2, iframeEl, [\"id\"]);\n });\n return e2;\n }\n case IncrementalSource.Drag:\n case IncrementalSource.TouchMove:\n case IncrementalSource.MouseMove: {\n e2.data.positions.forEach((p) => {\n this.replaceIds(p, iframeEl, [\"id\"]);\n });\n return e2;\n }\n case IncrementalSource.ViewportResize: {\n return false;\n }\n case IncrementalSource.MediaInteraction:\n case IncrementalSource.MouseInteraction:\n case IncrementalSource.Scroll:\n case IncrementalSource.CanvasMutation:\n case IncrementalSource.Input: {\n this.replaceIds(e2.data, iframeEl, [\"id\"]);\n return e2;\n }\n case IncrementalSource.StyleSheetRule:\n case IncrementalSource.StyleDeclaration: {\n this.replaceIds(e2.data, iframeEl, [\"id\"]);\n this.replaceStyleIds(e2.data, iframeEl, [\"styleId\"]);\n return e2;\n }\n case IncrementalSource.Font: {\n return e2;\n }\n case IncrementalSource.Selection: {\n e2.data.ranges.forEach((range) => {\n this.replaceIds(range, iframeEl, [\"start\", \"end\"]);\n });\n return e2;\n }\n case IncrementalSource.AdoptedStyleSheet: {\n this.replaceIds(e2.data, iframeEl, [\"id\"]);\n this.replaceStyleIds(e2.data, iframeEl, [\"styleIds\"]);\n e2.data.styles?.forEach((style) => {\n this.replaceStyleIds(style, iframeEl, [\"styleId\"]);\n });\n return e2;\n }\n }\n }\n }\n return false;\n }\n replace(iframeMirror, obj, iframeEl, keys) {\n for (const key of keys) {\n if (!Array.isArray(obj[key]) && typeof obj[key] !== \"number\") continue;\n if (Array.isArray(obj[key])) {\n obj[key] = iframeMirror.getIds(\n iframeEl,\n obj[key]\n );\n } else {\n obj[key] = iframeMirror.getId(iframeEl, obj[key]);\n }\n }\n return obj;\n }\n replaceIds(obj, iframeEl, keys) {\n return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\n }\n replaceStyleIds(obj, iframeEl, keys) {\n return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\n }\n replaceIdOnNode(node, iframeEl) {\n this.replaceIds(node, iframeEl, [\"id\", \"rootId\"]);\n if (\"childNodes\" in node) {\n node.childNodes.forEach((child) => {\n this.replaceIdOnNode(child, iframeEl);\n });\n }\n }\n patchRootIdOnNode(node, rootId) {\n if (node.type !== NodeType$2.Document && !node.rootId) node.rootId = rootId;\n if (\"childNodes\" in node) {\n node.childNodes.forEach((child) => {\n this.patchRootIdOnNode(child, rootId);\n });\n }\n }\n}\nclass ShadowDomManagerNoop {\n init() {\n }\n addShadowRoot() {\n }\n observeAttachShadow() {\n }\n reset() {\n }\n}\nclass ShadowDomManager {\n constructor(options) {\n this.shadowDoms = /* @__PURE__ */ new WeakSet();\n this.restoreHandlers = [];\n this.mutationCb = options.mutationCb;\n this.scrollCb = options.scrollCb;\n this.bypassOptions = options.bypassOptions;\n this.mirror = options.mirror;\n this.init();\n }\n init() {\n this.reset();\n this.patchAttachShadow(Element, document);\n }\n addShadowRoot(shadowRoot, doc) {\n if (!isNativeShadowDom(shadowRoot)) return;\n if (this.shadowDoms.has(shadowRoot)) return;\n this.shadowDoms.add(shadowRoot);\n this.bypassOptions.canvasManager.addShadowRoot(shadowRoot);\n const observer = initMutationObserver(\n {\n ...this.bypassOptions,\n doc,\n mutationCb: this.mutationCb,\n mirror: this.mirror,\n shadowDomManager: this\n },\n shadowRoot\n );\n this.restoreHandlers.push(() => observer.disconnect());\n this.restoreHandlers.push(\n initScrollObserver({\n ...this.bypassOptions,\n scrollCb: this.scrollCb,\n // https://gist.github.com/praveenpuglia/0832da687ed5a5d7a0907046c9ef1813\n // scroll is not allowed to pass the boundary, so we need to listen the shadow document\n doc: shadowRoot,\n mirror: this.mirror\n })\n );\n setTimeout$1(() => {\n if (shadowRoot.adoptedStyleSheets && shadowRoot.adoptedStyleSheets.length > 0)\n this.bypassOptions.stylesheetManager.adoptStyleSheets(\n shadowRoot.adoptedStyleSheets,\n this.mirror.getId(shadowRoot.host)\n );\n this.restoreHandlers.push(\n initAdoptedStyleSheetObserver(\n {\n mirror: this.mirror,\n stylesheetManager: this.bypassOptions.stylesheetManager\n },\n shadowRoot\n )\n );\n }, 0);\n }\n /**\n * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.\n */\n observeAttachShadow(iframeElement) {\n const iframeDoc = getIFrameContentDocument(iframeElement);\n const iframeWindow = getIFrameContentWindow(iframeElement);\n if (!iframeDoc || !iframeWindow) return;\n this.patchAttachShadow(\n iframeWindow.Element,\n iframeDoc\n );\n }\n /**\n * Patch 'attachShadow' to observe newly added shadow doms.\n */\n patchAttachShadow(element, doc) {\n const manager = this;\n this.restoreHandlers.push(\n patch(\n element.prototype,\n \"attachShadow\",\n function(original) {\n return function(option) {\n const shadowRoot = original.call(this, option);\n if (this.shadowRoot && inDom(this))\n manager.addShadowRoot(this.shadowRoot, doc);\n return shadowRoot;\n };\n }\n )\n );\n }\n reset() {\n this.restoreHandlers.forEach((handler) => {\n try {\n handler();\n } catch (e2) {\n }\n });\n this.restoreHandlers = [];\n this.shadowDoms = /* @__PURE__ */ new WeakSet();\n this.bypassOptions.canvasManager.resetShadowRoots();\n }\n}\nvar chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nvar lookup = typeof Uint8Array === \"undefined\" ? [] : new Uint8Array(256);\nfor (var i$1 = 0; i$1 < chars.length; i$1++) {\n lookup[chars.charCodeAt(i$1)] = i$1;\n}\nvar encode = function(arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = \"\";\n for (i2 = 0; i2 < len; i2 += 3) {\n base64 += chars[bytes[i2] >> 2];\n base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];\n base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];\n base64 += chars[bytes[i2 + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + \"=\";\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + \"==\";\n }\n return base64;\n};\nvar decode = function(base64) {\n var bufferLength = base64.length * 0.75, len = base64.length, i2, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === \"=\") {\n bufferLength--;\n if (base64[base64.length - 2] === \"=\") {\n bufferLength--;\n }\n }\n var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i2 = 0; i2 < len; i2 += 4) {\n encoded1 = lookup[base64.charCodeAt(i2)];\n encoded2 = lookup[base64.charCodeAt(i2 + 1)];\n encoded3 = lookup[base64.charCodeAt(i2 + 2)];\n encoded4 = lookup[base64.charCodeAt(i2 + 3)];\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n return arraybuffer;\n};\nconst canvasVarMap = /* @__PURE__ */ new Map();\nfunction variableListFor$1(ctx, ctor) {\n let contextMap = canvasVarMap.get(ctx);\n if (!contextMap) {\n contextMap = /* @__PURE__ */ new Map();\n canvasVarMap.set(ctx, contextMap);\n }\n if (!contextMap.has(ctor)) {\n contextMap.set(ctor, []);\n }\n return contextMap.get(ctor);\n}\nconst saveWebGLVar = (value, win, ctx) => {\n if (!value || !(isInstanceOfWebGLObject(value, win) || typeof value === \"object\"))\n return;\n const name = value.constructor.name;\n const list = variableListFor$1(ctx, name);\n let index = list.indexOf(value);\n if (index === -1) {\n index = list.length;\n list.push(value);\n }\n return index;\n};\nfunction serializeArg(value, win, ctx) {\n if (value instanceof Array) {\n return value.map((arg) => serializeArg(arg, win, ctx));\n } else if (value === null) {\n return value;\n } else if (value instanceof Float32Array || value instanceof Float64Array || value instanceof Int32Array || value instanceof Uint32Array || value instanceof Uint8Array || value instanceof Uint16Array || value instanceof Int16Array || value instanceof Int8Array || value instanceof Uint8ClampedArray) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [Object.values(value)]\n };\n } else if (\n // SharedArrayBuffer disabled on most browsers due to spectre.\n // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/SharedArrayBuffer\n // value instanceof SharedArrayBuffer ||\n value instanceof ArrayBuffer\n ) {\n const name = value.constructor.name;\n const base64 = encode(value);\n return {\n rr_type: name,\n base64\n };\n } else if (value instanceof DataView) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [\n serializeArg(value.buffer, win, ctx),\n value.byteOffset,\n value.byteLength\n ]\n };\n } else if (value instanceof HTMLImageElement) {\n const name = value.constructor.name;\n const { src } = value;\n return {\n rr_type: name,\n src\n };\n } else if (value instanceof HTMLCanvasElement) {\n const name = \"HTMLImageElement\";\n const src = value.toDataURL();\n return {\n rr_type: name,\n src\n };\n } else if (value instanceof ImageData) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [serializeArg(value.data, win, ctx), value.width, value.height]\n };\n } else if (isInstanceOfWebGLObject(value, win) || typeof value === \"object\") {\n const name = value.constructor.name;\n const index = saveWebGLVar(value, win, ctx);\n return {\n rr_type: name,\n index\n };\n }\n return value;\n}\nconst serializeArgs = (args, win, ctx) => {\n return args.map((arg) => serializeArg(arg, win, ctx));\n};\nconst isInstanceOfWebGLObject = (value, win) => {\n const webGLConstructorNames = [\n \"WebGLActiveInfo\",\n \"WebGLBuffer\",\n \"WebGLFramebuffer\",\n \"WebGLProgram\",\n \"WebGLRenderbuffer\",\n \"WebGLShader\",\n \"WebGLShaderPrecisionFormat\",\n \"WebGLTexture\",\n \"WebGLUniformLocation\",\n \"WebGLVertexArrayObject\",\n // In old Chrome versions, value won't be an instanceof WebGLVertexArrayObject.\n \"WebGLVertexArrayObjectOES\"\n ];\n const supportedWebGLConstructorNames = webGLConstructorNames.filter(\n (name) => typeof win[name] === \"function\"\n );\n return Boolean(\n supportedWebGLConstructorNames.find(\n (name) => value instanceof win[name]\n )\n );\n};\nfunction initCanvas2DMutationObserver(cb, win, blockClass2, blockSelector, unblockSelector) {\n const handlers = [];\n const props2D = Object.getOwnPropertyNames(\n win.CanvasRenderingContext2D.prototype\n );\n for (const prop of props2D) {\n try {\n if (typeof win.CanvasRenderingContext2D.prototype[prop] !== \"function\") {\n continue;\n }\n const restoreHandler = patch(\n win.CanvasRenderingContext2D.prototype,\n prop,\n function(original) {\n return function(...args) {\n if (!isBlocked(\n this.canvas,\n blockClass2,\n blockSelector,\n unblockSelector,\n true\n )) {\n setTimeout$1(() => {\n const recordArgs = serializeArgs(args, win, this);\n cb(this.canvas, {\n type: CanvasContext[\"2D\"],\n property: prop,\n args: recordArgs\n });\n }, 0);\n }\n return original.apply(this, args);\n };\n }\n );\n handlers.push(restoreHandler);\n } catch {\n const hookHandler = hookSetter(\n win.CanvasRenderingContext2D.prototype,\n prop,\n {\n set(v2) {\n cb(this.canvas, {\n type: CanvasContext[\"2D\"],\n property: prop,\n args: [v2],\n setter: true\n });\n }\n }\n );\n handlers.push(hookHandler);\n }\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\nfunction getNormalizedContextName(contextType) {\n return contextType === \"experimental-webgl\" ? \"webgl\" : contextType;\n}\nfunction initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, setPreserveDrawingBufferToTrue) {\n const handlers = [];\n try {\n const restoreHandler = patch(\n win.HTMLCanvasElement.prototype,\n \"getContext\",\n function(original) {\n return function(contextType, ...args) {\n if (!isBlocked(this, blockClass, blockSelector, unblockSelector, true)) {\n const ctxName = getNormalizedContextName(contextType);\n if (!(\"__context\" in this)) this.__context = ctxName;\n if (setPreserveDrawingBufferToTrue && [\"webgl\", \"webgl2\"].includes(ctxName)) {\n if (args[0] && typeof args[0] === \"object\") {\n const contextAttributes = args[0];\n if (!contextAttributes.preserveDrawingBuffer) {\n contextAttributes.preserveDrawingBuffer = true;\n }\n } else {\n args.splice(0, 1, {\n preserveDrawingBuffer: true\n });\n }\n }\n }\n return original.apply(this, [contextType, ...args]);\n };\n }\n );\n handlers.push(restoreHandler);\n } catch {\n console.error(\"failed to patch HTMLCanvasElement.prototype.getContext\");\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\nfunction patchGLPrototype(prototype, type, cb, blockClass2, blockSelector, unblockSelector, _mirror2, win) {\n const handlers = [];\n const props = Object.getOwnPropertyNames(prototype);\n for (const prop of props) {\n if (\n //prop.startsWith('get') || // e.g. getProgramParameter, but too risky\n [\n \"isContextLost\",\n \"canvas\",\n \"drawingBufferWidth\",\n \"drawingBufferHeight\"\n ].includes(prop)\n ) {\n continue;\n }\n try {\n if (typeof prototype[prop] !== \"function\") {\n continue;\n }\n const restoreHandler = patch(\n prototype,\n prop,\n function(original) {\n return function(...args) {\n const result = original.apply(this, args);\n saveWebGLVar(result, win, this);\n if (\"tagName\" in this.canvas && !isBlocked(\n this.canvas,\n blockClass2,\n blockSelector,\n unblockSelector,\n true\n )) {\n const recordArgs = serializeArgs(args, win, this);\n const mutation = {\n type,\n property: prop,\n args: recordArgs\n };\n cb(this.canvas, mutation);\n }\n return result;\n };\n }\n );\n handlers.push(restoreHandler);\n } catch {\n const hookHandler = hookSetter(prototype, prop, {\n set(v2) {\n cb(this.canvas, {\n type,\n property: prop,\n args: [v2],\n setter: true\n });\n }\n });\n handlers.push(hookHandler);\n }\n }\n return handlers;\n}\nfunction initCanvasWebGLMutationObserver(cb, win, blockClass2, blockSelector, unblockSelector, mirror2) {\n const handlers = [];\n handlers.push(\n ...patchGLPrototype(\n win.WebGLRenderingContext.prototype,\n CanvasContext.WebGL,\n cb,\n blockClass2,\n blockSelector,\n unblockSelector,\n mirror2,\n win\n )\n );\n if (typeof win.WebGL2RenderingContext !== \"undefined\") {\n handlers.push(\n ...patchGLPrototype(\n win.WebGL2RenderingContext.prototype,\n CanvasContext.WebGL2,\n cb,\n blockClass2,\n blockSelector,\n unblockSelector,\n mirror2,\n win\n )\n );\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\nconst r$1 = `for(var e=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\",t=\"undefined\"==typeof Uint8Array?[]:new Uint8Array(256),a=0;a<64;a++)t[e.charCodeAt(a)]=a;var n=function(t){var a,n=new Uint8Array(t),r=n.length,s=\"\";for(a=0;a>2],s+=e[(3&n[a])<<4|n[a+1]>>4],s+=e[(15&n[a+1])<<2|n[a+2]>>6],s+=e[63&n[a+2]];return r%3==2?s=s.substring(0,s.length-1)+\"=\":r%3==1&&(s=s.substring(0,s.length-2)+\"==\"),s};const r=new Map,s=new Map;const i=self;i.onmessage=async function(e){if(!(\"OffscreenCanvas\"in globalThis))return i.postMessage({id:e.data.id});{const{id:t,bitmap:a,width:o,height:f,maxCanvasSize:c,dataURLOptions:g}=e.data,u=async function(e,t,a){const r=e+\"-\"+t;if(\"OffscreenCanvas\"in globalThis){if(s.has(r))return s.get(r);const i=new OffscreenCanvas(e,t);i.getContext(\"2d\");const o=await i.convertToBlob(a),f=await o.arrayBuffer(),c=n(f);return s.set(r,c),c}return\"\"}(o,f,g),[h,d]=function(e,t,a){if(!a)return[e,t];const[n,r]=a;if(e<=n&&t<=r)return[e,t];let s=e,i=t;return s>n&&(i=Math.floor(n*t/e),s=n),i>r&&(s=Math.floor(r*e/t),i=r),[s,i]}(o,f,c),l=new OffscreenCanvas(h,d),w=l.getContext(\"bitmaprenderer\"),p=h===o&&d===f?a:await createImageBitmap(a,{resizeWidth:h,resizeHeight:d,resizeQuality:\"low\"});w?.transferFromImageBitmap(p),a.close();const y=await l.convertToBlob(g),v=y.type,b=await y.arrayBuffer(),m=n(b);if(p.close(),!r.has(t)&&await u===m)return r.set(t,m),i.postMessage({id:t});if(r.get(t)===m)return i.postMessage({id:t});i.postMessage({id:t,type:v,base64:m,width:o,height:f}),r.set(t,m)}};`;\nfunction t$1() {\n const t2 = new Blob([r$1]);\n return URL.createObjectURL(t2);\n}\nclass CanvasManagerNoop {\n reset() {\n }\n freeze() {\n }\n unfreeze() {\n }\n lock() {\n }\n unlock() {\n }\n snapshot() {\n }\n addWindow() {\n }\n addShadowRoot() {\n }\n resetShadowRoots() {\n }\n}\nclass CanvasManager {\n constructor(options) {\n this.pendingCanvasMutations = /* @__PURE__ */ new Map();\n this.rafStamps = { latestId: 0, invokeId: null };\n this.shadowDoms = /* @__PURE__ */ new Set();\n this.windowsSet = /* @__PURE__ */ new WeakSet();\n this.windows = [];\n this.restoreHandlers = [];\n this.frozen = false;\n this.locked = false;\n this.snapshotInProgressMap = /* @__PURE__ */ new Map();\n this.worker = null;\n this.lastSnapshotTime = 0;\n this.processMutation = (target, mutation) => {\n const newFrame = this.rafStamps.invokeId && this.rafStamps.latestId !== this.rafStamps.invokeId;\n if (newFrame || !this.rafStamps.invokeId)\n this.rafStamps.invokeId = this.rafStamps.latestId;\n if (!this.pendingCanvasMutations.has(target)) {\n this.pendingCanvasMutations.set(target, []);\n }\n this.pendingCanvasMutations.get(target).push(mutation);\n };\n const {\n enableManualSnapshot,\n sampling = \"all\",\n win,\n recordCanvas,\n errorHandler: errorHandler2\n } = options;\n options.sampling = sampling;\n this.mutationCb = options.mutationCb;\n this.mirror = options.mirror;\n this.options = options;\n if (errorHandler2) {\n registerErrorHandler(errorHandler2);\n }\n if (recordCanvas && typeof sampling === \"number\" || enableManualSnapshot) {\n this.worker = this.initFPSWorker();\n }\n this.addWindow(win);\n if (enableManualSnapshot) {\n return;\n }\n callbackWrapper(() => {\n if (recordCanvas && sampling === \"all\") {\n this.startRAFTimestamping();\n this.startPendingCanvasMutationFlusher();\n }\n if (recordCanvas && typeof sampling === \"number\") {\n this.initCanvasFPSObserver();\n }\n })();\n }\n reset() {\n this.pendingCanvasMutations.clear();\n this.restoreHandlers.forEach((handler) => {\n try {\n handler();\n } catch (e2) {\n }\n });\n this.restoreHandlers = [];\n this.windowsSet = /* @__PURE__ */ new WeakSet();\n this.windows = [];\n this.shadowDoms = /* @__PURE__ */ new Set();\n this.worker?.terminate();\n this.worker = null;\n this.snapshotInProgressMap = /* @__PURE__ */ new Map();\n }\n freeze() {\n this.frozen = true;\n }\n unfreeze() {\n this.frozen = false;\n }\n lock() {\n this.locked = true;\n }\n unlock() {\n this.locked = false;\n }\n addWindow(win) {\n const {\n sampling = \"all\",\n blockClass,\n blockSelector,\n unblockSelector,\n recordCanvas,\n enableManualSnapshot\n } = this.options;\n if (this.windowsSet.has(win)) return;\n if (enableManualSnapshot) {\n this.windowsSet.add(win);\n this.windows.push(new WeakRef(win));\n return;\n }\n callbackWrapper(() => {\n if (recordCanvas && sampling === \"all\") {\n this.initCanvasMutationObserver(\n win,\n blockClass,\n blockSelector,\n unblockSelector\n );\n }\n if (recordCanvas && typeof sampling === \"number\") {\n const canvasContextReset = initCanvasContextObserver(\n win,\n blockClass,\n blockSelector,\n unblockSelector,\n true\n );\n this.restoreHandlers.push(() => {\n canvasContextReset();\n });\n }\n })();\n this.windowsSet.add(win);\n this.windows.push(new WeakRef(win));\n }\n addShadowRoot(shadowRoot) {\n this.shadowDoms.add(new WeakRef(shadowRoot));\n }\n resetShadowRoots() {\n this.shadowDoms = /* @__PURE__ */ new Set();\n }\n snapshot(canvasElement, options) {\n if (options?.skipRequestAnimationFrame) {\n this.takeSnapshot(performance.now(), true, canvasElement);\n return;\n }\n onRequestAnimationFrame(\n (timestamp) => this.takeSnapshot(timestamp, true, canvasElement)\n );\n }\n initFPSWorker() {\n const worker = new Worker(t$1());\n worker.onmessage = (e2) => {\n const data = e2.data;\n const { id } = data;\n this.snapshotInProgressMap.set(id, false);\n if (!(\"base64\" in data)) return;\n const { base64, type, width, height } = data;\n this.mutationCb({\n id,\n type: CanvasContext[\"2D\"],\n commands: [\n {\n property: \"clearRect\",\n // wipe canvas\n args: [0, 0, width, height]\n },\n {\n property: \"drawImage\",\n // draws (semi-transparent) image\n args: [\n {\n rr_type: \"ImageBitmap\",\n args: [\n {\n rr_type: \"Blob\",\n data: [{ rr_type: \"ArrayBuffer\", base64 }],\n type\n }\n ]\n },\n 0,\n 0,\n // The below args are needed if we enforce a max size, we want to\n // retain the original size when drawing the image (which should be smaller)\n width,\n height\n ]\n }\n ]\n });\n };\n return worker;\n }\n initCanvasFPSObserver() {\n let rafId;\n if (!this.windows.length && !this.shadowDoms.size) {\n return;\n }\n const rafCallback = (timestamp) => {\n this.takeSnapshot(timestamp, false);\n rafId = onRequestAnimationFrame(rafCallback);\n };\n rafId = onRequestAnimationFrame(rafCallback);\n this.restoreHandlers.push(() => {\n if (rafId) {\n cancelAnimationFrame(rafId);\n }\n });\n }\n initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector) {\n const canvasContextReset = initCanvasContextObserver(\n win,\n blockClass,\n blockSelector,\n unblockSelector,\n false\n );\n const canvas2DReset = initCanvas2DMutationObserver(\n this.processMutation.bind(this),\n win,\n blockClass,\n blockSelector,\n unblockSelector\n );\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(\n this.processMutation.bind(this),\n win,\n blockClass,\n blockSelector,\n unblockSelector,\n this.mirror\n );\n this.restoreHandlers.push(() => {\n canvasContextReset();\n canvas2DReset();\n canvasWebGL1and2Reset();\n });\n }\n /**\n * Returns all `canvas` elements that are not blocked by the given selectors. Searches all windows and shadow roots.\n */\n getCanvasElements(blockClass, blockSelector, unblockSelector) {\n const matchedCanvas = [];\n const searchCanvas = (root) => {\n root.querySelectorAll(\"canvas\").forEach((canvas) => {\n if (!isBlocked(canvas, blockClass, blockSelector, unblockSelector, true)) {\n matchedCanvas.push(canvas);\n }\n });\n };\n for (const item of this.windows) {\n const window2 = item.deref();\n let _document;\n try {\n _document = window2 && window2.document;\n } catch {\n }\n if (_document) {\n searchCanvas(_document);\n }\n }\n for (const item of this.shadowDoms) {\n const shadowRoot = item.deref();\n if (shadowRoot) {\n searchCanvas(shadowRoot);\n }\n }\n return matchedCanvas;\n }\n /**\n * Takes a snapshot of the provided canvas element, or will search all windows/shadow roots for canvases. Will self-throttle based on `options.sampling`.\n *\n * @returns `true` if the snapshot was taken, `false` if it was throttled.\n */\n takeSnapshot(timestamp, isManualSnapshot, canvasElement) {\n const {\n sampling,\n blockClass,\n blockSelector,\n unblockSelector,\n dataURLOptions,\n maxCanvasSize\n } = this.options;\n const fps = sampling === \"all\" ? 2 : sampling || 2;\n const timeBetweenSnapshots = 1e3 / fps;\n const shouldThrottle = this.lastSnapshotTime && timestamp - this.lastSnapshotTime < timeBetweenSnapshots;\n if (shouldThrottle) {\n return false;\n }\n this.lastSnapshotTime = timestamp;\n const canvases = canvasElement ? [canvasElement] : this.getCanvasElements(blockClass, blockSelector, unblockSelector);\n canvases.forEach((canvas) => {\n const id = this.mirror.getId(canvas);\n if (!this.mirror.hasNode(canvas) || !canvas.width || !canvas.height || this.snapshotInProgressMap.get(id)) {\n return;\n }\n this.snapshotInProgressMap.set(id, true);\n if (!isManualSnapshot && [\"webgl\", \"webgl2\"].includes(canvas.__context)) {\n const context = canvas.getContext(canvas.__context);\n if (context?.getContextAttributes()?.preserveDrawingBuffer === false) {\n context.clear(context.COLOR_BUFFER_BIT);\n }\n }\n createImageBitmap(canvas).then((bitmap) => {\n this.worker?.postMessage(\n {\n id,\n bitmap,\n width: canvas.width,\n height: canvas.height,\n dataURLOptions,\n maxCanvasSize\n },\n [bitmap]\n );\n }).catch((error) => {\n callbackWrapper(() => {\n this.snapshotInProgressMap.delete(id);\n throw error;\n })();\n });\n });\n return true;\n }\n startPendingCanvasMutationFlusher() {\n onRequestAnimationFrame(() => this.flushPendingCanvasMutations());\n }\n startRAFTimestamping() {\n const setLatestRAFTimestamp = (timestamp) => {\n this.rafStamps.latestId = timestamp;\n onRequestAnimationFrame(setLatestRAFTimestamp);\n };\n onRequestAnimationFrame(setLatestRAFTimestamp);\n }\n flushPendingCanvasMutations() {\n this.pendingCanvasMutations.forEach(\n (_values, canvas) => {\n const id = this.mirror.getId(canvas);\n this.flushPendingCanvasMutationFor(canvas, id);\n }\n );\n onRequestAnimationFrame(() => this.flushPendingCanvasMutations());\n }\n flushPendingCanvasMutationFor(canvas, id) {\n if (this.frozen || this.locked) {\n return;\n }\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\n if (!valuesWithType || id === -1) return;\n const values = valuesWithType.map((value) => {\n const { type: type2, ...rest } = value;\n return rest;\n });\n const { type } = valuesWithType[0];\n this.mutationCb({ id, type, commands: values });\n this.pendingCanvasMutations.delete(canvas);\n }\n}\nclass StylesheetManager {\n constructor(options) {\n this.trackedLinkElements = /* @__PURE__ */ new WeakSet();\n this.styleMirror = new StyleSheetMirror();\n this.mutationCb = options.mutationCb;\n this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\n }\n attachLinkElement(linkEl, childSn) {\n if (\"_cssText\" in childSn.attributes)\n this.mutationCb({\n adds: [],\n removes: [],\n texts: [],\n attributes: [\n {\n id: childSn.id,\n attributes: childSn.attributes\n }\n ]\n });\n this.trackLinkElement(linkEl);\n }\n trackLinkElement(linkEl) {\n if (this.trackedLinkElements.has(linkEl)) return;\n this.trackedLinkElements.add(linkEl);\n this.trackStylesheetInLinkElement(linkEl);\n }\n adoptStyleSheets(sheets, hostId) {\n if (sheets.length === 0) return;\n const adoptedStyleSheetData = {\n id: hostId,\n styleIds: []\n };\n const styles = [];\n for (const sheet of sheets) {\n let styleId;\n if (!this.styleMirror.has(sheet)) {\n styleId = this.styleMirror.add(sheet);\n styles.push({\n styleId,\n rules: Array.from(sheet.rules || CSSRule, (r2, index) => ({\n rule: stringifyRule(r2),\n index\n }))\n });\n } else styleId = this.styleMirror.getId(sheet);\n adoptedStyleSheetData.styleIds.push(styleId);\n }\n if (styles.length > 0) adoptedStyleSheetData.styles = styles;\n this.adoptedStyleSheetCb(adoptedStyleSheetData);\n }\n reset() {\n this.styleMirror.reset();\n this.trackedLinkElements = /* @__PURE__ */ new WeakSet();\n }\n // TODO: take snapshot on stylesheet reload by applying event listener\n trackStylesheetInLinkElement(_linkEl) {\n }\n}\nclass ProcessedNodeManager {\n constructor() {\n this.nodeMap = /* @__PURE__ */ new WeakMap();\n this.active = false;\n }\n inOtherBuffer(node, thisBuffer) {\n const buffers = this.nodeMap.get(node);\n return buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer);\n }\n add(node, buffer) {\n if (!this.active) {\n this.active = true;\n onRequestAnimationFrame(() => {\n this.nodeMap = /* @__PURE__ */ new WeakMap();\n this.active = false;\n });\n }\n this.nodeMap.set(node, (this.nodeMap.get(node) || /* @__PURE__ */ new Set()).add(buffer));\n }\n destroy() {\n }\n}\nlet wrappedEmit;\nlet _wrappedEmit;\nlet _takeFullSnapshot;\ntry {\n if (Array.from([1], (x) => x * 2)[0] !== 2) {\n const cleanFrame = document.createElement(\"iframe\");\n document.body.appendChild(cleanFrame);\n Array.from = cleanFrame.contentWindow?.Array.from || Array.from;\n document.body.removeChild(cleanFrame);\n }\n} catch (err) {\n console.debug(\"Unable to override Array.from\", err);\n}\nconst mirror = createMirror$2();\nfunction record(options = {}) {\n const {\n emit,\n checkoutEveryNms,\n checkoutEveryNth,\n blockClass = \"rr-block\",\n blockSelector = null,\n unblockSelector = null,\n ignoreClass = \"rr-ignore\",\n ignoreSelector = null,\n maskAllText = false,\n maskTextClass = \"rr-mask\",\n unmaskTextClass = null,\n maskTextSelector = null,\n unmaskTextSelector = null,\n inlineStylesheet = true,\n maskAllInputs,\n maskInputOptions: _maskInputOptions,\n slimDOMOptions: _slimDOMOptions,\n maskAttributeFn,\n maskInputFn,\n maskTextFn,\n maxCanvasSize = null,\n packFn,\n sampling = {},\n dataURLOptions = {},\n mousemoveWait,\n recordDOM = true,\n recordCanvas = false,\n recordCrossOriginIframes = false,\n recordAfter = options.recordAfter === \"DOMContentLoaded\" ? options.recordAfter : \"load\",\n userTriggeredOnInput = false,\n collectFonts = false,\n inlineImages = false,\n plugins,\n keepIframeSrcFn = () => false,\n ignoreCSSAttributes = /* @__PURE__ */ new Set([]),\n errorHandler: errorHandler2,\n onMutation,\n getCanvasManager\n } = options;\n registerErrorHandler(errorHandler2);\n const inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;\n let passEmitsToParent = false;\n if (!inEmittingFrame) {\n try {\n if (window.parent.document) {\n passEmitsToParent = false;\n }\n } catch (e2) {\n passEmitsToParent = true;\n }\n }\n if (inEmittingFrame && !emit) {\n throw new Error(\"emit function is required\");\n }\n if (!inEmittingFrame && !passEmitsToParent) {\n return () => {\n };\n }\n if (mousemoveWait !== void 0 && sampling.mousemove === void 0) {\n sampling.mousemove = mousemoveWait;\n }\n mirror.reset();\n const maskInputOptions = maskAllInputs === true ? {\n color: true,\n date: true,\n \"datetime-local\": true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n radio: true,\n checkbox: true\n } : _maskInputOptions !== void 0 ? _maskInputOptions : {};\n const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === \"all\" ? {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaVerification: true,\n // the following are off for slimDOMOptions === true,\n // as they destroy some (hidden) info:\n headMetaAuthorship: _slimDOMOptions === \"all\",\n headMetaDescKeywords: _slimDOMOptions === \"all\"\n } : _slimDOMOptions ? _slimDOMOptions : {};\n polyfill$1();\n let lastFullSnapshotEvent;\n let incrementalSnapshotCount = 0;\n const eventProcessor = (e2) => {\n for (const plugin of plugins || []) {\n if (plugin.eventProcessor) {\n e2 = plugin.eventProcessor(e2);\n }\n }\n if (packFn && // Disable packing events which will be emitted to parent frames.\n !passEmitsToParent) {\n e2 = packFn(e2);\n }\n return e2;\n };\n wrappedEmit = (r2, isCheckout) => {\n const e2 = r2;\n e2.timestamp = nowTimestamp();\n if (mutationBuffers[0]?.isFrozen() && e2.type !== EventType.FullSnapshot && !(e2.type === EventType.IncrementalSnapshot && e2.data.source === IncrementalSource.Mutation)) {\n mutationBuffers.forEach((buf) => buf.unfreeze());\n }\n if (inEmittingFrame) {\n emit?.(eventProcessor(e2), isCheckout);\n } else if (passEmitsToParent) {\n const message = {\n type: \"rrweb\",\n event: eventProcessor(e2),\n origin: window.location.origin,\n isCheckout\n };\n window.parent.postMessage(message, \"*\");\n }\n if (e2.type === EventType.FullSnapshot) {\n lastFullSnapshotEvent = e2;\n incrementalSnapshotCount = 0;\n } else if (e2.type === EventType.IncrementalSnapshot) {\n if (e2.data.source === IncrementalSource.Mutation && e2.data.isAttachIframe) {\n return;\n }\n incrementalSnapshotCount++;\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n const exceedTime = checkoutEveryNms && lastFullSnapshotEvent && e2.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n if (exceedCount || exceedTime) {\n takeFullSnapshot2(true);\n }\n }\n };\n _wrappedEmit = wrappedEmit;\n const wrappedMutationEmit = (m) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Mutation,\n ...m\n }\n });\n };\n const wrappedScrollEmit = (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Scroll,\n ...p\n }\n });\n const wrappedCanvasMutationEmit = (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CanvasMutation,\n ...p\n }\n });\n const wrappedAdoptedStyleSheetEmit = (a2) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.AdoptedStyleSheet,\n ...a2\n }\n });\n const stylesheetManager = new StylesheetManager({\n mutationCb: wrappedMutationEmit,\n adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit\n });\n const iframeManager = typeof __RRWEB_EXCLUDE_IFRAME__ === \"boolean\" && __RRWEB_EXCLUDE_IFRAME__ ? new IframeManagerNoop() : new IframeManager({\n mirror,\n mutationCb: wrappedMutationEmit,\n stylesheetManager,\n recordCrossOriginIframes,\n wrappedEmit\n });\n for (const plugin of plugins || []) {\n if (plugin.getMirror)\n plugin.getMirror({\n nodeMirror: mirror,\n crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\n crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror\n });\n }\n const processedNodeManager = new ProcessedNodeManager();\n const canvasManager = _getCanvasManager(\n getCanvasManager,\n {\n mirror,\n win: window,\n mutationCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CanvasMutation,\n ...p\n }\n }),\n recordCanvas,\n blockClass,\n blockSelector,\n unblockSelector,\n maxCanvasSize,\n sampling: sampling[\"canvas\"],\n dataURLOptions,\n errorHandler: errorHandler2\n }\n );\n const shadowDomManager = typeof __RRWEB_EXCLUDE_SHADOW_DOM__ === \"boolean\" && __RRWEB_EXCLUDE_SHADOW_DOM__ ? new ShadowDomManagerNoop() : new ShadowDomManager({\n mutationCb: wrappedMutationEmit,\n scrollCb: wrappedScrollEmit,\n bypassOptions: {\n onMutation,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputOptions,\n dataURLOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n recordCanvas,\n inlineImages,\n sampling,\n slimDOMOptions,\n iframeManager,\n stylesheetManager,\n canvasManager,\n keepIframeSrcFn,\n processedNodeManager,\n ignoreCSSAttributes\n },\n mirror\n });\n const takeFullSnapshot2 = (isCheckout = false) => {\n if (!recordDOM) {\n return;\n }\n wrappedEmit(\n {\n type: EventType.Meta,\n data: {\n href: window.location.href,\n width: getWindowWidth(),\n height: getWindowHeight()\n }\n },\n isCheckout\n );\n stylesheetManager.reset();\n shadowDomManager.init();\n mutationBuffers.forEach((buf) => buf.lock());\n const node = snapshot(document, {\n mirror,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskAllInputs: maskInputOptions,\n maskAttributeFn,\n maskInputFn,\n maskTextFn,\n slimDOM: slimDOMOptions,\n dataURLOptions,\n recordCanvas,\n inlineImages,\n onSerialize: (n2) => {\n if (isSerializedIframe(n2, mirror)) {\n iframeManager.addIframe(n2);\n }\n if (isSerializedStylesheet(n2, mirror)) {\n stylesheetManager.trackLinkElement(n2);\n }\n if (hasShadowRoot(n2)) {\n shadowDomManager.addShadowRoot(n2.shadowRoot, document);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n iframeManager.attachIframe(iframe, childSn);\n if (iframe.contentWindow) {\n canvasManager.addWindow(iframe.contentWindow);\n }\n shadowDomManager.observeAttachShadow(iframe);\n },\n onStylesheetLoad: (linkEl, childSn) => {\n stylesheetManager.attachLinkElement(linkEl, childSn);\n },\n onBlockedImageLoad: (_imageEl, serializedNode, { width, height }) => {\n wrappedMutationEmit({\n adds: [],\n removes: [],\n texts: [],\n attributes: [\n {\n id: serializedNode.id,\n attributes: {\n style: {\n width: `${width}px`,\n height: `${height}px`\n }\n }\n }\n ]\n });\n },\n keepIframeSrcFn,\n ignoreCSSAttributes\n });\n if (!node) {\n return console.warn(\"Failed to snapshot the document\");\n }\n wrappedEmit({\n type: EventType.FullSnapshot,\n data: {\n node,\n initialOffset: getWindowScroll(window)\n }\n });\n mutationBuffers.forEach((buf) => buf.unlock());\n if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\n stylesheetManager.adoptStyleSheets(\n document.adoptedStyleSheets,\n mirror.getId(document)\n );\n };\n _takeFullSnapshot = takeFullSnapshot2;\n try {\n const handlers = [];\n const observe = (doc) => {\n return callbackWrapper(initObservers)(\n {\n onMutation,\n mutationCb: wrappedMutationEmit,\n mousemoveCb: (positions, source) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source,\n positions\n }\n }),\n mouseInteractionCb: (d) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.MouseInteraction,\n ...d\n }\n }),\n scrollCb: wrappedScrollEmit,\n viewportResizeCb: (d) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.ViewportResize,\n ...d\n }\n }),\n inputCb: (v2) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Input,\n ...v2\n }\n }),\n mediaInteractionCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.MediaInteraction,\n ...p\n }\n }),\n styleSheetRuleCb: (r2) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleSheetRule,\n ...r2\n }\n }),\n styleDeclarationCb: (r2) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleDeclaration,\n ...r2\n }\n }),\n canvasMutationCb: wrappedCanvasMutationEmit,\n fontCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Font,\n ...p\n }\n }),\n selectionCb: (p) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Selection,\n ...p\n }\n });\n },\n customElementCb: (c2) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CustomElement,\n ...c2\n }\n });\n },\n blockClass,\n ignoreClass,\n ignoreSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskInputOptions,\n inlineStylesheet,\n sampling,\n recordDOM,\n recordCanvas,\n inlineImages,\n userTriggeredOnInput,\n collectFonts,\n doc,\n maskAttributeFn,\n maskInputFn,\n maskTextFn,\n keepIframeSrcFn,\n blockSelector,\n unblockSelector,\n slimDOMOptions,\n dataURLOptions,\n mirror,\n iframeManager,\n stylesheetManager,\n shadowDomManager,\n processedNodeManager,\n canvasManager,\n ignoreCSSAttributes,\n plugins: plugins?.filter((p) => p.observer)?.map((p) => ({\n observer: p.observer,\n options: p.options,\n callback: (payload) => wrappedEmit({\n type: EventType.Plugin,\n data: {\n plugin: p.name,\n payload\n }\n })\n })) || []\n },\n {}\n );\n };\n iframeManager.addLoadListener((iframeEl) => {\n try {\n handlers.push(observe(iframeEl.contentDocument));\n } catch (error) {\n console.warn(error);\n }\n });\n const init = () => {\n takeFullSnapshot2();\n handlers.push(observe(document));\n };\n if (document.readyState === \"interactive\" || document.readyState === \"complete\") {\n init();\n } else {\n handlers.push(\n on(\"DOMContentLoaded\", () => {\n wrappedEmit({\n type: EventType.DomContentLoaded,\n data: {}\n });\n if (recordAfter === \"DOMContentLoaded\") init();\n })\n );\n handlers.push(\n on(\n \"load\",\n () => {\n wrappedEmit({\n type: EventType.Load,\n data: {}\n });\n if (recordAfter === \"load\") init();\n },\n window\n )\n );\n }\n return () => {\n handlers.forEach((h) => h());\n processedNodeManager.destroy();\n _takeFullSnapshot = void 0;\n unregisterErrorHandler();\n };\n } catch (error) {\n console.warn(error);\n }\n}\nfunction addCustomEvent(tag, payload) {\n if (!_wrappedEmit) {\n throw new Error(\"please add custom event after start recording\");\n }\n wrappedEmit({\n type: EventType.Custom,\n data: {\n tag,\n payload\n }\n });\n}\nfunction freezePage() {\n mutationBuffers.forEach((buf) => buf.freeze());\n}\nfunction takeFullSnapshot(isCheckout) {\n if (!_takeFullSnapshot) {\n throw new Error(\"please take full snapshot after start recording\");\n }\n _takeFullSnapshot(isCheckout);\n}\nrecord.mirror = mirror;\nrecord.takeFullSnapshot = takeFullSnapshot;\nfunction _getCanvasManager(getCanvasManagerFn, options) {\n try {\n return getCanvasManagerFn ? getCanvasManagerFn(options) : new CanvasManagerNoop();\n } catch {\n console.warn(\"Unable to initialize CanvasManager\");\n return new CanvasManagerNoop();\n }\n}\nfunction mitt$1(n2) {\n return { all: n2 = n2 || /* @__PURE__ */ new Map(), on: function(t2, e2) {\n var i2 = n2.get(t2);\n i2 ? i2.push(e2) : n2.set(t2, [e2]);\n }, off: function(t2, e2) {\n var i2 = n2.get(t2);\n i2 && (e2 ? i2.splice(i2.indexOf(e2) >>> 0, 1) : n2.set(t2, []));\n }, emit: function(t2, e2) {\n var i2 = n2.get(t2);\n i2 && i2.slice().map(function(n3) {\n n3(e2);\n }), (i2 = n2.get(\"*\")) && i2.slice().map(function(n3) {\n n3(t2, e2);\n });\n } };\n}\nconst mittProxy = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({\n __proto__: null,\n default: mitt$1\n}, Symbol.toStringTag, { value: \"Module\" }));\nfunction polyfill(w = window, d = document) {\n if (\"scrollBehavior\" in d.documentElement.style && w.__forceSmoothScrollPolyfill__ !== true) {\n return;\n }\n const Element2 = w.HTMLElement || w.Element;\n const SCROLL_TIME = 468;\n const original = {\n scroll: w.scroll || w.scrollTo,\n scrollBy: w.scrollBy,\n elementScroll: Element2.prototype.scroll || scrollElement,\n scrollIntoView: Element2.prototype.scrollIntoView\n };\n const now = w.performance && w.performance.now ? w.performance.now.bind(w.performance) : Date.now;\n function isMicrosoftBrowser(userAgent) {\n const userAgentPatterns = [\"MSIE \", \"Trident/\", \"Edge/\"];\n return new RegExp(userAgentPatterns.join(\"|\")).test(userAgent);\n }\n const ROUNDING_TOLERANCE = isMicrosoftBrowser(w.navigator.userAgent) ? 1 : 0;\n function scrollElement(x, y) {\n this.scrollLeft = x;\n this.scrollTop = y;\n }\n function ease(k) {\n return 0.5 * (1 - Math.cos(Math.PI * k));\n }\n function shouldBailOut(firstArg) {\n if (firstArg === null || typeof firstArg !== \"object\" || firstArg.behavior === void 0 || firstArg.behavior === \"auto\" || firstArg.behavior === \"instant\") {\n return true;\n }\n if (typeof firstArg === \"object\" && firstArg.behavior === \"smooth\") {\n return false;\n }\n throw new TypeError(\n \"behavior member of ScrollOptions \" + firstArg.behavior + \" is not a valid value for enumeration ScrollBehavior.\"\n );\n }\n function hasScrollableSpace(el, axis) {\n if (axis === \"Y\") {\n return el.clientHeight + ROUNDING_TOLERANCE < el.scrollHeight;\n }\n if (axis === \"X\") {\n return el.clientWidth + ROUNDING_TOLERANCE < el.scrollWidth;\n }\n }\n function canOverflow(el, axis) {\n const overflowValue = w.getComputedStyle(el, null)[\"overflow\" + axis];\n return overflowValue === \"auto\" || overflowValue === \"scroll\";\n }\n function isScrollable(el) {\n const isScrollableY = hasScrollableSpace(el, \"Y\") && canOverflow(el, \"Y\");\n const isScrollableX = hasScrollableSpace(el, \"X\") && canOverflow(el, \"X\");\n return isScrollableY || isScrollableX;\n }\n function findScrollableParent(el) {\n while (el !== d.body && isScrollable(el) === false) {\n el = el.parentNode || el.host;\n }\n return el;\n }\n function step(context) {\n const time = now();\n let value;\n let currentX;\n let currentY;\n let elapsed = (time - context.startTime) / SCROLL_TIME;\n elapsed = elapsed > 1 ? 1 : elapsed;\n value = ease(elapsed);\n currentX = context.startX + (context.x - context.startX) * value;\n currentY = context.startY + (context.y - context.startY) * value;\n context.method.call(context.scrollable, currentX, currentY);\n if (currentX !== context.x || currentY !== context.y) {\n w.requestAnimationFrame(step.bind(w, context));\n }\n }\n function smoothScroll(el, x, y) {\n let scrollable;\n let startX;\n let startY;\n let method;\n const startTime = now();\n if (el === d.body) {\n scrollable = w;\n startX = w.scrollX || w.pageXOffset;\n startY = w.scrollY || w.pageYOffset;\n method = original.scroll;\n } else {\n scrollable = el;\n startX = el.scrollLeft;\n startY = el.scrollTop;\n method = scrollElement;\n }\n step({\n scrollable,\n method,\n startTime,\n startX,\n startY,\n x,\n y\n });\n }\n w.scroll = w.scrollTo = function() {\n if (arguments[0] === void 0) {\n return;\n }\n if (shouldBailOut(arguments[0]) === true) {\n original.scroll.call(\n w,\n arguments[0].left !== void 0 ? arguments[0].left : typeof arguments[0] !== \"object\" ? arguments[0] : w.scrollX || w.pageXOffset,\n // use top prop, second argument if present or fallback to scrollY\n arguments[0].top !== void 0 ? arguments[0].top : arguments[1] !== void 0 ? arguments[1] : w.scrollY || w.pageYOffset\n );\n return;\n }\n smoothScroll.call(\n w,\n d.body,\n arguments[0].left !== void 0 ? ~~arguments[0].left : w.scrollX || w.pageXOffset,\n arguments[0].top !== void 0 ? ~~arguments[0].top : w.scrollY || w.pageYOffset\n );\n };\n w.scrollBy = function() {\n if (arguments[0] === void 0) {\n return;\n }\n if (shouldBailOut(arguments[0])) {\n original.scrollBy.call(\n w,\n arguments[0].left !== void 0 ? arguments[0].left : typeof arguments[0] !== \"object\" ? arguments[0] : 0,\n arguments[0].top !== void 0 ? arguments[0].top : arguments[1] !== void 0 ? arguments[1] : 0\n );\n return;\n }\n smoothScroll.call(\n w,\n d.body,\n ~~arguments[0].left + (w.scrollX || w.pageXOffset),\n ~~arguments[0].top + (w.scrollY || w.pageYOffset)\n );\n };\n Element2.prototype.scroll = Element2.prototype.scrollTo = function() {\n if (arguments[0] === void 0) {\n return;\n }\n if (shouldBailOut(arguments[0]) === true) {\n if (typeof arguments[0] === \"number\" && arguments[1] === void 0) {\n throw new SyntaxError(\"Value could not be converted\");\n }\n original.elementScroll.call(\n this,\n // use left prop, first number argument or fallback to scrollLeft\n arguments[0].left !== void 0 ? ~~arguments[0].left : typeof arguments[0] !== \"object\" ? ~~arguments[0] : this.scrollLeft,\n // use top prop, second argument or fallback to scrollTop\n arguments[0].top !== void 0 ? ~~arguments[0].top : arguments[1] !== void 0 ? ~~arguments[1] : this.scrollTop\n );\n return;\n }\n const left = arguments[0].left;\n const top = arguments[0].top;\n smoothScroll.call(\n this,\n this,\n typeof left === \"undefined\" ? this.scrollLeft : ~~left,\n typeof top === \"undefined\" ? this.scrollTop : ~~top\n );\n };\n Element2.prototype.scrollBy = function() {\n if (arguments[0] === void 0) {\n return;\n }\n if (shouldBailOut(arguments[0]) === true) {\n original.elementScroll.call(\n this,\n arguments[0].left !== void 0 ? ~~arguments[0].left + this.scrollLeft : ~~arguments[0] + this.scrollLeft,\n arguments[0].top !== void 0 ? ~~arguments[0].top + this.scrollTop : ~~arguments[1] + this.scrollTop\n );\n return;\n }\n this.scroll({\n left: ~~arguments[0].left + this.scrollLeft,\n top: ~~arguments[0].top + this.scrollTop,\n behavior: arguments[0].behavior\n });\n };\n Element2.prototype.scrollIntoView = function() {\n if (shouldBailOut(arguments[0]) === true) {\n original.scrollIntoView.call(\n this,\n arguments[0] === void 0 ? true : arguments[0]\n );\n return;\n }\n const scrollableParent = findScrollableParent(this);\n const parentRects = scrollableParent.getBoundingClientRect();\n const clientRects = this.getBoundingClientRect();\n if (scrollableParent !== d.body) {\n smoothScroll.call(\n this,\n scrollableParent,\n scrollableParent.scrollLeft + clientRects.left - parentRects.left,\n scrollableParent.scrollTop + clientRects.top - parentRects.top\n );\n if (w.getComputedStyle(scrollableParent).position !== \"fixed\") {\n w.scrollBy({\n left: parentRects.left,\n top: parentRects.top,\n behavior: \"smooth\"\n });\n }\n } else {\n w.scrollBy({\n left: clientRects.left,\n top: clientRects.top,\n behavior: \"smooth\"\n });\n }\n };\n}\nclass Timer {\n constructor(actions = [], config) {\n this.timeOffset = 0;\n this.raf = null;\n this.actions = actions;\n this.speed = config.speed;\n }\n /**\n * Add an action, possibly after the timer starts.\n */\n addAction(action) {\n const rafWasActive = this.raf === true;\n if (!this.actions.length || this.actions[this.actions.length - 1].delay <= action.delay) {\n this.actions.push(action);\n } else {\n const index = this.findActionIndex(action);\n this.actions.splice(index, 0, action);\n }\n if (rafWasActive) {\n this.raf = onRequestAnimationFrame(this.rafCheck.bind(this));\n }\n }\n start() {\n this.timeOffset = 0;\n this.lastTimestamp = performance.now();\n this.raf = onRequestAnimationFrame(this.rafCheck.bind(this));\n }\n rafCheck() {\n const time = performance.now();\n this.timeOffset += (time - this.lastTimestamp) * this.speed;\n this.lastTimestamp = time;\n while (this.actions.length) {\n const action = this.actions[0];\n if (this.timeOffset >= action.delay) {\n this.actions.shift();\n action.doAction();\n } else {\n break;\n }\n }\n if (this.actions.length > 0) {\n this.raf = onRequestAnimationFrame(this.rafCheck.bind(this));\n } else {\n this.raf = true;\n }\n }\n clear() {\n if (this.raf) {\n if (this.raf !== true) {\n cancelAnimationFrame(this.raf);\n }\n this.raf = null;\n }\n this.actions.length = 0;\n }\n setSpeed(speed) {\n this.speed = speed;\n }\n isActive() {\n return this.raf !== null;\n }\n findActionIndex(action) {\n let start = 0;\n let end = this.actions.length - 1;\n while (start <= end) {\n const mid = Math.floor((start + end) / 2);\n if (this.actions[mid].delay < action.delay) {\n start = mid + 1;\n } else if (this.actions[mid].delay > action.delay) {\n end = mid - 1;\n } else {\n return mid + 1;\n }\n }\n return start;\n }\n}\nfunction addDelay(event, baselineTime) {\n if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.MouseMove && event.data.positions && event.data.positions.length) {\n const firstOffset = event.data.positions[0].timeOffset;\n const firstTimestamp = event.timestamp + firstOffset;\n event.delay = firstTimestamp - baselineTime;\n return firstTimestamp - baselineTime;\n }\n event.delay = event.timestamp - baselineTime;\n return event.delay;\n}\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\nfunction t(t2, n2) {\n var e2 = \"function\" == typeof Symbol && t2[Symbol.iterator];\n if (!e2) return t2;\n var r2, o2, i2 = e2.call(t2), a2 = [];\n try {\n for (; (void 0 === n2 || n2-- > 0) && !(r2 = i2.next()).done; ) a2.push(r2.value);\n } catch (t3) {\n o2 = { error: t3 };\n } finally {\n try {\n r2 && !r2.done && (e2 = i2.return) && e2.call(i2);\n } finally {\n if (o2) throw o2.error;\n }\n }\n return a2;\n}\nvar n;\n!function(t2) {\n t2[t2.NotStarted = 0] = \"NotStarted\", t2[t2.Running = 1] = \"Running\", t2[t2.Stopped = 2] = \"Stopped\";\n}(n || (n = {}));\nvar e = { type: \"xstate.init\" };\nfunction r(t2) {\n return void 0 === t2 ? [] : [].concat(t2);\n}\nfunction o(t2) {\n return { type: \"xstate.assign\", assignment: t2 };\n}\nfunction i(t2, n2) {\n return \"string\" == typeof (t2 = \"string\" == typeof t2 && n2 && n2[t2] ? n2[t2] : t2) ? { type: t2 } : \"function\" == typeof t2 ? { type: t2.name, exec: t2 } : t2;\n}\nfunction a(t2) {\n return function(n2) {\n return t2 === n2;\n };\n}\nfunction u(t2) {\n return \"string\" == typeof t2 ? { type: t2 } : t2;\n}\nfunction c(t2, n2) {\n return { value: t2, context: n2, actions: [], changed: false, matches: a(t2) };\n}\nfunction f(t2, n2, e2) {\n var r2 = n2, o2 = false;\n return [t2.filter(function(t3) {\n if (\"xstate.assign\" === t3.type) {\n o2 = true;\n var n3 = Object.assign({}, r2);\n return \"function\" == typeof t3.assignment ? n3 = t3.assignment(r2, e2) : Object.keys(t3.assignment).forEach(function(o3) {\n n3[o3] = \"function\" == typeof t3.assignment[o3] ? t3.assignment[o3](r2, e2) : t3.assignment[o3];\n }), r2 = n3, false;\n }\n return true;\n }), r2, o2];\n}\nfunction s(n2, o2) {\n void 0 === o2 && (o2 = {});\n var s2 = t(f(r(n2.states[n2.initial].entry).map(function(t2) {\n return i(t2, o2.actions);\n }), n2.context, e), 2), l2 = s2[0], v2 = s2[1], y = { config: n2, _options: o2, initialState: { value: n2.initial, actions: l2, context: v2, matches: a(n2.initial) }, transition: function(e2, o3) {\n var s3, l3, v3 = \"string\" == typeof e2 ? { value: e2, context: n2.context } : e2, p = v3.value, g = v3.context, d = u(o3), x = n2.states[p];\n if (x.on) {\n var m = r(x.on[d.type]);\n try {\n for (var h = function(t2) {\n var n3 = \"function\" == typeof Symbol && Symbol.iterator, e3 = n3 && t2[n3], r2 = 0;\n if (e3) return e3.call(t2);\n if (t2 && \"number\" == typeof t2.length) return { next: function() {\n return t2 && r2 >= t2.length && (t2 = void 0), { value: t2 && t2[r2++], done: !t2 };\n } };\n throw new TypeError(n3 ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n }(m), b = h.next(); !b.done; b = h.next()) {\n var S = b.value;\n if (void 0 === S) return c(p, g);\n var w = \"string\" == typeof S ? { target: S } : S, j = w.target, E = w.actions, R = void 0 === E ? [] : E, N = w.cond, O = void 0 === N ? function() {\n return true;\n } : N, _ = void 0 === j, k = null != j ? j : p, T = n2.states[k];\n if (O(g, d)) {\n var q = t(f((_ ? r(R) : [].concat(x.exit, R, T.entry).filter(function(t2) {\n return t2;\n })).map(function(t2) {\n return i(t2, y._options.actions);\n }), g, d), 3), z = q[0], A = q[1], B = q[2], C = null != j ? j : p;\n return { value: C, context: A, actions: z, changed: j !== p || z.length > 0 || B, matches: a(C) };\n }\n }\n } catch (t2) {\n s3 = { error: t2 };\n } finally {\n try {\n b && !b.done && (l3 = h.return) && l3.call(h);\n } finally {\n if (s3) throw s3.error;\n }\n }\n }\n return c(p, g);\n } };\n return y;\n}\nvar l = function(t2, n2) {\n return t2.actions.forEach(function(e2) {\n var r2 = e2.exec;\n return r2 && r2(t2.context, n2);\n });\n};\nfunction v(t2) {\n var r2 = t2.initialState, o2 = n.NotStarted, i2 = /* @__PURE__ */ new Set(), c2 = { _machine: t2, send: function(e2) {\n o2 === n.Running && (r2 = t2.transition(r2, e2), l(r2, u(e2)), i2.forEach(function(t3) {\n return t3(r2);\n }));\n }, subscribe: function(t3) {\n return i2.add(t3), t3(r2), { unsubscribe: function() {\n return i2.delete(t3);\n } };\n }, start: function(i3) {\n if (i3) {\n var u2 = \"object\" == typeof i3 ? i3 : { context: t2.config.context, value: i3 };\n r2 = { value: u2.value, actions: [], context: u2.context, matches: a(u2.value) };\n }\n return o2 = n.Running, l(r2, e), c2;\n }, stop: function() {\n return o2 = n.Stopped, i2.clear(), c2;\n }, get state() {\n return r2;\n }, get status() {\n return o2;\n } };\n return c2;\n}\nfunction discardPriorSnapshots(events, baselineTime) {\n for (let idx = events.length - 1; idx >= 0; idx--) {\n const event = events[idx];\n if (event.type === EventType.Meta) {\n if (event.timestamp <= baselineTime) {\n return events.slice(idx);\n }\n }\n }\n return events;\n}\nfunction createPlayerService(context, { getCastFn, applyEventsSynchronously, emitter }) {\n const playerMachine = s(\n {\n id: \"player\",\n context,\n initial: \"paused\",\n states: {\n playing: {\n on: {\n PAUSE: {\n target: \"paused\",\n actions: [\"pause\"]\n },\n CAST_EVENT: {\n target: \"playing\",\n actions: \"castEvent\"\n },\n END: {\n target: \"paused\",\n actions: [\"resetLastPlayedEvent\", \"pause\"]\n },\n ADD_EVENT: {\n target: \"playing\",\n actions: [\"addEvent\"]\n }\n }\n },\n paused: {\n on: {\n PLAY: {\n target: \"playing\",\n actions: [\"recordTimeOffset\", \"play\"]\n },\n CAST_EVENT: {\n target: \"paused\",\n actions: \"castEvent\"\n },\n TO_LIVE: {\n target: \"live\",\n actions: [\"startLive\"]\n },\n ADD_EVENT: {\n target: \"paused\",\n actions: [\"addEvent\"]\n }\n }\n },\n live: {\n on: {\n ADD_EVENT: {\n target: \"live\",\n actions: [\"addEvent\"]\n },\n CAST_EVENT: {\n target: \"live\",\n actions: [\"castEvent\"]\n }\n }\n }\n }\n },\n {\n actions: {\n castEvent: o({\n lastPlayedEvent: (ctx, event) => {\n if (event.type === \"CAST_EVENT\") {\n return event.payload.event;\n }\n return ctx.lastPlayedEvent;\n }\n }),\n recordTimeOffset: o((ctx, event) => {\n let timeOffset = ctx.timeOffset;\n if (\"payload\" in event && \"timeOffset\" in event.payload) {\n timeOffset = event.payload.timeOffset;\n }\n return {\n ...ctx,\n timeOffset,\n baselineTime: ctx.events[0].timestamp + timeOffset\n };\n }),\n play(ctx) {\n const { timer, events, baselineTime, lastPlayedEvent } = ctx;\n timer.clear();\n for (const event of events) {\n addDelay(event, baselineTime);\n }\n const neededEvents = discardPriorSnapshots(events, baselineTime);\n let lastPlayedTimestamp = lastPlayedEvent?.timestamp;\n if (lastPlayedEvent?.type === EventType.IncrementalSnapshot && lastPlayedEvent.data.source === IncrementalSource.MouseMove) {\n lastPlayedTimestamp = lastPlayedEvent.timestamp + lastPlayedEvent.data.positions[0]?.timeOffset;\n }\n if (baselineTime < (lastPlayedTimestamp || 0)) {\n emitter.emit(ReplayerEvents.PlayBack);\n }\n const syncEvents = new Array();\n for (const event of neededEvents) {\n if (lastPlayedTimestamp && lastPlayedTimestamp < baselineTime && (event.timestamp <= lastPlayedTimestamp || event === lastPlayedEvent)) {\n continue;\n }\n if (event.timestamp < baselineTime) {\n syncEvents.push(event);\n } else {\n const castFn = getCastFn(event, false);\n timer.addAction({\n doAction: () => {\n castFn();\n },\n delay: event.delay\n });\n }\n }\n applyEventsSynchronously(syncEvents);\n emitter.emit(ReplayerEvents.Flush);\n timer.start();\n },\n pause(ctx) {\n ctx.timer.clear();\n },\n resetLastPlayedEvent: o((ctx) => {\n return {\n ...ctx,\n lastPlayedEvent: null\n };\n }),\n startLive: o({\n baselineTime: (ctx, event) => {\n ctx.timer.start();\n if (event.type === \"TO_LIVE\" && event.payload.baselineTime) {\n return event.payload.baselineTime;\n }\n return Date.now();\n }\n }),\n addEvent: o((ctx, machineEvent) => {\n const { baselineTime, timer, events } = ctx;\n if (machineEvent.type === \"ADD_EVENT\") {\n const { event } = machineEvent.payload;\n addDelay(event, baselineTime);\n let end = events.length - 1;\n if (!events[end] || events[end].timestamp <= event.timestamp) {\n events.push(event);\n } else {\n let insertionIndex = -1;\n let start = 0;\n while (start <= end) {\n const mid = Math.floor((start + end) / 2);\n if (events[mid].timestamp <= event.timestamp) {\n start = mid + 1;\n } else {\n end = mid - 1;\n }\n }\n if (insertionIndex === -1) {\n insertionIndex = start;\n }\n events.splice(insertionIndex, 0, event);\n }\n const isSync = event.timestamp < baselineTime;\n const castFn = getCastFn(event, isSync);\n if (isSync) {\n castFn();\n } else if (timer.isActive()) {\n timer.addAction({\n doAction: () => {\n castFn();\n },\n delay: event.delay\n });\n }\n }\n return { ...ctx, events };\n })\n }\n }\n );\n return v(playerMachine);\n}\nfunction createSpeedService(context) {\n const speedMachine = s(\n {\n id: \"speed\",\n context,\n initial: \"normal\",\n states: {\n normal: {\n on: {\n FAST_FORWARD: {\n target: \"skipping\",\n actions: [\"recordSpeed\", \"setSpeed\"]\n },\n SET_SPEED: {\n target: \"normal\",\n actions: [\"setSpeed\"]\n }\n }\n },\n skipping: {\n on: {\n BACK_TO_NORMAL: {\n target: \"normal\",\n actions: [\"restoreSpeed\"]\n },\n SET_SPEED: {\n target: \"normal\",\n actions: [\"setSpeed\"]\n }\n }\n }\n }\n },\n {\n actions: {\n setSpeed: (ctx, event) => {\n if (\"payload\" in event) {\n ctx.timer.setSpeed(event.payload.speed);\n }\n },\n recordSpeed: o({\n normalSpeed: (ctx) => ctx.timer.speed\n }),\n restoreSpeed: (ctx) => {\n ctx.timer.setSpeed(ctx.normalSpeed);\n }\n }\n }\n );\n return v(speedMachine);\n}\nconst rules = (blockClass) => [\n `.${blockClass} { background: currentColor }`,\n \"noscript { display: none !important; }\"\n];\nconst webGLVarMap = /* @__PURE__ */ new Map();\nfunction variableListFor(ctx, ctor) {\n let contextMap = webGLVarMap.get(ctx);\n if (!contextMap) {\n contextMap = /* @__PURE__ */ new Map();\n webGLVarMap.set(ctx, contextMap);\n }\n if (!contextMap.has(ctor)) {\n contextMap.set(ctor, []);\n }\n return contextMap.get(ctor);\n}\nfunction deserializeArg(imageMap, ctx, preload) {\n return async (arg) => {\n if (arg && typeof arg === \"object\" && \"rr_type\" in arg) {\n if (preload) preload.isUnchanged = false;\n if (arg.rr_type === \"ImageBitmap\" && \"args\" in arg) {\n const args = await deserializeArg(imageMap, ctx, preload)(arg.args);\n return await createImageBitmap.apply(null, args);\n } else if (\"index\" in arg) {\n if (preload || ctx === null) return arg;\n const { rr_type: name, index } = arg;\n return variableListFor(ctx, name)[index];\n } else if (\"args\" in arg) {\n const { rr_type: name, args } = arg;\n const ctor = window[name];\n return new ctor(\n ...await Promise.all(\n args.map(deserializeArg(imageMap, ctx, preload))\n )\n );\n } else if (\"base64\" in arg) {\n return decode(arg.base64);\n } else if (\"src\" in arg) {\n const image = imageMap.get(arg.src);\n if (image) {\n return image;\n } else {\n const image2 = new Image();\n image2.src = arg.src;\n imageMap.set(arg.src, image2);\n return image2;\n }\n } else if (\"data\" in arg && arg.rr_type === \"Blob\") {\n const blobContents = await Promise.all(\n arg.data.map(deserializeArg(imageMap, ctx, preload))\n );\n const blob = new Blob(blobContents, {\n type: arg.type\n });\n return blob;\n }\n } else if (Array.isArray(arg)) {\n const result = await Promise.all(\n arg.map(deserializeArg(imageMap, ctx, preload))\n );\n return result;\n }\n return arg;\n };\n}\nfunction getContext(target, type) {\n try {\n if (type === CanvasContext.WebGL) {\n return target.getContext(\"webgl\") || target.getContext(\"experimental-webgl\");\n }\n return target.getContext(\"webgl2\");\n } catch (e2) {\n return null;\n }\n}\nconst WebGLVariableConstructorsNames = [\n \"WebGLActiveInfo\",\n \"WebGLBuffer\",\n \"WebGLFramebuffer\",\n \"WebGLProgram\",\n \"WebGLRenderbuffer\",\n \"WebGLShader\",\n \"WebGLShaderPrecisionFormat\",\n \"WebGLTexture\",\n \"WebGLUniformLocation\",\n \"WebGLVertexArrayObject\"\n];\nfunction saveToWebGLVarMap(ctx, result) {\n if (!result?.constructor) return;\n const { name } = result.constructor;\n if (!WebGLVariableConstructorsNames.includes(name)) return;\n const variables = variableListFor(ctx, name);\n if (!variables.includes(result)) variables.push(result);\n}\nasync function webglMutation({\n mutation,\n target,\n type,\n imageMap,\n errorHandler: errorHandler2\n}) {\n try {\n const ctx = getContext(target, type);\n if (!ctx) return;\n if (mutation.setter) {\n ctx[mutation.property] = mutation.args[0];\n return;\n }\n const original = ctx[mutation.property];\n const args = await Promise.all(\n mutation.args.map(deserializeArg(imageMap, ctx))\n );\n const result = original.apply(ctx, args);\n saveToWebGLVarMap(ctx, result);\n const debugMode = false;\n if (debugMode) ;\n } catch (error) {\n errorHandler2(mutation, error);\n }\n}\nasync function canvasMutation$1({\n event,\n mutations,\n target,\n imageMap,\n errorHandler: errorHandler2\n}) {\n const ctx = target.getContext(\"2d\");\n if (!ctx) {\n errorHandler2(mutations[0], new Error(\"Canvas context is null\"));\n return;\n }\n const mutationArgsPromises = mutations.map(\n async (mutation) => {\n return Promise.all(mutation.args.map(deserializeArg(imageMap, ctx)));\n }\n );\n const args = await Promise.all(mutationArgsPromises);\n args.forEach((args2, index) => {\n const mutation = mutations[index];\n try {\n if (mutation.setter) {\n ctx[mutation.property] = mutation.args[0];\n return;\n }\n const original = ctx[mutation.property];\n if (mutation.property === \"drawImage\" && typeof mutation.args[0] === \"string\") {\n imageMap.get(event);\n original.apply(ctx, mutation.args);\n } else {\n original.apply(ctx, args2);\n }\n } catch (error) {\n errorHandler2(mutation, error);\n }\n return;\n });\n}\nasync function canvasMutation({\n event,\n mutation,\n target,\n imageMap,\n canvasEventMap,\n errorHandler: errorHandler2\n}) {\n try {\n const precomputedMutation = canvasEventMap.get(event) || mutation;\n const commands = \"commands\" in precomputedMutation ? precomputedMutation.commands : [precomputedMutation];\n if ([CanvasContext.WebGL, CanvasContext.WebGL2].includes(mutation.type)) {\n for (let i2 = 0; i2 < commands.length; i2++) {\n const command = commands[i2];\n await webglMutation({\n mutation: command,\n type: mutation.type,\n target,\n imageMap,\n errorHandler: errorHandler2\n });\n }\n return;\n }\n await canvasMutation$1({\n event,\n mutations: commands,\n target,\n imageMap,\n errorHandler: errorHandler2\n });\n } catch (error) {\n errorHandler2(mutation, error);\n }\n}\nconst SKIP_TIME_INTERVAL = 5 * 1e3;\nconst mitt = mitt$1 || mittProxy;\nconst REPLAY_CONSOLE_PREFIX = \"[replayer]\";\nfunction getEventIndex(events, eventTime) {\n let result = -1;\n if (events.length === 0) {\n return result;\n }\n let left = 0, right = events.length - 1;\n while (left <= right) {\n const mid = Math.floor((left + right) / 2);\n if (events[mid].timestamp <= eventTime) {\n result = mid;\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n return result;\n}\nconst defaultMouseTailConfig = {\n duration: 500,\n lineCap: \"round\",\n lineWidth: 3,\n strokeStyle: \"red\"\n};\nfunction indicatesTouchDevice(e2) {\n return e2.type == EventType.IncrementalSnapshot && (e2.data.source == IncrementalSource.TouchMove || e2.data.source == IncrementalSource.MouseInteraction && e2.data.type == MouseInteractions.TouchStart);\n}\nfunction getPointerId(d) {\n const pointerId = \"pointerId\" in d && typeof d.pointerId === \"number\" ? d.pointerId : -1;\n return pointerId;\n}\nclass Replayer {\n constructor(events, config) {\n this.usingVirtualDom = false;\n this.virtualDom = new RRDocument();\n this.emitter = mitt();\n this.legacy_missingNodeRetryMap = {};\n this.cache = createCache();\n this.imageMap = /* @__PURE__ */ new Map();\n this.canvasEventMap = /* @__PURE__ */ new Map();\n this.mirror = createMirror$2();\n this.styleMirror = new StyleSheetMirror();\n this.firstFullSnapshot = null;\n this.newDocumentQueue = [];\n this.pointers = {};\n this.lastMouseDownEvent = null;\n this.lastSelectionData = null;\n this.constructedStyleMutations = [];\n this.adoptedStyleSheets = [];\n this.handleResize = (dimension) => {\n this.iframe.style.display = \"inherit\";\n for (const el of [\n ...Object.values(this.pointers).flatMap((a2) => a2.mouseTail),\n this.iframe\n ]) {\n if (!el) {\n continue;\n }\n el.setAttribute(\"width\", String(dimension.width));\n el.setAttribute(\"height\", String(dimension.height));\n }\n };\n this.applyEventsSynchronously = (events2) => {\n for (const event of events2) {\n switch (event.type) {\n case EventType.DomContentLoaded:\n case EventType.Load:\n case EventType.Custom:\n continue;\n case EventType.FullSnapshot:\n case EventType.Meta:\n case EventType.Plugin:\n case EventType.IncrementalSnapshot:\n break;\n }\n const castFn = this.getCastFn(event, true);\n castFn();\n }\n };\n this.getCastFn = (event, isSync = false) => {\n let castFn;\n switch (event.type) {\n case EventType.DomContentLoaded:\n case EventType.Load:\n break;\n case EventType.Custom:\n castFn = () => {\n this.emitter.emit(ReplayerEvents.CustomEvent, event);\n };\n break;\n case EventType.Meta:\n castFn = () => this.emitter.emit(ReplayerEvents.Resize, {\n width: event.data.width,\n height: event.data.height\n });\n break;\n case EventType.FullSnapshot:\n castFn = () => {\n if (this.firstFullSnapshot) {\n if (this.firstFullSnapshot === event) {\n this.firstFullSnapshot = true;\n return;\n }\n } else {\n this.firstFullSnapshot = true;\n }\n this.rebuildFullSnapshot(event, isSync);\n this.iframe.contentWindow?.scrollTo(event.data.initialOffset);\n this.styleMirror.reset();\n };\n break;\n case EventType.IncrementalSnapshot:\n castFn = () => {\n this.applyIncremental(event, isSync);\n if (isSync) {\n return;\n }\n if (event === this.nextUserInteractionEvent) {\n this.nextUserInteractionEvent = null;\n this.backToNormal();\n }\n if (this.config.skipInactive && !this.nextUserInteractionEvent) {\n for (const _event of this.service.state.context.events) {\n if (_event.timestamp <= event.timestamp) {\n continue;\n }\n if (this.isUserInteraction(_event)) {\n if (\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n _event.delay - event.delay > this.config.inactivePeriodThreshold * this.speedService.state.context.timer.speed\n ) {\n this.nextUserInteractionEvent = _event;\n }\n break;\n }\n }\n if (this.nextUserInteractionEvent) {\n const skipTime = (\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.nextUserInteractionEvent.delay - event.delay\n );\n const payload = {\n speed: Math.min(\n Math.round(skipTime / SKIP_TIME_INTERVAL),\n this.config.maxSpeed\n )\n };\n this.speedService.send({ type: \"FAST_FORWARD\", payload });\n this.emitter.emit(ReplayerEvents.SkipStart, payload);\n }\n }\n };\n break;\n }\n const wrappedCastFn = () => {\n if (castFn) {\n castFn();\n }\n for (const plugin of this.config.plugins || []) {\n if (plugin.handler) plugin.handler(event, isSync, { replayer: this });\n }\n this.service.send({ type: \"CAST_EVENT\", payload: { event } });\n const last_index = this.service.state.context.events.length - 1;\n if (!this.config.liveMode && event === this.service.state.context.events[last_index]) {\n const finish = () => {\n if (last_index < this.service.state.context.events.length - 1) {\n return;\n }\n this.backToNormal();\n this.service.send(\"END\");\n this.emitter.emit(ReplayerEvents.Finish);\n };\n let finish_buffer = 50;\n if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.MouseMove && event.data.positions.length) {\n finish_buffer += Math.max(0, -event.data.positions[0].timeOffset);\n }\n setTimeout$1(finish, finish_buffer);\n }\n this.emitter.emit(ReplayerEvents.EventCast, event);\n };\n return wrappedCastFn;\n };\n if (!config?.liveMode && events.length < 2) {\n throw new Error(\"Replayer need at least 2 events.\");\n }\n const defaultConfig = {\n speed: 1,\n maxSpeed: 360,\n root: document.body,\n loadTimeout: 0,\n skipInactive: false,\n inactivePeriodThreshold: 10 * 1e3,\n showWarning: true,\n showDebug: false,\n blockClass: \"rr-block\",\n liveMode: false,\n insertStyleRules: [],\n triggerFocus: true,\n UNSAFE_replayCanvas: false,\n pauseAnimation: true,\n mouseTail: defaultMouseTailConfig,\n useVirtualDom: true,\n // Virtual-dom optimization is enabled by default.\n logger: console\n };\n this.config = Object.assign({}, defaultConfig, config);\n this.handleResize = this.handleResize.bind(this);\n this.getCastFn = this.getCastFn.bind(this);\n this.applyEventsSynchronously = this.applyEventsSynchronously.bind(this);\n this.emitter.on(ReplayerEvents.Resize, this.handleResize);\n this.setupDom();\n for (const plugin of this.config.plugins || []) {\n if (plugin.getMirror) plugin.getMirror({ nodeMirror: this.mirror });\n }\n this.emitter.on(ReplayerEvents.Flush, () => {\n if (this.usingVirtualDom) {\n const replayerHandler = {\n mirror: this.mirror,\n applyCanvas: (canvasEvent, canvasMutationData2, target) => {\n void canvasMutation({\n event: canvasEvent,\n mutation: canvasMutationData2,\n target,\n imageMap: this.imageMap,\n canvasEventMap: this.canvasEventMap,\n errorHandler: this.warnCanvasMutationFailed.bind(this)\n });\n },\n applyInput: this.applyInput.bind(this),\n applyScroll: this.applyScroll.bind(this),\n applyStyleSheetMutation: (data, styleSheet) => {\n if (data.source === IncrementalSource.StyleSheetRule)\n this.applyStyleSheetRule(data, styleSheet);\n else if (data.source === IncrementalSource.StyleDeclaration)\n this.applyStyleDeclaration(data, styleSheet);\n },\n afterAppend: (node, id) => {\n for (const plugin of this.config.plugins || []) {\n if (plugin.onBuild) plugin.onBuild(node, { id, replayer: this });\n }\n }\n };\n const iframeDoc = getIFrameContentDocument(this.iframe);\n if (iframeDoc)\n try {\n diff(\n iframeDoc,\n this.virtualDom,\n replayerHandler,\n this.virtualDom.mirror\n );\n } catch (e2) {\n console.warn(e2);\n }\n this.virtualDom.destroyTree();\n this.usingVirtualDom = false;\n if (Object.keys(this.legacy_missingNodeRetryMap).length) {\n for (const key in this.legacy_missingNodeRetryMap) {\n try {\n const value = this.legacy_missingNodeRetryMap[key];\n const realNode = createOrGetNode(\n value.node,\n this.mirror,\n this.virtualDom.mirror\n );\n diff(\n realNode,\n value.node,\n replayerHandler,\n this.virtualDom.mirror\n );\n value.node = realNode;\n } catch (error) {\n this.warn(error);\n }\n }\n }\n this.constructedStyleMutations.forEach((data) => {\n this.applyStyleSheetMutation(data);\n });\n this.constructedStyleMutations = [];\n this.adoptedStyleSheets.forEach((data) => {\n this.applyAdoptedStyleSheet(data);\n });\n this.adoptedStyleSheets = [];\n }\n for (const [\n pointerId,\n { pointerPosition, touchActive }\n ] of Object.entries(this.pointers)) {\n const id = parseInt(pointerId);\n const pointer = this.pointers[id];\n if (pointerPosition) {\n this.moveAndHover(\n pointerPosition.x,\n pointerPosition.y,\n pointerPosition.id,\n true,\n pointerPosition.debugData,\n id\n );\n pointer.pointerPosition = null;\n }\n if (touchActive === true) {\n pointer.pointerEl.classList.add(\"touch-active\");\n } else if (touchActive === false) {\n pointer.pointerEl.classList.remove(\"touch-active\");\n }\n pointer.touchActive = null;\n }\n if (this.lastMouseDownEvent) {\n const [target, event] = this.lastMouseDownEvent;\n target.dispatchEvent(event);\n }\n this.lastMouseDownEvent = null;\n if (this.lastSelectionData) {\n this.applySelection(this.lastSelectionData);\n this.lastSelectionData = null;\n }\n });\n this.emitter.on(ReplayerEvents.PlayBack, () => {\n this.firstFullSnapshot = null;\n this.mirror.reset();\n this.styleMirror.reset();\n });\n const timer = new Timer([], {\n speed: this.config.speed\n });\n this.service = createPlayerService(\n {\n events: events.map((e2) => {\n if (config && config.unpackFn) {\n return config.unpackFn(e2);\n }\n return e2;\n }).sort((a1, a2) => a1.timestamp - a2.timestamp),\n timer,\n timeOffset: 0,\n baselineTime: 0,\n lastPlayedEvent: null\n },\n {\n getCastFn: this.getCastFn,\n applyEventsSynchronously: this.applyEventsSynchronously,\n emitter: this.emitter\n }\n );\n this.service.start();\n this.service.subscribe((state) => {\n this.emitter.emit(ReplayerEvents.StateChange, {\n player: state\n });\n });\n this.speedService = createSpeedService({\n normalSpeed: -1,\n timer\n });\n this.speedService.start();\n this.speedService.subscribe((state) => {\n this.emitter.emit(ReplayerEvents.StateChange, {\n speed: state\n });\n });\n const firstMeta = this.service.state.context.events.find(\n (e2) => e2.type === EventType.Meta\n );\n const firstFullsnapshot = this.service.state.context.events.find(\n (e2) => e2.type === EventType.FullSnapshot\n );\n if (firstMeta) {\n const { width, height } = firstMeta.data;\n setTimeout$1(() => {\n this.emitter.emit(ReplayerEvents.Resize, {\n width,\n height\n });\n }, 0);\n }\n if (firstFullsnapshot) {\n setTimeout$1(() => {\n if (this.firstFullSnapshot) {\n return;\n }\n this.firstFullSnapshot = firstFullsnapshot;\n this.rebuildFullSnapshot(\n firstFullsnapshot\n );\n this.iframe.contentWindow?.scrollTo(\n firstFullsnapshot.data.initialOffset\n );\n }, 1);\n }\n }\n get timer() {\n return this.service.state.context.timer;\n }\n createPointer(pointerId, event) {\n const mouseTail = document.createElement(\"canvas\");\n mouseTail.classList.add(\"replayer-mouse-tail\");\n mouseTail.width = Number.parseFloat(this.iframe.width);\n mouseTail.height = Number.parseFloat(this.iframe.height);\n this.wrapper.insertBefore(mouseTail, this.iframe);\n mouseTail.style.display = this.config.mouseTail === false ? \"none\" : \"inherit\";\n const newMouse = document.createElement(\"div\");\n newMouse.classList.add(\"replayer-mouse\");\n this.pointers[pointerId] = {\n touchActive: null,\n pointerEl: newMouse,\n tailPositions: [],\n pointerPosition: null,\n mouseTail\n };\n if (indicatesTouchDevice(event)) {\n newMouse.classList.add(\"touch-device\");\n }\n this.wrapper.appendChild(newMouse);\n }\n on(event, handler) {\n this.emitter.on(event, handler);\n return this;\n }\n off(event, handler) {\n this.emitter.off(event, handler);\n return this;\n }\n setConfig(config) {\n const previousSkipInactive = this.config.skipInactive;\n Object.keys(config).forEach((key) => {\n config[key];\n this.config[key] = config[key];\n });\n if (!this.config.skipInactive) {\n this.backToNormal();\n } else if (previousSkipInactive === false && this.config.skipInactive === true) {\n this.reevaluateFastForward();\n }\n if (typeof config.speed !== \"undefined\") {\n this.speedService.send({\n type: \"SET_SPEED\",\n payload: {\n speed: config.speed\n }\n });\n }\n if (typeof config.mouseTail !== \"undefined\") {\n if (config.mouseTail === false) {\n for (const { mouseTail } of Object.values(this.pointers)) {\n if (mouseTail) {\n mouseTail.style.display = \"none\";\n }\n }\n } else {\n for (let { mouseTail } of Object.values(this.pointers)) {\n if (!mouseTail) {\n mouseTail = document.createElement(\"canvas\");\n mouseTail.width = Number.parseFloat(this.iframe.width);\n mouseTail.height = Number.parseFloat(this.iframe.height);\n mouseTail.classList.add(\"replayer-mouse-tail\");\n this.wrapper.insertBefore(mouseTail, this.iframe);\n }\n mouseTail.style.display = \"inherit\";\n }\n }\n }\n }\n getMetaData() {\n const firstEvent = this.service.state.context.events[0];\n const lastEvent = this.service.state.context.events[this.service.state.context.events.length - 1];\n return {\n startTime: firstEvent.timestamp,\n endTime: lastEvent.timestamp,\n totalTime: lastEvent.timestamp - firstEvent.timestamp\n };\n }\n getCurrentTime() {\n return this.timer.timeOffset + this.getTimeOffset();\n }\n getTimeOffset() {\n const { baselineTime, events } = this.service.state.context;\n return baselineTime - events[0].timestamp;\n }\n getMirror() {\n return this.mirror;\n }\n /**\n * This API was designed to be used as play at any time offset.\n * Since we minimized the data collected from recorder, we do not\n * have the ability of undo an event.\n * So the implementation of play at any time offset will always iterate\n * all of the events, cast event before the offset synchronously\n * and cast event after the offset asynchronously with timer.\n * @param timeOffset - number\n */\n play(timeOffset = 0) {\n if (this.config.skipInactive && this.speedService.state.matches(\"skipping\")) {\n this.backToNormal();\n }\n if (this.service.state.matches(\"paused\")) {\n this.service.send({ type: \"PLAY\", payload: { timeOffset } });\n } else {\n this.service.send({ type: \"PAUSE\" });\n this.service.send({ type: \"PLAY\", payload: { timeOffset } });\n }\n const iframeDoc = getIFrameContentDocument(this.iframe);\n iframeDoc?.getElementsByTagName(\"html\")[0]?.classList.remove(\"rrweb-paused\");\n this.emitter.emit(ReplayerEvents.Start);\n if (this.config.skipInactive) {\n this.reevaluateFastForward();\n }\n }\n pause(timeOffset) {\n if (timeOffset === void 0 && this.service.state.matches(\"playing\")) {\n this.service.send({ type: \"PAUSE\" });\n }\n if (typeof timeOffset === \"number\") {\n this.play(timeOffset);\n this.service.send({ type: \"PAUSE\" });\n }\n const iframeDoc = getIFrameContentDocument(this.iframe);\n iframeDoc?.getElementsByTagName(\"html\")[0]?.classList.add(\"rrweb-paused\");\n this.emitter.emit(ReplayerEvents.Pause);\n }\n resume(timeOffset = 0) {\n this.warn(\n `The 'resume' was deprecated in 1.0. Please use 'play' method which has the same interface.`\n );\n this.play(timeOffset);\n this.emitter.emit(ReplayerEvents.Resume);\n }\n /**\n * Totally destroy this replayer and please be careful that this operation is irreversible.\n * Memory occupation can be released by removing all references to this replayer.\n */\n destroy() {\n this.pause();\n this.config.root.removeChild(this.wrapper);\n this.emitter.emit(ReplayerEvents.Destroy);\n }\n startLive(baselineTime) {\n this.service.send({ type: \"TO_LIVE\", payload: { baselineTime } });\n }\n addEvent(rawEvent) {\n const event = this.config.unpackFn ? this.config.unpackFn(rawEvent) : rawEvent;\n void Promise.resolve().then(\n () => this.service.send({ type: \"ADD_EVENT\", payload: { event } })\n );\n }\n enableInteract() {\n this.iframe.setAttribute(\"scrolling\", \"auto\");\n this.iframe.style.pointerEvents = \"auto\";\n }\n disableInteract() {\n this.iframe.setAttribute(\"scrolling\", \"no\");\n this.iframe.style.pointerEvents = \"none\";\n }\n /**\n * Empties the replayer's cache and reclaims memory.\n * The replayer will use this cache to speed up the playback.\n */\n resetCache() {\n this.cache = createCache();\n }\n reevaluateFastForward() {\n if (!this.config.skipInactive) {\n return;\n }\n this.nextUserInteractionEvent = null;\n const events = this.service.state.context.events;\n const firstEvent = events[0];\n if (!firstEvent) {\n return;\n }\n const currentEventTime = firstEvent.timestamp + this.getCurrentTime();\n const currentEventIndex = getEventIndex(events, currentEventTime);\n if (currentEventIndex === -1) {\n return;\n }\n const currentEvent = events[currentEventIndex];\n const threshold = this.config.inactivePeriodThreshold * this.speedService.state.context.timer.speed;\n for (let i2 = currentEventIndex + 1; i2 < events.length; i2++) {\n const event = events[i2];\n if (this.isUserInteraction(event)) {\n const gapTime = event.timestamp - currentEvent.timestamp;\n if (gapTime > threshold) {\n this.nextUserInteractionEvent = event;\n const payload = {\n speed: Math.min(\n Math.round(gapTime / SKIP_TIME_INTERVAL),\n this.config.maxSpeed\n )\n };\n this.speedService.send({ type: \"FAST_FORWARD\", payload });\n this.emitter.emit(ReplayerEvents.SkipStart, payload);\n }\n break;\n }\n }\n }\n setupDom() {\n this.wrapper = document.createElement(\"div\");\n this.wrapper.classList.add(\"replayer-wrapper\");\n this.config.root.appendChild(this.wrapper);\n this.iframe = document.createElement(\"iframe\");\n const attributes2 = [\"allow-same-origin\"];\n if (this.config.UNSAFE_replayCanvas) {\n attributes2.push(\"allow-scripts\");\n }\n this.iframe.style.display = \"none\";\n this.iframe.setAttribute(\"sandbox\", attributes2.join(\" \"));\n this.disableInteract();\n this.wrapper.appendChild(this.iframe);\n const iframeDoc = getIFrameContentDocument(this.iframe);\n const iframeWindow = getIFrameContentWindow(this.iframe);\n if (iframeWindow && iframeDoc) {\n polyfill(iframeWindow, iframeDoc);\n polyfill$1(iframeWindow);\n }\n }\n rebuildFullSnapshot(event, isSync = false) {\n const iframeDoc = getIFrameContentDocument(this.iframe);\n if (!iframeDoc) {\n return this.warn(\"Looks like your replayer has been destroyed.\");\n }\n if (Object.keys(this.legacy_missingNodeRetryMap).length) {\n this.warn(\n \"Found unresolved missing node map\",\n this.legacy_missingNodeRetryMap\n );\n }\n this.legacy_missingNodeRetryMap = {};\n const collected = [];\n const afterAppend = (builtNode, id) => {\n this.collectIframeAndAttachDocument(collected, builtNode);\n for (const plugin of this.config.plugins || []) {\n if (plugin.onBuild)\n plugin.onBuild(builtNode, {\n id,\n replayer: this\n });\n }\n };\n if (this.usingVirtualDom) {\n this.virtualDom.destroyTree();\n this.usingVirtualDom = false;\n }\n this.mirror.reset();\n rebuild(event.data.node, {\n doc: iframeDoc,\n afterAppend,\n cache: this.cache,\n mirror: this.mirror\n });\n afterAppend(iframeDoc, event.data.node.id);\n for (const { mutationInQueue, builtNode } of collected) {\n this.attachDocumentToIframe(mutationInQueue, builtNode);\n this.newDocumentQueue = this.newDocumentQueue.filter(\n (m) => m !== mutationInQueue\n );\n }\n const { documentElement, head } = iframeDoc;\n this.insertStyleRules(documentElement, head);\n if (!this.service.state.matches(\"playing\")) {\n const iframeHtmlElement = iframeDoc.getElementsByTagName(\"html\")[0];\n iframeHtmlElement && iframeHtmlElement.classList.add(\"rrweb-paused\");\n }\n this.emitter.emit(ReplayerEvents.FullsnapshotRebuilded, event);\n if (!isSync) {\n this.waitForStylesheetLoad();\n }\n if (this.config.UNSAFE_replayCanvas) {\n void this.preloadAllImages();\n }\n }\n insertStyleRules(documentElement, head) {\n const injectStylesRules = rules(\n this.config.blockClass\n ).concat(this.config.insertStyleRules);\n if (this.config.pauseAnimation) {\n injectStylesRules.push(\n \"html.rrweb-paused *, html.rrweb-paused *:before, html.rrweb-paused *:after { animation-play-state: paused !important; }\"\n );\n }\n if (this.usingVirtualDom) {\n const styleEl = this.virtualDom.createElement(\"style\");\n this.virtualDom.mirror.add(\n styleEl,\n getDefaultSN(styleEl, this.virtualDom.unserializedId)\n );\n documentElement.insertBefore(styleEl, head);\n styleEl.rules.push({\n source: IncrementalSource.StyleSheetRule,\n adds: injectStylesRules.map((cssText, index) => ({\n rule: cssText,\n index\n }))\n });\n } else {\n const styleEl = document.createElement(\"style\");\n documentElement.insertBefore(\n styleEl,\n head\n );\n for (let idx = 0; idx < injectStylesRules.length; idx++) {\n styleEl.sheet?.insertRule(injectStylesRules[idx], idx);\n }\n }\n }\n attachDocumentToIframe(mutation, iframeEl) {\n const mirror2 = this.usingVirtualDom ? this.virtualDom.mirror : this.mirror;\n const iframeContentDoc = getIFrameContentDocument(\n iframeEl\n );\n const collected = [];\n const afterAppend = (builtNode, id) => {\n this.collectIframeAndAttachDocument(collected, builtNode);\n const sn = mirror2.getMeta(builtNode);\n if (sn?.type === NodeType$2.Element && sn?.tagName.toUpperCase() === \"HTML\" && iframeContentDoc) {\n const { documentElement, head } = iframeContentDoc;\n this.insertStyleRules(\n documentElement,\n head\n );\n }\n if (this.usingVirtualDom) return;\n for (const plugin of this.config.plugins || []) {\n if (plugin.onBuild)\n plugin.onBuild(builtNode, {\n id,\n replayer: this\n });\n }\n };\n buildNodeWithSN(mutation.node, {\n doc: iframeContentDoc,\n mirror: mirror2,\n hackCss: true,\n skipChild: false,\n afterAppend,\n cache: this.cache\n });\n afterAppend(iframeContentDoc, mutation.node.id);\n for (const { mutationInQueue, builtNode } of collected) {\n this.attachDocumentToIframe(mutationInQueue, builtNode);\n this.newDocumentQueue = this.newDocumentQueue.filter(\n (m) => m !== mutationInQueue\n );\n }\n }\n collectIframeAndAttachDocument(collected, builtNode) {\n if (isSerializedIframe(builtNode, this.mirror)) {\n const mutationInQueue = this.newDocumentQueue.find(\n (m) => m.parentId === this.mirror.getId(builtNode)\n );\n if (mutationInQueue) {\n collected.push({\n mutationInQueue,\n builtNode\n });\n }\n }\n }\n /**\n * pause when loading style sheet, resume when loaded all timeout exceed\n */\n waitForStylesheetLoad() {\n const iframeDoc = getIFrameContentDocument(this.iframe);\n const head = iframeDoc?.head;\n if (head) {\n const unloadSheets = /* @__PURE__ */ new Set();\n let timer;\n let beforeLoadState = this.service.state;\n const stateHandler = () => {\n beforeLoadState = this.service.state;\n };\n this.emitter.on(ReplayerEvents.Start, stateHandler);\n this.emitter.on(ReplayerEvents.Pause, stateHandler);\n const unsubscribe = () => {\n this.emitter.off(ReplayerEvents.Start, stateHandler);\n this.emitter.off(ReplayerEvents.Pause, stateHandler);\n };\n head.querySelectorAll('link[rel=\"stylesheet\"]').forEach((css) => {\n if (!css.sheet) {\n unloadSheets.add(css);\n css.addEventListener(\"load\", () => {\n unloadSheets.delete(css);\n if (unloadSheets.size === 0 && timer !== -1) {\n if (beforeLoadState.matches(\"playing\")) {\n this.play(this.getCurrentTime());\n }\n this.emitter.emit(ReplayerEvents.LoadStylesheetEnd);\n if (timer) {\n clearTimeout(timer);\n }\n unsubscribe();\n }\n });\n }\n });\n if (unloadSheets.size > 0) {\n this.service.send({ type: \"PAUSE\" });\n this.emitter.emit(ReplayerEvents.LoadStylesheetStart);\n timer = setTimeout$1(() => {\n if (beforeLoadState.matches(\"playing\")) {\n this.play(this.getCurrentTime());\n }\n timer = -1;\n unsubscribe();\n }, this.config.loadTimeout);\n }\n }\n }\n /**\n * pause when there are some canvas drawImage args need to be loaded\n */\n async preloadAllImages() {\n const promises = [];\n for (const event of this.service.state.context.events) {\n if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.CanvasMutation) {\n promises.push(\n this.deserializeAndPreloadCanvasEvents(event.data, event)\n );\n const commands = \"commands\" in event.data ? event.data.commands : [event.data];\n commands.forEach((c2) => {\n this.preloadImages(c2, event);\n });\n }\n }\n return Promise.all(promises);\n }\n preloadImages(data, event) {\n if (data.property === \"drawImage\" && typeof data.args[0] === \"string\" && !this.imageMap.has(event)) {\n const canvas = document.createElement(\"canvas\");\n const ctx = canvas.getContext(\"2d\");\n const imgd = ctx?.createImageData(canvas.width, canvas.height);\n ctx?.putImageData(imgd, 0, 0);\n }\n }\n async deserializeAndPreloadCanvasEvents(data, event) {\n if (!this.canvasEventMap.has(event)) {\n const status = {\n isUnchanged: true\n };\n if (\"commands\" in data) {\n const commands = await Promise.all(\n data.commands.map(async (c2) => {\n const args = await Promise.all(\n c2.args.map(deserializeArg(this.imageMap, null, status))\n );\n return { ...c2, args };\n })\n );\n if (status.isUnchanged === false)\n this.canvasEventMap.set(event, { ...data, commands });\n } else {\n const args = await Promise.all(\n data.args.map(deserializeArg(this.imageMap, null, status))\n );\n if (status.isUnchanged === false)\n this.canvasEventMap.set(event, { ...data, args });\n }\n }\n }\n applyIncremental(e2, isSync) {\n const { data: d } = e2;\n switch (d.source) {\n case IncrementalSource.Mutation: {\n try {\n this.applyMutation(d, isSync);\n } catch (error) {\n this.warn(`Exception in mutation ${error.message || error}`, d);\n }\n break;\n }\n case IncrementalSource.Drag:\n case IncrementalSource.TouchMove:\n case IncrementalSource.MouseMove: {\n const pointerId = getPointerId(d);\n if (!this.pointers[pointerId]) {\n this.createPointer(pointerId, e2);\n }\n const pointer = this.pointers[pointerId];\n if (isSync) {\n const lastPosition = d.positions[d.positions.length - 1];\n pointer.pointerPosition = {\n x: lastPosition.x,\n y: lastPosition.y,\n id: lastPosition.id,\n debugData: d\n };\n } else {\n d.positions.forEach((p) => {\n const action = {\n doAction: () => {\n this.moveAndHover(p.x, p.y, p.id, isSync, d, pointerId);\n },\n delay: p.timeOffset + e2.timestamp - this.service.state.context.baselineTime\n };\n this.timer.addAction(action);\n });\n this.timer.addAction({\n doAction() {\n },\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n delay: e2.delay - d.positions[0]?.timeOffset\n });\n }\n break;\n }\n case IncrementalSource.MouseInteraction: {\n const pointerId = getPointerId(d);\n if (!this.pointers[pointerId]) {\n this.createPointer(pointerId, e2);\n }\n const pointer = this.pointers[pointerId];\n if (d.id === -1) {\n break;\n }\n const event = new Event(toLowerCase(MouseInteractions[d.type]));\n const target = this.mirror.getNode(d.id);\n if (!target) {\n return this.debugNodeNotFound(d, d.id);\n }\n this.emitter.emit(ReplayerEvents.MouseInteraction, {\n type: d.type,\n target\n });\n const { triggerFocus } = this.config;\n switch (d.type) {\n case MouseInteractions.Blur:\n if (\"blur\" in target) {\n target.blur();\n }\n break;\n case MouseInteractions.Focus:\n if (triggerFocus && target.focus) {\n target.focus({\n preventScroll: true\n });\n }\n break;\n case MouseInteractions.Click:\n case MouseInteractions.TouchStart:\n case MouseInteractions.TouchEnd:\n case MouseInteractions.MouseDown:\n case MouseInteractions.MouseUp:\n if (isSync) {\n if (d.type === MouseInteractions.TouchStart) {\n pointer.touchActive = true;\n Object.values(this.pointers).forEach((p) => {\n if (p !== pointer && !p.touchActive) {\n p.touchActive = false;\n }\n });\n } else if (d.type === MouseInteractions.TouchEnd) {\n pointer.touchActive = false;\n pointer.pointerEl.remove();\n if (pointer.mouseTail) {\n pointer.mouseTail.remove();\n }\n delete this.pointers[pointerId];\n }\n if (d.type === MouseInteractions.MouseDown) {\n this.lastMouseDownEvent = [target, event];\n } else if (d.type === MouseInteractions.MouseUp) {\n this.lastMouseDownEvent = null;\n }\n pointer.pointerPosition = {\n x: d.x || 0,\n y: d.y || 0,\n id: d.id,\n debugData: d\n };\n } else {\n if (d.type === MouseInteractions.TouchStart) {\n pointer.tailPositions.length = 0;\n }\n this.moveAndHover(d.x || 0, d.y || 0, d.id, isSync, d, pointerId);\n if (d.type === MouseInteractions.Click) {\n pointer.pointerEl.classList.remove(\"active\");\n void pointer.pointerEl.offsetWidth;\n pointer.pointerEl.classList.add(\"active\");\n } else if (d.type === MouseInteractions.TouchStart) {\n void pointer.pointerEl.offsetWidth;\n pointer.pointerEl.classList.add(\"touch-active\");\n } else if (d.type === MouseInteractions.TouchEnd) {\n pointer.pointerEl.remove();\n if (pointer.mouseTail) {\n pointer.mouseTail.remove();\n }\n delete this.pointers[pointerId];\n } else {\n target.dispatchEvent(event);\n }\n }\n break;\n case MouseInteractions.TouchCancel:\n if (isSync) {\n pointer.touchActive = false;\n } else {\n pointer.pointerEl.classList.remove(\"touch-active\");\n }\n break;\n default:\n target.dispatchEvent(event);\n }\n break;\n }\n case IncrementalSource.Scroll: {\n if (d.id === -1) {\n break;\n }\n if (this.usingVirtualDom) {\n const target = this.virtualDom.mirror.getNode(d.id);\n if (!target) {\n return this.debugNodeNotFound(d, d.id);\n }\n target.scrollData = d;\n break;\n }\n this.applyScroll(d, isSync);\n break;\n }\n case IncrementalSource.ViewportResize:\n this.emitter.emit(ReplayerEvents.Resize, {\n width: d.width,\n height: d.height\n });\n break;\n case IncrementalSource.Input: {\n if (d.id === -1) {\n break;\n }\n if (this.usingVirtualDom) {\n const target = this.virtualDom.mirror.getNode(d.id);\n if (!target) {\n return this.debugNodeNotFound(d, d.id);\n }\n target.inputData = d;\n break;\n }\n this.applyInput(d);\n break;\n }\n case IncrementalSource.MediaInteraction: {\n const target = this.usingVirtualDom ? this.virtualDom.mirror.getNode(d.id) : this.mirror.getNode(d.id);\n if (!target) {\n return this.debugNodeNotFound(d, d.id);\n }\n const mediaEl = target;\n try {\n if (d.currentTime !== void 0) {\n mediaEl.currentTime = d.currentTime;\n }\n if (d.volume !== void 0) {\n mediaEl.volume = d.volume;\n }\n if (d.muted !== void 0) {\n mediaEl.muted = d.muted;\n }\n if (d.type === MediaInteractions.Pause) {\n mediaEl.pause();\n }\n if (d.type === MediaInteractions.Play) {\n const maybePlayPromise = mediaEl.play();\n if (typeof maybePlayPromise?.catch === \"function\") {\n maybePlayPromise.catch((err) => {\n console.warn(err);\n });\n }\n }\n if (d.type === MediaInteractions.RateChange) {\n mediaEl.playbackRate = d.playbackRate;\n }\n } catch (error) {\n this.warn(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/restrict-template-expressions\n `Failed to replay media interactions: ${error.message || error}`\n );\n }\n break;\n }\n case IncrementalSource.StyleSheetRule:\n case IncrementalSource.StyleDeclaration: {\n if (this.usingVirtualDom) {\n if (d.styleId) this.constructedStyleMutations.push(d);\n else if (d.id)\n this.virtualDom.mirror.getNode(d.id)?.rules?.push(d);\n } else this.applyStyleSheetMutation(d);\n break;\n }\n case IncrementalSource.CanvasMutation: {\n if (!this.config.UNSAFE_replayCanvas) {\n return;\n }\n if (this.usingVirtualDom) {\n const target = this.virtualDom.mirror.getNode(\n d.id\n );\n if (!target) {\n return this.debugNodeNotFound(d, d.id);\n }\n target.canvasMutations.push({\n event: e2,\n mutation: d\n });\n } else {\n const target = this.mirror.getNode(d.id);\n if (!target) {\n return this.debugNodeNotFound(d, d.id);\n }\n void canvasMutation({\n event: e2,\n mutation: d,\n target,\n imageMap: this.imageMap,\n canvasEventMap: this.canvasEventMap,\n errorHandler: this.warnCanvasMutationFailed.bind(this)\n });\n }\n break;\n }\n case IncrementalSource.Font: {\n try {\n const fontFace = new FontFace(\n d.family,\n d.buffer ? new Uint8Array(JSON.parse(d.fontSource)) : d.fontSource,\n d.descriptors\n );\n getIFrameContentDocument(this.iframe)?.fonts.add(fontFace);\n } catch (error) {\n this.warn(error);\n }\n break;\n }\n case IncrementalSource.Selection: {\n if (isSync) {\n this.lastSelectionData = d;\n break;\n }\n this.applySelection(d);\n break;\n }\n case IncrementalSource.AdoptedStyleSheet: {\n if (this.usingVirtualDom) this.adoptedStyleSheets.push(d);\n else this.applyAdoptedStyleSheet(d);\n break;\n }\n }\n }\n applyMutation(d, isSync) {\n if (this.config.useVirtualDom && !this.usingVirtualDom && isSync) {\n this.usingVirtualDom = true;\n const iframeDoc = getIFrameContentDocument(this.iframe);\n if (iframeDoc) {\n buildFromDom(iframeDoc, this.mirror, this.virtualDom);\n }\n if (Object.keys(this.legacy_missingNodeRetryMap).length) {\n for (const key in this.legacy_missingNodeRetryMap) {\n try {\n const value = this.legacy_missingNodeRetryMap[key];\n const virtualNode = buildFromNode(\n value.node,\n this.virtualDom,\n this.mirror\n );\n if (virtualNode) value.node = virtualNode;\n } catch (error) {\n this.warn(error);\n }\n }\n }\n }\n const mirror2 = this.usingVirtualDom ? this.virtualDom.mirror : this.mirror;\n d.removes = d.removes.filter((mutation) => {\n if (!mirror2.getNode(mutation.id)) {\n this.warnNodeNotFound(d, mutation.id);\n return false;\n }\n return true;\n });\n d.removes.forEach((mutation) => {\n const target = mirror2.getNode(mutation.id);\n if (!target) {\n return;\n }\n let parent = mirror2.getNode(\n mutation.parentId\n );\n if (!parent) {\n return this.warnNodeNotFound(d, mutation.parentId);\n }\n if (mutation.isShadow && hasShadowRoot(parent)) {\n parent = parent.shadowRoot;\n }\n mirror2.removeNodeFromMap(target);\n if (parent)\n try {\n parent.removeChild(target);\n if (this.usingVirtualDom && target.nodeName === \"#text\" && parent.nodeName === \"STYLE\" && parent.rules?.length > 0)\n parent.rules = [];\n } catch (error) {\n if (error instanceof DOMException) {\n this.warn(\n \"parent could not remove child in mutation\",\n parent,\n target,\n d\n );\n } else {\n throw error;\n }\n }\n });\n const legacy_missingNodeMap = {\n ...this.legacy_missingNodeRetryMap\n };\n const queue = [];\n const nextNotInDOM = (mutation) => {\n let next = null;\n if (mutation.nextId) {\n next = mirror2.getNode(mutation.nextId);\n }\n if (mutation.nextId !== null && mutation.nextId !== void 0 && mutation.nextId !== -1 && !next) {\n return true;\n }\n return false;\n };\n const appendNode = (mutation) => {\n const iframeDoc = getIFrameContentDocument(this.iframe);\n if (!iframeDoc) {\n return this.warn(\"Looks like your replayer has been destroyed.\");\n }\n let parent = mirror2.getNode(\n mutation.parentId\n );\n if (!parent) {\n if (mutation.node.type === NodeType$2.Document) {\n return this.newDocumentQueue.push(mutation);\n }\n return queue.push(mutation);\n }\n if (mutation.node.isShadow) {\n if (!hasShadowRoot(parent)) {\n parent.attachShadow({ mode: \"open\" });\n parent = parent.shadowRoot;\n } else parent = parent.shadowRoot;\n }\n let previous = null;\n let next = null;\n if (mutation.previousId) {\n previous = mirror2.getNode(mutation.previousId);\n }\n if (mutation.nextId) {\n next = mirror2.getNode(mutation.nextId);\n }\n if (nextNotInDOM(mutation)) {\n return queue.push(mutation);\n }\n if (mutation.node.rootId && !mirror2.getNode(mutation.node.rootId)) {\n return;\n }\n const targetDoc = mutation.node.rootId ? mirror2.getNode(mutation.node.rootId) : this.usingVirtualDom ? this.virtualDom : iframeDoc;\n if (isSerializedIframe(parent, mirror2)) {\n this.attachDocumentToIframe(\n mutation,\n parent\n );\n return;\n }\n const afterAppend = (node, id) => {\n if (this.usingVirtualDom) return;\n for (const plugin of this.config.plugins || []) {\n if (plugin.onBuild) plugin.onBuild(node, { id, replayer: this });\n }\n };\n const target = buildNodeWithSN(mutation.node, {\n doc: targetDoc,\n // can be Document or RRDocument\n mirror: mirror2,\n // can be this.mirror or virtualDom.mirror\n skipChild: true,\n hackCss: true,\n cache: this.cache,\n /**\n * caveat: `afterAppend` only gets called on child nodes of target\n * we have to call it again below when this target was added to the DOM\n */\n afterAppend\n });\n if (mutation.previousId === -1 || mutation.nextId === -1) {\n legacy_missingNodeMap[mutation.node.id] = {\n node: target,\n mutation\n };\n return;\n }\n const parentSn = mirror2.getMeta(parent);\n if (parentSn && parentSn.type === NodeType$2.Element && parentSn.tagName === \"textarea\" && mutation.node.type === NodeType$2.Text) {\n const childNodeArray = Array.isArray(parent.childNodes) ? parent.childNodes : Array.from(parent.childNodes);\n for (const c2 of childNodeArray) {\n if (c2.nodeType === parent.TEXT_NODE) {\n parent.removeChild(c2);\n }\n }\n } else if (parentSn?.type === NodeType$2.Document) {\n const parentDoc = parent;\n if (mutation.node.type === NodeType$2.DocumentType && parentDoc.childNodes[0]?.nodeType === Node.DOCUMENT_TYPE_NODE)\n parentDoc.removeChild(parentDoc.childNodes[0]);\n if (target.nodeName === \"HTML\" && parentDoc.documentElement)\n parentDoc.removeChild(\n parentDoc.documentElement\n );\n }\n if (previous && previous.nextSibling && previous.nextSibling.parentNode) {\n parent.insertBefore(\n target,\n previous.nextSibling\n );\n } else if (next && next.parentNode) {\n parent.contains(next) ? parent.insertBefore(target, next) : parent.insertBefore(target, null);\n } else {\n parent.appendChild(target);\n }\n afterAppend(target, mutation.node.id);\n if (this.usingVirtualDom && target.nodeName === \"#text\" && parent.nodeName === \"STYLE\" && parent.rules?.length > 0)\n parent.rules = [];\n if (isSerializedIframe(target, this.mirror)) {\n const targetId = this.mirror.getId(target);\n const mutationInQueue = this.newDocumentQueue.find(\n (m) => m.parentId === targetId\n );\n if (mutationInQueue) {\n this.attachDocumentToIframe(\n mutationInQueue,\n target\n );\n this.newDocumentQueue = this.newDocumentQueue.filter(\n (m) => m !== mutationInQueue\n );\n }\n }\n if (mutation.previousId || mutation.nextId) {\n this.legacy_resolveMissingNode(\n legacy_missingNodeMap,\n parent,\n target,\n mutation\n );\n }\n };\n d.adds.forEach((mutation) => {\n appendNode(mutation);\n });\n const startTime = Date.now();\n while (queue.length) {\n const resolveTrees = queueToResolveTrees(queue);\n queue.length = 0;\n if (Date.now() - startTime > 500) {\n this.warn(\n \"Timeout in the loop, please check the resolve tree data:\",\n resolveTrees\n );\n break;\n }\n for (const tree of resolveTrees) {\n const parent = mirror2.getNode(tree.value.parentId);\n if (!parent) {\n this.debug(\n \"Drop resolve tree since there is no parent for the root node.\",\n tree\n );\n } else {\n iterateResolveTree(tree, (mutation) => {\n appendNode(mutation);\n });\n }\n }\n }\n if (Object.keys(legacy_missingNodeMap).length) {\n Object.assign(this.legacy_missingNodeRetryMap, legacy_missingNodeMap);\n }\n uniqueTextMutations(d.texts).forEach((mutation) => {\n const target = mirror2.getNode(mutation.id);\n if (!target) {\n if (d.removes.find((r2) => r2.id === mutation.id)) {\n return;\n }\n return this.warnNodeNotFound(d, mutation.id);\n }\n target.textContent = mutation.value;\n if (this.usingVirtualDom) {\n const parent = target.parentNode;\n if (parent?.rules?.length > 0) parent.rules = [];\n }\n });\n d.attributes.forEach((mutation) => {\n const target = mirror2.getNode(mutation.id);\n if (!target) {\n if (d.removes.find((r2) => r2.id === mutation.id)) {\n return;\n }\n return this.warnNodeNotFound(d, mutation.id);\n }\n for (const attributeName in mutation.attributes) {\n if (typeof attributeName === \"string\") {\n const value = mutation.attributes[attributeName];\n if (value === null) {\n target.removeAttribute(attributeName);\n } else if (typeof value === \"string\") {\n try {\n if (attributeName === \"_cssText\" && (target.nodeName === \"LINK\" || target.nodeName === \"STYLE\")) {\n try {\n const newSn = mirror2.getMeta(\n target\n );\n const newNode = buildNodeWithSN(\n {\n ...newSn,\n attributes: {\n ...newSn.attributes,\n ...mutation.attributes\n }\n },\n {\n doc: target.ownerDocument,\n // can be Document or RRDocument\n mirror: mirror2,\n skipChild: true,\n hackCss: true,\n cache: this.cache\n }\n );\n const siblingNode = target.nextSibling;\n const parentNode = target.parentNode;\n if (newNode && parentNode) {\n parentNode.removeChild(target);\n parentNode.insertBefore(\n newNode,\n siblingNode\n );\n mirror2.replace(mutation.id, newNode);\n break;\n }\n } catch (e2) {\n }\n }\n if (target.nodeType !== 3) {\n target.setAttribute(\n attributeName,\n value\n );\n }\n } catch (error) {\n this.warn(\n \"An error occurred may due to the checkout feature.\",\n error\n );\n }\n } else if (attributeName === \"style\") {\n const styleValues = value;\n const targetEl = target;\n for (const s2 in styleValues) {\n if (styleValues[s2] === false) {\n targetEl.style.removeProperty(s2);\n } else if (styleValues[s2] instanceof Array) {\n const svp = styleValues[s2];\n targetEl.style.setProperty(s2, svp[0], svp[1]);\n } else {\n const svs = styleValues[s2];\n targetEl.style.setProperty(s2, svs);\n }\n }\n }\n }\n }\n });\n }\n /**\n * Apply the scroll data on real elements.\n * If the replayer is in sync mode, smooth scroll behavior should be disabled.\n * @param d - the scroll data\n * @param isSync - whether the replayer is in sync mode(fast-forward)\n */\n applyScroll(d, isSync) {\n const target = this.mirror.getNode(d.id);\n if (!target) {\n return this.debugNodeNotFound(d, d.id);\n }\n const sn = this.mirror.getMeta(target);\n const iframeDoc = getIFrameContentDocument(this.iframe);\n if (target === iframeDoc) {\n this.iframe.contentWindow?.scrollTo({\n top: d.y,\n left: d.x,\n behavior: isSync ? \"auto\" : \"smooth\"\n });\n } else if (sn?.type === NodeType$2.Document) {\n target.defaultView?.scrollTo({\n top: d.y,\n left: d.x,\n behavior: isSync ? \"auto\" : \"smooth\"\n });\n } else {\n try {\n target.scrollTo({\n top: d.y,\n left: d.x,\n behavior: isSync ? \"auto\" : \"smooth\"\n });\n } catch (error) {\n }\n }\n }\n applyInput(d) {\n const target = this.mirror.getNode(d.id);\n if (!target) {\n return this.debugNodeNotFound(d, d.id);\n }\n try {\n target.checked = d.isChecked;\n target.value = d.text;\n } catch (error) {\n }\n }\n applySelection(d) {\n try {\n const selectionSet = /* @__PURE__ */ new Set();\n const ranges = d.ranges.map(({ start, startOffset, end, endOffset }) => {\n const startContainer = this.mirror.getNode(start);\n const endContainer = this.mirror.getNode(end);\n if (!startContainer || !endContainer) return;\n const result = new Range();\n result.setStart(startContainer, startOffset);\n result.setEnd(endContainer, endOffset);\n const doc = startContainer.ownerDocument;\n const selection = doc?.getSelection();\n selection && selectionSet.add(selection);\n return {\n range: result,\n selection\n };\n });\n selectionSet.forEach((s2) => s2.removeAllRanges());\n ranges.forEach((r2) => r2 && r2.selection?.addRange(r2.range));\n } catch (error) {\n }\n }\n applyStyleSheetMutation(data) {\n let styleSheet = null;\n if (data.styleId) styleSheet = this.styleMirror.getStyle(data.styleId);\n else if (data.id)\n styleSheet = this.mirror.getNode(data.id)?.sheet || null;\n if (!styleSheet) return;\n if (data.source === IncrementalSource.StyleSheetRule)\n this.applyStyleSheetRule(data, styleSheet);\n else if (data.source === IncrementalSource.StyleDeclaration)\n this.applyStyleDeclaration(data, styleSheet);\n }\n applyStyleSheetRule(data, styleSheet) {\n data.adds?.forEach(({ rule, index: nestedIndex }) => {\n try {\n if (Array.isArray(nestedIndex)) {\n const { positions, index } = getPositionsAndIndex(nestedIndex);\n const nestedRule = getNestedRule(styleSheet.cssRules, positions);\n nestedRule.insertRule(rule, index);\n } else {\n const index = nestedIndex === void 0 ? void 0 : Math.min(nestedIndex, styleSheet.cssRules.length);\n styleSheet?.insertRule(rule, index);\n }\n } catch (e2) {\n }\n });\n data.removes?.forEach(({ index: nestedIndex }) => {\n try {\n if (Array.isArray(nestedIndex)) {\n const { positions, index } = getPositionsAndIndex(nestedIndex);\n const nestedRule = getNestedRule(styleSheet.cssRules, positions);\n nestedRule.deleteRule(index || 0);\n } else {\n styleSheet?.deleteRule(nestedIndex);\n }\n } catch (e2) {\n }\n });\n if (data.replace)\n try {\n void styleSheet.replace?.(data.replace);\n } catch (e2) {\n }\n if (data.replaceSync)\n try {\n styleSheet.replaceSync?.(data.replaceSync);\n } catch (e2) {\n }\n }\n applyStyleDeclaration(data, styleSheet) {\n if (data.set) {\n const rule = getNestedRule(\n styleSheet.rules,\n data.index\n );\n rule && rule.style && rule.style.setProperty(\n data.set.property,\n data.set.value,\n data.set.priority\n );\n }\n if (data.remove) {\n const rule = getNestedRule(\n styleSheet.rules,\n data.index\n );\n rule && rule.style && rule.style.removeProperty(data.remove.property);\n }\n }\n applyAdoptedStyleSheet(data) {\n const targetHost = this.mirror.getNode(data.id);\n if (!targetHost) return;\n data.styles?.forEach((style) => {\n let newStyleSheet = null;\n let hostWindow = null;\n if (hasShadowRoot(targetHost))\n hostWindow = targetHost.ownerDocument?.defaultView || null;\n else if (targetHost.nodeName === \"#document\")\n hostWindow = targetHost.defaultView;\n if (!hostWindow) return;\n try {\n newStyleSheet = new hostWindow.CSSStyleSheet();\n this.styleMirror.add(newStyleSheet, style.styleId);\n this.applyStyleSheetRule(\n {\n source: IncrementalSource.StyleSheetRule,\n adds: style.rules\n },\n newStyleSheet\n );\n } catch (e2) {\n }\n });\n const MAX_RETRY_TIME = 10;\n let count = 0;\n const adoptStyleSheets = (targetHost2, styleIds) => {\n const stylesToAdopt = styleIds.map((styleId) => this.styleMirror.getStyle(styleId)).filter((style) => style !== null);\n if (hasShadowRoot(targetHost2))\n targetHost2.shadowRoot.adoptedStyleSheets = stylesToAdopt;\n else if (targetHost2.nodeName === \"#document\")\n targetHost2.adoptedStyleSheets = stylesToAdopt;\n if (stylesToAdopt.length !== styleIds.length && count < MAX_RETRY_TIME) {\n setTimeout$1(\n () => adoptStyleSheets(targetHost2, styleIds),\n 0 + 100 * count\n );\n count++;\n }\n };\n adoptStyleSheets(targetHost, data.styleIds);\n }\n legacy_resolveMissingNode(map, parent, target, targetMutation) {\n const { previousId, nextId } = targetMutation;\n const previousInMap = previousId && map[previousId];\n const nextInMap = nextId && map[nextId];\n if (previousInMap) {\n const { node, mutation } = previousInMap;\n parent.insertBefore(node, target);\n delete map[mutation.node.id];\n delete this.legacy_missingNodeRetryMap[mutation.node.id];\n if (mutation.previousId || mutation.nextId) {\n this.legacy_resolveMissingNode(map, parent, node, mutation);\n }\n }\n if (nextInMap) {\n const { node, mutation } = nextInMap;\n parent.insertBefore(\n node,\n target.nextSibling\n );\n delete map[mutation.node.id];\n delete this.legacy_missingNodeRetryMap[mutation.node.id];\n if (mutation.previousId || mutation.nextId) {\n this.legacy_resolveMissingNode(map, parent, node, mutation);\n }\n }\n }\n moveAndHover(x, y, id, isSync, debugData, pointerId) {\n const target = this.mirror.getNode(id);\n if (!target) {\n return this.debugNodeNotFound(debugData, id);\n }\n const base = getBaseDimension(target, this.iframe);\n const _x = x * base.absoluteScale + base.x;\n const _y = y * base.absoluteScale + base.y;\n const pointer = this.pointers[pointerId];\n if (pointer && pointer.pointerEl) {\n pointer.pointerEl.style.left = `${_x}px`;\n pointer.pointerEl.style.top = `${_y}px`;\n }\n if (!isSync) {\n this.drawMouseTail({ x: _x, y: _y }, pointerId);\n }\n this.hoverElements(target);\n }\n drawMouseTail(position, pointerId) {\n const pointer = this.pointers[pointerId];\n if (!pointer || !pointer.mouseTail) {\n return;\n }\n const { lineCap, lineWidth, strokeStyle, duration } = this.config.mouseTail === true ? defaultMouseTailConfig : Object.assign({}, defaultMouseTailConfig, this.config.mouseTail);\n const draw = () => {\n if (!pointer || !pointer.mouseTail) {\n return;\n }\n const mouseTail = pointer.mouseTail;\n const ctx = mouseTail.getContext(\"2d\");\n if (!ctx || !pointer.tailPositions.length) {\n return;\n }\n ctx.clearRect(0, 0, mouseTail.width, mouseTail.height);\n ctx.beginPath();\n ctx.lineWidth = lineWidth;\n ctx.lineCap = lineCap;\n ctx.strokeStyle = strokeStyle;\n ctx.moveTo(pointer.tailPositions[0].x, pointer.tailPositions[0].y);\n pointer.tailPositions.forEach((p) => ctx.lineTo(p.x, p.y));\n ctx.stroke();\n };\n pointer.tailPositions.push(position);\n draw();\n setTimeout$1(() => {\n if (pointerId in this.pointers) {\n pointer.tailPositions = pointer.tailPositions.filter(\n (p) => p !== position\n );\n draw();\n }\n }, duration / this.speedService.state.context.timer.speed);\n }\n hoverElements(el) {\n const iframeDoc = getIFrameContentDocument(this.iframe);\n const rootElement = this.lastHoveredRootNode || iframeDoc;\n if (rootElement && typeof rootElement.querySelectorAll === \"function\") {\n rootElement.querySelectorAll(\".\\\\:hover\").forEach((hoveredEl) => {\n hoveredEl.classList.remove(\":hover\");\n });\n }\n this.lastHoveredRootNode = el.getRootNode();\n let currentEl = el;\n while (currentEl) {\n if (currentEl.classList) {\n currentEl.classList.add(\":hover\");\n }\n currentEl = currentEl.parentElement;\n }\n }\n isUserInteraction(event) {\n if (event.type !== EventType.IncrementalSnapshot) {\n return false;\n }\n return event.data.source > IncrementalSource.Mutation && event.data.source <= IncrementalSource.Input;\n }\n backToNormal() {\n this.nextUserInteractionEvent = null;\n if (this.speedService.state.matches(\"normal\")) {\n return;\n }\n this.speedService.send({ type: \"BACK_TO_NORMAL\" });\n this.emitter.emit(ReplayerEvents.SkipEnd, {\n speed: this.speedService.state.context.normalSpeed\n });\n }\n warnNodeNotFound(d, id) {\n this.warn(`Node with id '${id}' not found. `, d);\n }\n warnCanvasMutationFailed(d, error) {\n this.warn(`Has error on canvas update`, error, \"canvas mutation:\", d);\n }\n debugNodeNotFound(d, id) {\n this.debug(`Node with id '${id}' not found. `, d);\n }\n warn(...args) {\n if (!this.config.showWarning) {\n return;\n }\n this.config.logger.warn(REPLAY_CONSOLE_PREFIX, ...args);\n }\n debug(...args) {\n if (!this.config.showDebug) {\n return;\n }\n this.config.logger.log(REPLAY_CONSOLE_PREFIX, ...args);\n }\n}\nexport {\n CanvasManager,\n EventType,\n IncrementalSource,\n MouseInteractions,\n Replayer,\n ReplayerEvents,\n addCustomEvent,\n canvasMutation,\n deserializeArg,\n freezePage,\n record,\n takeFullSnapshot,\n utils\n};\n//# sourceMappingURL=rrweb.js.map\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 specifically 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 use 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 recordCrossOriginIframes?: boolean;\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 addWindow(win: typeof globalThis & Window): void;\n addShadowRoot(shadowRoot: ShadowRoot): void;\n resetShadowRoots(): 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 type { Breadcrumb } from '@sentry/core';\nimport { normalize } from '@sentry/core';\nimport { EventType } from '@sentry-internal/rrweb';\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/core';\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 {\n // ignore errors in here\n }\n }\n\n return originalWindowOpen.apply(WINDOW, args);\n };\n });\n}\n", "import type { Breadcrumb } from '@sentry/core';\nimport { setTimeout } from '@sentry-internal/browser-utils';\nimport { IncrementalSource, MouseInteractions, record } from '@sentry-internal/rrweb';\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/** Any IncrementalSource for rrweb that we interpret as a kind of mutation. */\nconst IncrementalMutationSources = new Set([\n IncrementalSource.Mutation,\n IncrementalSource.StyleSheetRule,\n IncrementalSource.StyleDeclaration,\n IncrementalSource.AdoptedStyleSheet,\n IncrementalSource.CanvasMutation,\n IncrementalSource.Selection,\n IncrementalSource.MediaInteraction,\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 _scrollTimeout: 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._scrollTimeout = 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._scrollTimeout;\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 (IncrementalMutationSources.has(source)) {\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", "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", "var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nvar NodeType = /* @__PURE__ */ ((NodeType2) => {\n NodeType2[NodeType2[\"Document\"] = 0] = \"Document\";\n NodeType2[NodeType2[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType2[NodeType2[\"Element\"] = 2] = \"Element\";\n NodeType2[NodeType2[\"Text\"] = 3] = \"Text\";\n NodeType2[NodeType2[\"CDATA\"] = 4] = \"CDATA\";\n NodeType2[NodeType2[\"Comment\"] = 5] = \"Comment\";\n return NodeType2;\n})(NodeType || {});\nfunction isElement(n) {\n return n.nodeType === n.ELEMENT_NODE;\n}\nfunction isShadowRoot(n) {\n const host = n?.host;\n return Boolean(host?.shadowRoot === n);\n}\nfunction isNativeShadowDom(shadowRoot) {\n return Object.prototype.toString.call(shadowRoot) === \"[object ShadowRoot]\";\n}\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\n if (cssText.includes(\" background-clip: text;\") && !cssText.includes(\" -webkit-background-clip: text;\")) {\n cssText = cssText.replace(\n /\\sbackground-clip:\\s*text;/g,\n \" -webkit-background-clip: text; background-clip: text;\"\n );\n }\n return cssText;\n}\nfunction escapeImportStatement(rule) {\n const { cssText } = rule;\n if (cssText.split('\"').length < 3) return cssText;\n const statement = [\"@import\", `url(${JSON.stringify(rule.href)})`];\n if (rule.layerName === \"\") {\n statement.push(`layer`);\n } else if (rule.layerName) {\n statement.push(`layer(${rule.layerName})`);\n }\n if (rule.supportsText) {\n statement.push(`supports(${rule.supportsText})`);\n }\n if (rule.media.length) {\n statement.push(rule.media.mediaText);\n }\n return statement.join(\" \") + \";\";\n}\nfunction stringifyStylesheet(s) {\n try {\n const rules = s.rules || s.cssRules;\n return rules ? fixBrowserCompatibilityIssuesInCSS(\n Array.from(rules, stringifyRule).join(\"\")\n ) : null;\n } catch (error) {\n return null;\n }\n}\nfunction fixAllCssProperty(rule) {\n let styles = \"\";\n for (let i = 0; i < rule.style.length; i++) {\n const styleDeclaration = rule.style;\n const attribute = styleDeclaration[i];\n const isImportant = styleDeclaration.getPropertyPriority(attribute);\n styles += `${attribute}:${styleDeclaration.getPropertyValue(attribute)}${isImportant ? ` !important` : \"\"};`;\n }\n return `${rule.selectorText} { ${styles} }`;\n}\nfunction stringifyRule(rule) {\n let importStringified;\n if (isCSSImportRule(rule)) {\n try {\n importStringified = // for same-origin stylesheets,\n // we can access the imported stylesheet rules directly\n stringifyStylesheet(rule.styleSheet) || // work around browser issues with the raw string `@import url(...)` statement\n escapeImportStatement(rule);\n } catch (error) {\n }\n } else if (isCSSStyleRule(rule)) {\n let cssText = rule.cssText;\n const needsSafariColonFix = rule.selectorText.includes(\":\");\n const needsAllFix = typeof rule.style[\"all\"] === \"string\" && rule.style[\"all\"];\n if (needsAllFix) {\n cssText = fixAllCssProperty(rule);\n }\n if (needsSafariColonFix) {\n cssText = fixSafariColons(cssText);\n }\n if (needsSafariColonFix || needsAllFix) {\n return cssText;\n }\n }\n return importStringified || rule.cssText;\n}\nfunction fixSafariColons(cssStringified) {\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n return cssStringified.replace(regex, \"$1\\\\$2\");\n}\nfunction isCSSImportRule(rule) {\n return \"styleSheet\" in rule;\n}\nfunction isCSSStyleRule(rule) {\n return \"selectorText\" in rule;\n}\nclass Mirror {\n constructor() {\n __publicField(this, \"idNodeMap\", /* @__PURE__ */ new Map());\n __publicField(this, \"nodeMetaMap\", /* @__PURE__ */ new WeakMap());\n }\n getId(n) {\n if (!n) return -1;\n const id = this.getMeta(n)?.id;\n return id ?? -1;\n }\n getNode(id) {\n return this.idNodeMap.get(id) || null;\n }\n getIds() {\n return Array.from(this.idNodeMap.keys());\n }\n getMeta(n) {\n return this.nodeMetaMap.get(n) || null;\n }\n // removes the node from idNodeMap\n // doesn't remove the node from nodeMetaMap\n removeNodeFromMap(n) {\n const id = this.getId(n);\n this.idNodeMap.delete(id);\n if (n.childNodes) {\n n.childNodes.forEach(\n (childNode) => this.removeNodeFromMap(childNode)\n );\n }\n }\n has(id) {\n return this.idNodeMap.has(id);\n }\n hasNode(node) {\n return this.nodeMetaMap.has(node);\n }\n add(n, meta) {\n const id = meta.id;\n this.idNodeMap.set(id, n);\n this.nodeMetaMap.set(n, meta);\n }\n replace(id, n) {\n const oldNode = this.getNode(id);\n if (oldNode) {\n const meta = this.nodeMetaMap.get(oldNode);\n if (meta) this.nodeMetaMap.set(n, meta);\n }\n this.idNodeMap.set(id, n);\n }\n reset() {\n this.idNodeMap = /* @__PURE__ */ new Map();\n this.nodeMetaMap = /* @__PURE__ */ new WeakMap();\n }\n}\nfunction createMirror() {\n return new Mirror();\n}\nfunction shouldMaskInput({\n maskInputOptions,\n tagName,\n type\n}) {\n if (tagName === \"OPTION\") {\n tagName = \"SELECT\";\n }\n return Boolean(\n maskInputOptions[tagName.toLowerCase()] || type && maskInputOptions[type] || type === \"password\" || // Default to \"text\" option for inputs without a \"type\" attribute defined\n tagName === \"INPUT\" && !type && maskInputOptions[\"text\"]\n );\n}\nfunction maskInputValue({\n isMasked,\n element,\n value,\n maskInputFn\n}) {\n let text = value || \"\";\n if (!isMasked) {\n return text;\n }\n if (maskInputFn) {\n text = maskInputFn(text, element);\n }\n return \"*\".repeat(text.length);\n}\nfunction toLowerCase(str) {\n return str.toLowerCase();\n}\nfunction toUpperCase(str) {\n return str.toUpperCase();\n}\nconst ORIGINAL_ATTRIBUTE_NAME = \"__rrweb_original__\";\nfunction is2DCanvasBlank(canvas) {\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return true;\n const chunkSize = 50;\n for (let x = 0; x < canvas.width; x += chunkSize) {\n for (let y = 0; y < canvas.height; y += chunkSize) {\n const getImageData = ctx.getImageData;\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;\n const pixelBuffer = new Uint32Array(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n originalGetImageData.call(\n ctx,\n x,\n y,\n Math.min(chunkSize, canvas.width - x),\n Math.min(chunkSize, canvas.height - y)\n ).data.buffer\n );\n if (pixelBuffer.some((pixel) => pixel !== 0)) return false;\n }\n }\n return true;\n}\nfunction isNodeMetaEqual(a, b) {\n if (!a || !b || a.type !== b.type) return false;\n if (a.type === NodeType.Document)\n return a.compatMode === b.compatMode;\n else if (a.type === NodeType.DocumentType)\n return a.name === b.name && a.publicId === b.publicId && a.systemId === b.systemId;\n else if (a.type === NodeType.Comment || a.type === NodeType.Text || a.type === NodeType.CDATA)\n return a.textContent === b.textContent;\n else if (a.type === NodeType.Element)\n return a.tagName === b.tagName && JSON.stringify(a.attributes) === JSON.stringify(b.attributes) && a.isSVG === b.isSVG && a.needBlock === b.needBlock;\n return false;\n}\nfunction getInputType(element) {\n const type = element.type;\n return element.hasAttribute(\"data-rr-is-password\") ? \"password\" : type ? (\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n toLowerCase(type)\n ) : null;\n}\nfunction getInputValue(el, tagName, type) {\n if (tagName === \"INPUT\" && (type === \"radio\" || type === \"checkbox\")) {\n return el.getAttribute(\"value\") || \"\";\n }\n return el.value;\n}\nfunction extractFileExtension(path, baseURL) {\n let url;\n try {\n url = new URL(path, baseURL ?? window.location.href);\n } catch (err) {\n return null;\n }\n const regex = /\\.([0-9a-z]+)(?:$)/i;\n const match = url.pathname.match(regex);\n return match?.[1] ?? null;\n}\nconst cachedImplementations = {};\nfunction getImplementation(name) {\n const cached = cachedImplementations[name];\n if (cached) {\n return cached;\n }\n const document = window.document;\n let impl = window[name];\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[name]) {\n impl = // eslint-disable-next-line @typescript-eslint/unbound-method\n contentWindow[name];\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n }\n }\n return cachedImplementations[name] = impl.bind(\n window\n );\n}\nfunction onRequestAnimationFrame(...rest) {\n return getImplementation(\"requestAnimationFrame\")(...rest);\n}\nfunction setTimeout(...rest) {\n return getImplementation(\"setTimeout\")(...rest);\n}\nfunction clearTimeout(...rest) {\n return getImplementation(\"clearTimeout\")(...rest);\n}\nfunction getIframeContentDocument(iframe) {\n try {\n return iframe.contentDocument;\n } catch (e) {\n }\n}\nlet _id = 1;\nconst tagNameRegex = new RegExp(\"[^a-z0-9-_:]\");\nconst IGNORED_NODE = -2;\nfunction genId() {\n return _id++;\n}\nfunction getValidTagName(element) {\n if (element instanceof HTMLFormElement) {\n return \"form\";\n }\n const processedTagName = toLowerCase(element.tagName);\n if (tagNameRegex.test(processedTagName)) {\n return \"div\";\n }\n return processedTagName;\n}\nfunction extractOrigin(url) {\n let origin = \"\";\n if (url.indexOf(\"//\") > -1) {\n origin = url.split(\"/\").slice(0, 3).join(\"/\");\n } else {\n origin = url.split(\"/\")[0];\n }\n origin = origin.split(\"?\")[0];\n return origin;\n}\nlet canvasService;\nlet canvasCtx;\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\nconst URL_WWW_MATCH = /^www\\..*/i;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction filterCSSPropertiesFromInlineStyle(cssText, ignoredProperties) {\n if (!cssText || ignoredProperties.size === 0) {\n return cssText;\n }\n try {\n const properties = cssText.split(\";\");\n const filteredProperties = [];\n for (let property of properties) {\n property = property.trim();\n if (!property) continue;\n const colonIndex = property.indexOf(\":\");\n if (colonIndex === -1) {\n filteredProperties.push(property);\n continue;\n }\n const propertyName = property.slice(0, colonIndex).trim();\n if (!ignoredProperties.has(propertyName)) {\n filteredProperties.push(property);\n }\n }\n return filteredProperties.join(\"; \") + (filteredProperties.length > 0 && cssText.endsWith(\";\") ? \";\" : \"\");\n } catch (error) {\n console.warn(\"Error filtering CSS properties:\", error);\n return cssText;\n }\n}\nfunction absoluteToStylesheet(cssText, href) {\n return (cssText || \"\").replace(\n URL_IN_CSS_REF,\n (origin, quote1, path1, quote2, path2, path3) => {\n const filePath = path1 || path2 || path3;\n const maybeQuote = quote1 || quote2 || \"\";\n if (!filePath) {\n return origin;\n }\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (DATA_URI.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (filePath[0] === \"/\") {\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\n }\n const stack = href.split(\"/\");\n const parts = filePath.split(\"/\");\n stack.pop();\n for (const part of parts) {\n if (part === \".\") {\n continue;\n } else if (part === \"..\") {\n stack.pop();\n } else {\n stack.push(part);\n }\n }\n return `url(${maybeQuote}${stack.join(\"/\")}${maybeQuote})`;\n }\n );\n}\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n if (attributeValue.trim() === \"\") {\n return attributeValue;\n }\n let pos = 0;\n function collectCharacters(regEx) {\n let chars;\n const match = regEx.exec(attributeValue.substring(pos));\n if (match) {\n chars = match[0];\n pos += chars.length;\n return chars;\n }\n return \"\";\n }\n const output = [];\n while (true) {\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\n if (pos >= attributeValue.length) {\n break;\n }\n let url = collectCharacters(SRCSET_NOT_SPACES);\n if (url.slice(-1) === \",\") {\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n output.push(url);\n } else {\n let descriptorsStr = \"\";\n url = absoluteToDoc(doc, url);\n let inParens = false;\n while (true) {\n const c = attributeValue.charAt(pos);\n if (c === \"\") {\n output.push((url + descriptorsStr).trim());\n break;\n } else if (!inParens) {\n if (c === \",\") {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n } else if (c === \"(\") {\n inParens = true;\n }\n } else {\n if (c === \")\") {\n inParens = false;\n }\n }\n descriptorsStr += c;\n pos += 1;\n }\n }\n }\n return output.join(\", \");\n}\nconst cachedDocument = /* @__PURE__ */ new WeakMap();\nfunction absoluteToDoc(doc, attributeValue) {\n if (!attributeValue || attributeValue.trim() === \"\") {\n return attributeValue;\n }\n return getHref(doc, attributeValue);\n}\nfunction isSVGElement(el) {\n return Boolean(el.tagName === \"svg\" || el.ownerSVGElement);\n}\nfunction getHref(doc, customHref) {\n let a = cachedDocument.get(doc);\n if (!a) {\n a = doc.createElement(\"a\");\n cachedDocument.set(doc, a);\n }\n if (!customHref) {\n customHref = \"\";\n } else if (customHref.startsWith(\"blob:\") || customHref.startsWith(\"data:\")) {\n return customHref;\n }\n a.setAttribute(\"href\", customHref);\n return a.href;\n}\nfunction transformAttribute(doc, tagName, name, value, element, maskAttributeFn, ignoreCSSAttributes) {\n if (!value) {\n return value;\n }\n if (name === \"src\" || name === \"href\" && !(tagName === \"use\" && value[0] === \"#\")) {\n return absoluteToDoc(doc, value);\n } else if (name === \"xlink:href\" && value[0] !== \"#\") {\n return absoluteToDoc(doc, value);\n } else if (name === \"background\" && (tagName === \"table\" || tagName === \"td\" || tagName === \"th\")) {\n return absoluteToDoc(doc, value);\n } else if (name === \"srcset\") {\n return getAbsoluteSrcsetString(doc, value);\n } else if (name === \"style\") {\n let processedStyle = absoluteToStylesheet(value, getHref(doc));\n if (ignoreCSSAttributes && ignoreCSSAttributes.size > 0) {\n processedStyle = filterCSSPropertiesFromInlineStyle(\n processedStyle,\n ignoreCSSAttributes\n );\n }\n return processedStyle;\n } else if (tagName === \"object\" && name === \"data\") {\n return absoluteToDoc(doc, value);\n }\n if (typeof maskAttributeFn === \"function\") {\n return maskAttributeFn(name, value, element);\n }\n return value;\n}\nfunction ignoreAttribute(tagName, name, _value) {\n return (tagName === \"video\" || tagName === \"audio\") && name === \"autoplay\";\n}\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\n try {\n if (unblockSelector && element.matches(unblockSelector)) {\n return false;\n }\n if (typeof blockClass === \"string\") {\n if (element.classList.contains(blockClass)) {\n return true;\n }\n } else {\n for (let eIndex = element.classList.length; eIndex--; ) {\n const className = element.classList[eIndex];\n if (blockClass.test(className)) {\n return true;\n }\n }\n }\n if (blockSelector) {\n return element.matches(blockSelector);\n }\n } catch (e) {\n }\n return false;\n}\nfunction elementClassMatchesRegex(el, regex) {\n for (let eIndex = el.classList.length; eIndex--; ) {\n const className = el.classList[eIndex];\n if (regex.test(className)) {\n return true;\n }\n }\n return false;\n}\nfunction classMatchesRegex(node, regex, checkAncestors) {\n if (!node) return false;\n if (checkAncestors) {\n return distanceToMatch(\n node,\n (node2) => elementClassMatchesRegex(node2, regex)\n ) >= 0;\n } else if (node.nodeType === node.ELEMENT_NODE) {\n return elementClassMatchesRegex(node, regex);\n }\n return false;\n}\nfunction distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\n if (!node) return -1;\n if (node.nodeType !== node.ELEMENT_NODE) return -1;\n if (distance > limit) return -1;\n if (matchPredicate(node)) return distance;\n return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1);\n}\nfunction createMatchPredicate(className, selector) {\n return (node) => {\n const el = node;\n if (el === null) return false;\n try {\n if (className) {\n if (typeof className === \"string\") {\n if (el.matches(`.${className}`)) return true;\n } else if (elementClassMatchesRegex(el, className)) {\n return true;\n }\n }\n if (selector && el.matches(selector)) return true;\n return false;\n } catch {\n return false;\n }\n };\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\n try {\n const el = node.nodeType === node.ELEMENT_NODE ? node : node.parentElement;\n if (el === null) return false;\n if (el.tagName === \"INPUT\") {\n const autocomplete = el.getAttribute(\"autocomplete\");\n const disallowedAutocompleteValues = [\n \"current-password\",\n \"new-password\",\n \"cc-number\",\n \"cc-exp\",\n \"cc-exp-month\",\n \"cc-exp-year\",\n \"cc-csc\"\n ];\n if (disallowedAutocompleteValues.includes(autocomplete)) {\n return true;\n }\n }\n let maskDistance = -1;\n let unmaskDistance = -1;\n if (maskAllText) {\n unmaskDistance = distanceToMatch(\n el,\n createMatchPredicate(unmaskTextClass, unmaskTextSelector)\n );\n if (unmaskDistance < 0) {\n return true;\n }\n maskDistance = distanceToMatch(\n el,\n createMatchPredicate(maskTextClass, maskTextSelector),\n unmaskDistance >= 0 ? unmaskDistance : Infinity\n );\n } else {\n maskDistance = distanceToMatch(\n el,\n createMatchPredicate(maskTextClass, maskTextSelector)\n );\n if (maskDistance < 0) {\n return false;\n }\n unmaskDistance = distanceToMatch(\n el,\n createMatchPredicate(unmaskTextClass, unmaskTextSelector),\n maskDistance >= 0 ? maskDistance : Infinity\n );\n }\n return maskDistance >= 0 ? unmaskDistance >= 0 ? maskDistance <= unmaskDistance : true : unmaskDistance >= 0 ? false : !!maskAllText;\n } catch (e) {\n }\n return !!maskAllText;\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n const win = iframeEl.contentWindow;\n if (!win) {\n return;\n }\n let fired = false;\n let readyState;\n try {\n readyState = win.document.readyState;\n } catch (error) {\n return;\n }\n if (readyState !== \"complete\") {\n const timer = setTimeout(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, iframeLoadTimeout);\n iframeEl.addEventListener(\"load\", () => {\n clearTimeout(timer);\n fired = true;\n listener();\n });\n return;\n }\n const blankUrl = \"about:blank\";\n if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === \"\") {\n setTimeout(listener, 0);\n return iframeEl.addEventListener(\"load\", listener);\n }\n iframeEl.addEventListener(\"load\", listener);\n}\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\n let fired = false;\n let styleSheetLoaded;\n try {\n styleSheetLoaded = link.sheet;\n } catch (error) {\n return;\n }\n if (styleSheetLoaded) return;\n const timer = setTimeout(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, styleSheetLoadTimeout);\n link.addEventListener(\"load\", () => {\n clearTimeout(timer);\n fired = true;\n listener();\n });\n}\nfunction serializeNode(n, options) {\n const {\n doc,\n mirror,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskAttributeFn,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputOptions = {},\n maskTextFn,\n maskInputFn,\n dataURLOptions = {},\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement = false,\n ignoreCSSAttributes\n } = options;\n const rootId = getRootId(doc, mirror);\n switch (n.nodeType) {\n case n.DOCUMENT_NODE:\n if (n.compatMode !== \"CSS1Compat\") {\n return {\n type: NodeType.Document,\n childNodes: [],\n compatMode: n.compatMode\n // probably \"BackCompat\"\n };\n } else {\n return {\n type: NodeType.Document,\n childNodes: []\n };\n }\n case n.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType.DocumentType,\n name: n.name,\n publicId: n.publicId,\n systemId: n.systemId,\n rootId\n };\n case n.ELEMENT_NODE:\n return serializeElementNode(n, {\n doc,\n blockClass,\n blockSelector,\n unblockSelector,\n inlineStylesheet,\n maskAttributeFn,\n maskInputOptions,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement,\n rootId,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n ignoreCSSAttributes\n });\n case n.TEXT_NODE:\n return serializeTextNode(n, {\n doc,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskTextFn,\n maskInputOptions,\n maskInputFn,\n rootId\n });\n case n.CDATA_SECTION_NODE:\n return {\n type: NodeType.CDATA,\n textContent: \"\",\n rootId\n };\n case n.COMMENT_NODE:\n return {\n type: NodeType.Comment,\n textContent: n.textContent || \"\",\n rootId\n };\n default:\n return false;\n }\n}\nfunction getRootId(doc, mirror) {\n if (!mirror.hasNode(doc)) return void 0;\n const docId = mirror.getId(doc);\n return docId === 1 ? void 0 : docId;\n}\nfunction serializeTextNode(n, options) {\n const {\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskTextFn,\n maskInputOptions,\n maskInputFn,\n rootId\n } = options;\n const parentTagName = n.parentNode && n.parentNode.tagName;\n let textContent = n.textContent;\n const isStyle = parentTagName === \"STYLE\" ? true : void 0;\n const isScript = parentTagName === \"SCRIPT\" ? true : void 0;\n const isTextarea = parentTagName === \"TEXTAREA\" ? true : void 0;\n if (isStyle && textContent) {\n try {\n if (n.nextSibling || n.previousSibling) {\n } else if (n.parentNode.sheet?.cssRules) {\n textContent = stringifyStylesheet(\n n.parentNode.sheet\n );\n }\n } catch (err) {\n console.warn(\n `Cannot get CSS styles from text's parentNode. Error: ${err}`,\n n\n );\n }\n textContent = absoluteToStylesheet(textContent, getHref(options.doc));\n }\n if (isScript) {\n textContent = \"SCRIPT_PLACEHOLDER\";\n }\n const forceMask = needMaskingText(\n n,\n maskTextClass,\n maskTextSelector,\n unmaskTextClass,\n unmaskTextSelector,\n maskAllText\n );\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\n textContent = maskTextFn ? maskTextFn(textContent, n.parentElement) : textContent.replace(/[\\S]/g, \"*\");\n }\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\n textContent = maskInputFn ? maskInputFn(textContent, n.parentNode) : textContent.replace(/[\\S]/g, \"*\");\n }\n if (parentTagName === \"OPTION\" && textContent) {\n const isInputMasked = shouldMaskInput({\n type: null,\n tagName: parentTagName,\n maskInputOptions\n });\n textContent = maskInputValue({\n isMasked: needMaskingText(\n n,\n maskTextClass,\n maskTextSelector,\n unmaskTextClass,\n unmaskTextSelector,\n isInputMasked\n ),\n element: n,\n value: textContent,\n maskInputFn\n });\n }\n return {\n type: NodeType.Text,\n textContent: textContent || \"\",\n isStyle,\n rootId\n };\n}\nfunction serializeElementNode(n, options) {\n const {\n doc,\n blockClass,\n blockSelector,\n unblockSelector,\n inlineStylesheet,\n maskInputOptions = {},\n maskAttributeFn,\n maskInputFn,\n dataURLOptions = {},\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement = false,\n rootId,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n ignoreCSSAttributes\n } = options;\n const needBlock = _isBlockedElement(\n n,\n blockClass,\n blockSelector,\n unblockSelector\n );\n const tagName = getValidTagName(n);\n let attributes2 = {};\n const len = n.attributes.length;\n for (let i = 0; i < len; i++) {\n const attr = n.attributes[i];\n if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {\n attributes2[attr.name] = transformAttribute(\n doc,\n tagName,\n toLowerCase(attr.name),\n attr.value,\n n,\n maskAttributeFn,\n ignoreCSSAttributes\n );\n }\n }\n if (tagName === \"link\" && inlineStylesheet) {\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\n return s.href === n.href;\n });\n let cssText = null;\n if (stylesheet) {\n cssText = stringifyStylesheet(stylesheet);\n }\n if (cssText) {\n attributes2.rel = null;\n attributes2.href = null;\n attributes2.crossorigin = null;\n attributes2._cssText = absoluteToStylesheet(cssText, stylesheet.href);\n }\n }\n if (tagName === \"style\" && n.sheet && // TODO: Currently we only try to get dynamic stylesheet when it is an empty style element\n !(n.innerText || n.textContent || \"\").trim().length) {\n const cssText = stringifyStylesheet(\n n.sheet\n );\n if (cssText) {\n attributes2._cssText = absoluteToStylesheet(cssText, getHref(doc));\n }\n }\n if (tagName === \"input\" || tagName === \"textarea\" || tagName === \"select\" || tagName === \"option\") {\n const el = n;\n const type = getInputType(el);\n const value = getInputValue(el, toUpperCase(tagName), type);\n const checked = el.checked;\n if (type !== \"submit\" && type !== \"button\" && value) {\n const forceMask = needMaskingText(\n el,\n maskTextClass,\n maskTextSelector,\n unmaskTextClass,\n unmaskTextSelector,\n shouldMaskInput({\n type,\n tagName: toUpperCase(tagName),\n maskInputOptions\n })\n );\n attributes2.value = maskInputValue({\n isMasked: forceMask,\n element: el,\n value,\n maskInputFn\n });\n }\n if (checked) {\n attributes2.checked = checked;\n }\n }\n if (tagName === \"option\") {\n if (n.selected && !maskInputOptions[\"select\"]) {\n attributes2.selected = true;\n } else {\n delete attributes2.selected;\n }\n }\n if (tagName === \"canvas\" && recordCanvas) {\n if (n.__context === \"2d\") {\n if (!is2DCanvasBlank(n)) {\n attributes2.rr_dataURL = n.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n }\n } else if (!(\"__context\" in n)) {\n const canvasDataURL = n.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n const blankCanvas = doc.createElement(\"canvas\");\n blankCanvas.width = n.width;\n blankCanvas.height = n.height;\n const blankCanvasDataURL = blankCanvas.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes2.rr_dataURL = canvasDataURL;\n }\n }\n }\n if (tagName === \"img\" && inlineImages) {\n if (!canvasService) {\n canvasService = doc.createElement(\"canvas\");\n canvasCtx = canvasService.getContext(\"2d\");\n }\n const image = n;\n const imageSrc = image.currentSrc || image.getAttribute(\"src\") || \"\";\n const priorCrossOrigin = image.crossOrigin;\n const recordInlineImage = () => {\n image.removeEventListener(\"load\", recordInlineImage);\n try {\n canvasService.width = image.naturalWidth;\n canvasService.height = image.naturalHeight;\n canvasCtx.drawImage(image, 0, 0);\n attributes2.rr_dataURL = canvasService.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n } catch (err) {\n if (image.crossOrigin !== \"anonymous\") {\n image.crossOrigin = \"anonymous\";\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else image.addEventListener(\"load\", recordInlineImage);\n return;\n } else {\n console.warn(\n `Cannot inline img src=${imageSrc}! Error: ${err}`\n );\n }\n }\n if (image.crossOrigin === \"anonymous\") {\n priorCrossOrigin ? attributes2.crossOrigin = priorCrossOrigin : image.removeAttribute(\"crossorigin\");\n }\n };\n if (image.complete && image.naturalWidth !== 0) recordInlineImage();\n else image.addEventListener(\"load\", recordInlineImage);\n }\n if (tagName === \"audio\" || tagName === \"video\") {\n attributes2.rr_mediaState = n.paused ? \"paused\" : \"played\";\n attributes2.rr_mediaCurrentTime = n.currentTime;\n }\n if (!newlyAddedElement) {\n if (n.scrollLeft) {\n attributes2.rr_scrollLeft = n.scrollLeft;\n }\n if (n.scrollTop) {\n attributes2.rr_scrollTop = n.scrollTop;\n }\n }\n if (needBlock) {\n const { width, height } = n.getBoundingClientRect();\n attributes2 = {\n class: attributes2.class,\n rr_width: `${width}px`,\n rr_height: `${height}px`\n };\n }\n if (tagName === \"iframe\" && !keepIframeSrcFn(attributes2.src)) {\n if (!needBlock && !getIframeContentDocument(n)) {\n attributes2.rr_src = attributes2.src;\n }\n delete attributes2.src;\n }\n let isCustomElement;\n try {\n if (customElements.get(tagName)) isCustomElement = true;\n } catch (e) {\n }\n return {\n type: NodeType.Element,\n tagName,\n attributes: attributes2,\n childNodes: [],\n isSVG: isSVGElement(n) || void 0,\n needBlock,\n rootId,\n isCustom: isCustomElement\n };\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === void 0 || maybeAttr === null) {\n return \"\";\n } else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\n return true;\n } else if (sn.type === NodeType.Element) {\n if (slimDOMOptions.script && // script tag\n (sn.tagName === \"script\" || // (module)preload link\n sn.tagName === \"link\" && (sn.attributes.rel === \"preload\" || sn.attributes.rel === \"modulepreload\") || // prefetch link\n sn.tagName === \"link\" && sn.attributes.rel === \"prefetch\" && typeof sn.attributes.href === \"string\" && extractFileExtension(sn.attributes.href) === \"js\")) {\n return true;\n } else if (slimDOMOptions.headFavicon && (sn.tagName === \"link\" && sn.attributes.rel === \"shortcut icon\" || sn.tagName === \"meta\" && (lowerIfExists(sn.attributes.name).match(\n /^msapplication-tile(image|color)$/\n ) || lowerIfExists(sn.attributes.name) === \"application-name\" || lowerIfExists(sn.attributes.rel) === \"icon\" || lowerIfExists(sn.attributes.rel) === \"apple-touch-icon\" || lowerIfExists(sn.attributes.rel) === \"shortcut icon\"))) {\n return true;\n } else if (sn.tagName === \"meta\") {\n if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === \"pinterest\")) {\n return true;\n } else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === \"robots\" || lowerIfExists(sn.attributes.name) === \"googlebot\" || lowerIfExists(sn.attributes.name) === \"bingbot\")) {\n return true;\n } else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes[\"http-equiv\"] !== void 0) {\n return true;\n } else if (slimDOMOptions.headMetaAuthorship && (lowerIfExists(sn.attributes.name) === \"author\" || lowerIfExists(sn.attributes.name) === \"generator\" || lowerIfExists(sn.attributes.name) === \"framework\" || lowerIfExists(sn.attributes.name) === \"publisher\" || lowerIfExists(sn.attributes.name) === \"progid\" || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n } else if (slimDOMOptions.headMetaVerification && (lowerIfExists(sn.attributes.name) === \"google-site-verification\" || lowerIfExists(sn.attributes.name) === \"yandex-verification\" || lowerIfExists(sn.attributes.name) === \"csrf-token\" || lowerIfExists(sn.attributes.name) === \"p:domain_verify\" || lowerIfExists(sn.attributes.name) === \"verify-v1\" || lowerIfExists(sn.attributes.name) === \"verification\" || lowerIfExists(sn.attributes.name) === \"shopify-checkout-api-token\")) {\n return true;\n }\n }\n }\n return false;\n}\nfunction serializeNodeWithId(n, options) {\n const {\n doc,\n mirror,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild = false,\n inlineStylesheet = true,\n maskInputOptions = {},\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions = {},\n inlineImages = false,\n recordCanvas = false,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout = 5e3,\n onBlockedImageLoad,\n onStylesheetLoad,\n stylesheetLoadTimeout = 5e3,\n keepIframeSrcFn = () => false,\n newlyAddedElement = false,\n ignoreCSSAttributes\n } = options;\n let { preserveWhiteSpace = true } = options;\n const _serializedNode = serializeNode(n, {\n doc,\n mirror,\n blockClass,\n blockSelector,\n maskAllText,\n unblockSelector,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement,\n ignoreCSSAttributes\n });\n if (!_serializedNode) {\n console.warn(n, \"not serialized\");\n return null;\n }\n let id;\n if (mirror.hasNode(n)) {\n id = mirror.getId(n);\n } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType.Text && !_serializedNode.isStyle && !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, \"\").length) {\n id = IGNORED_NODE;\n } else {\n id = genId();\n }\n const serializedNode2 = Object.assign(_serializedNode, { id });\n mirror.add(n, serializedNode2);\n if (id === IGNORED_NODE) {\n return null;\n }\n if (onSerialize) {\n onSerialize(n);\n }\n let recordChild = !skipChild;\n if (serializedNode2.type === NodeType.Element) {\n recordChild = recordChild && !serializedNode2.needBlock;\n const shadowRoot = n.shadowRoot;\n if (shadowRoot && isNativeShadowDom(shadowRoot))\n serializedNode2.isShadowHost = true;\n }\n if ((serializedNode2.type === NodeType.Document || serializedNode2.type === NodeType.Element) && recordChild) {\n if (slimDOMOptions.headWhitespace && serializedNode2.type === NodeType.Element && serializedNode2.tagName === \"head\") {\n preserveWhiteSpace = false;\n }\n const bypassOptions = {\n doc,\n mirror,\n blockClass,\n blockSelector,\n maskAllText,\n unblockSelector,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onBlockedImageLoad,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n ignoreCSSAttributes\n };\n const childNodes = n.childNodes ? Array.from(n.childNodes) : [];\n for (const childN of childNodes) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode2.childNodes.push(serializedChildNode);\n }\n }\n if (isElement(n) && n.shadowRoot) {\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n isNativeShadowDom(n.shadowRoot) && (serializedChildNode.isShadow = true);\n serializedNode2.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n if (n.parentNode && isShadowRoot(n.parentNode) && isNativeShadowDom(n.parentNode)) {\n serializedNode2.isShadow = true;\n }\n if (serializedNode2.type === NodeType.Element && serializedNode2.tagName === \"iframe\" && !serializedNode2.needBlock) {\n onceIframeLoaded(\n n,\n () => {\n const iframeDoc = getIframeContentDocument(n);\n if (iframeDoc && onIframeLoad) {\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n doc: iframeDoc,\n mirror,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n ignoreCSSAttributes\n });\n if (serializedIframeNode) {\n onIframeLoad(\n n,\n serializedIframeNode\n );\n }\n }\n },\n iframeLoadTimeout\n );\n }\n if (serializedNode2.type === NodeType.Element && serializedNode2.tagName === \"img\" && !n.complete && serializedNode2.needBlock) {\n const image = n;\n const updateImageDimensions = () => {\n if (image.isConnected && !image.complete && onBlockedImageLoad) {\n try {\n const rect = image.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) {\n onBlockedImageLoad(image, serializedNode2, rect);\n }\n } catch (error) {\n }\n }\n image.removeEventListener(\"load\", updateImageDimensions);\n };\n if (image.isConnected) {\n image.addEventListener(\"load\", updateImageDimensions);\n }\n }\n if (serializedNode2.type === NodeType.Element && serializedNode2.tagName === \"link\" && typeof serializedNode2.attributes.rel === \"string\" && (serializedNode2.attributes.rel === \"stylesheet\" || serializedNode2.attributes.rel === \"preload\" && typeof serializedNode2.attributes.href === \"string\" && extractFileExtension(serializedNode2.attributes.href) === \"css\")) {\n onceStylesheetLoaded(\n n,\n () => {\n if (onStylesheetLoad) {\n const serializedLinkNode = serializeNodeWithId(n, {\n doc,\n mirror,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n ignoreCSSAttributes\n });\n if (serializedLinkNode) {\n onStylesheetLoad(\n n,\n serializedLinkNode\n );\n }\n }\n },\n stylesheetLoadTimeout\n );\n }\n if (serializedNode2.type === NodeType.Element) {\n delete serializedNode2.needBlock;\n }\n return serializedNode2;\n}\nfunction snapshot(n, options) {\n const {\n mirror = new Mirror(),\n blockClass = \"rr-block\",\n blockSelector = null,\n unblockSelector = null,\n maskAllText = false,\n maskTextClass = \"rr-mask\",\n unmaskTextClass = null,\n maskTextSelector = null,\n unmaskTextSelector = null,\n inlineStylesheet = true,\n inlineImages = false,\n recordCanvas = false,\n maskAllInputs = false,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOM = false,\n dataURLOptions,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onBlockedImageLoad,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn = () => false,\n ignoreCSSAttributes = /* @__PURE__ */ new Set([])\n } = options || {};\n const maskInputOptions = maskAllInputs === true ? {\n color: true,\n date: true,\n \"datetime-local\": true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true\n } : maskAllInputs === false ? {} : maskAllInputs;\n const slimDOMOptions = slimDOM === true || slimDOM === \"all\" ? (\n // if true: set of sensible options that should not throw away any information\n {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaDescKeywords: slimDOM === \"all\",\n // destructive\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaAuthorship: true,\n headMetaVerification: true\n }\n ) : slimDOM === false ? {} : slimDOM;\n return serializeNodeWithId(n, {\n doc: n,\n mirror,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onBlockedImageLoad,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n newlyAddedElement: false,\n ignoreCSSAttributes\n });\n}\nfunction visitSnapshot(node, onVisit) {\n function walk(current) {\n onVisit(current);\n if (current.type === NodeType.Document || current.type === NodeType.Element) {\n current.childNodes.forEach(walk);\n }\n }\n walk(node);\n}\nfunction cleanupSnapshot() {\n _id = 1;\n}\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\nfunction parse(css, options = {}) {\n let lineno = 1;\n let column = 1;\n function updatePosition(str) {\n const lines = str.match(/\\n/g);\n if (lines) {\n lineno += lines.length;\n }\n const i = str.lastIndexOf(\"\\n\");\n column = i === -1 ? column + str.length : str.length - i;\n }\n function position() {\n const start = { line: lineno, column };\n return (node) => {\n node.position = new Position(start);\n whitespace();\n return node;\n };\n }\n const _Position = class _Position {\n constructor(start) {\n __publicField(this, \"content\");\n __publicField(this, \"start\");\n __publicField(this, \"end\");\n __publicField(this, \"source\");\n this.start = start;\n this.end = { line: lineno, column };\n this.source = options.source;\n this.content = _Position.content;\n }\n };\n __publicField(_Position, \"content\");\n let Position = _Position;\n Position.content = css;\n const errorsList = [];\n function error(msg) {\n const err = new Error(\n `${options.source || \"\"}:${lineno}:${column}: ${msg}`\n );\n err.reason = msg;\n err.filename = options.source;\n err.line = lineno;\n err.column = column;\n err.source = css;\n if (options.silent) {\n errorsList.push(err);\n } else {\n throw err;\n }\n }\n function stylesheet() {\n const rulesList = rules();\n return {\n type: \"stylesheet\",\n stylesheet: {\n source: options.source,\n rules: rulesList,\n parsingErrors: errorsList\n }\n };\n }\n function open() {\n return match(/^{\\s*/);\n }\n function close() {\n return match(/^}/);\n }\n function rules() {\n let node;\n const rules2 = [];\n whitespace();\n comments(rules2);\n while (css.length && css.charAt(0) !== \"}\" && (node = atrule() || rule())) {\n if (node) {\n rules2.push(node);\n comments(rules2);\n }\n }\n return rules2;\n }\n function match(re) {\n const m = re.exec(css);\n if (!m) {\n return;\n }\n const str = m[0];\n updatePosition(str);\n css = css.slice(str.length);\n return m;\n }\n function whitespace() {\n match(/^\\s*/);\n }\n function comments(rules2 = []) {\n let c;\n while (c = comment()) {\n if (c) {\n rules2.push(c);\n }\n c = comment();\n }\n return rules2;\n }\n function comment() {\n const pos = position();\n if (\"/\" !== css.charAt(0) || \"*\" !== css.charAt(1)) {\n return;\n }\n let i = 2;\n while (\"\" !== css.charAt(i) && (\"*\" !== css.charAt(i) || \"/\" !== css.charAt(i + 1))) {\n ++i;\n }\n i += 2;\n if (\"\" === css.charAt(i - 1)) {\n return error(\"End of comment missing\");\n }\n const str = css.slice(2, i - 2);\n column += 2;\n updatePosition(str);\n css = css.slice(i);\n column += 2;\n return pos({\n type: \"comment\",\n comment: str\n });\n }\n function selector() {\n const m = match(/^([^{]+)/);\n if (!m) {\n return;\n }\n const splitSelectors = trim(m[0]).replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, \"\").replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m2) => {\n return m2.replace(/,/g, \"‌\");\n }).split(/\\s*(?![^(]*\\)),\\s*/);\n if (splitSelectors.length <= 1) {\n return splitSelectors.map((s) => {\n return s.replace(/\\u200C/g, \",\");\n });\n }\n let i = 0;\n let j = 0;\n const len = splitSelectors.length;\n const finalSelectors = [];\n while (i < len) {\n const openingParensCount = (splitSelectors[i].match(/\\(/g) || []).length;\n const closingParensCount = (splitSelectors[i].match(/\\)/g) || []).length;\n let unbalancedParens = openingParensCount - closingParensCount;\n if (unbalancedParens >= 1) {\n let foundClosingSelector = false;\n j = i + 1;\n while (j < len) {\n const nextOpeningParensCount = (splitSelectors[j].match(/\\(/g) || []).length;\n const nextClosingParensCount = (splitSelectors[j].match(/\\)/g) || []).length;\n const nextUnbalancedParens = nextClosingParensCount - nextOpeningParensCount;\n if (nextUnbalancedParens === unbalancedParens) {\n finalSelectors.push(splitSelectors.slice(i, j + 1).join(\",\"));\n i = j + 1;\n foundClosingSelector = true;\n break;\n }\n j++;\n unbalancedParens -= nextUnbalancedParens;\n }\n if (foundClosingSelector) {\n continue;\n }\n splitSelectors.slice(i, len).forEach((selector2) => selector2 && finalSelectors.push(selector2));\n break;\n }\n splitSelectors[i] && finalSelectors.push(splitSelectors[i]);\n i++;\n }\n return finalSelectors.map((s) => {\n return s.replace(/\\u200C/g, \",\");\n });\n }\n function declaration() {\n const pos = position();\n const propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\n if (!propMatch) {\n return;\n }\n const prop = trim(propMatch[0]);\n if (!match(/^:\\s*/)) {\n return error(`property missing ':'`);\n }\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\n const ret = pos({\n type: \"declaration\",\n property: prop.replace(commentre, \"\"),\n value: val ? trim(val[0]).replace(commentre, \"\") : \"\"\n });\n match(/^[;\\s]*/);\n return ret;\n }\n function declarations() {\n const decls = [];\n if (!open()) {\n return error(`missing '{'`);\n }\n comments(decls);\n let decl;\n while (decl = declaration()) {\n if (decl !== false) {\n decls.push(decl);\n comments(decls);\n }\n decl = declaration();\n }\n if (!close()) {\n return error(`missing '}'`);\n }\n return decls;\n }\n function keyframe() {\n let m;\n const vals = [];\n const pos = position();\n while (m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/)) {\n vals.push(m[1]);\n match(/^,\\s*/);\n }\n if (!vals.length) {\n return;\n }\n return pos({\n type: \"keyframe\",\n values: vals,\n declarations: declarations()\n });\n }\n function atkeyframes() {\n const pos = position();\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\n if (!m) {\n return;\n }\n const vendor = m[1];\n m = match(/^([-\\w]+)\\s*/);\n if (!m) {\n return error(\"@keyframes missing name\");\n }\n const name = m[1];\n if (!open()) {\n return error(`@keyframes missing '{'`);\n }\n let frame;\n let frames = comments();\n while (frame = keyframe()) {\n frames.push(frame);\n frames = frames.concat(comments());\n }\n if (!close()) {\n return error(`@keyframes missing '}'`);\n }\n return pos({\n type: \"keyframes\",\n name,\n vendor,\n keyframes: frames\n });\n }\n function atsupports() {\n const pos = position();\n const m = match(/^@supports *([^{]+)/);\n if (!m) {\n return;\n }\n const supports = trim(m[1]);\n if (!open()) {\n return error(`@supports missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@supports missing '}'`);\n }\n return pos({\n type: \"supports\",\n supports,\n rules: style\n });\n }\n function athost() {\n const pos = position();\n const m = match(/^@host\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(`@host missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@host missing '}'`);\n }\n return pos({\n type: \"host\",\n rules: style\n });\n }\n function atmedia() {\n const pos = position();\n const m = match(/^@media *([^{]+)/);\n if (!m) {\n return;\n }\n const media = trim(m[1]);\n if (!open()) {\n return error(`@media missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@media missing '}'`);\n }\n return pos({\n type: \"media\",\n media,\n rules: style\n });\n }\n function atcustommedia() {\n const pos = position();\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\n if (!m) {\n return;\n }\n return pos({\n type: \"custom-media\",\n name: trim(m[1]),\n media: trim(m[2])\n });\n }\n function atpage() {\n const pos = position();\n const m = match(/^@page */);\n if (!m) {\n return;\n }\n const sel = selector() || [];\n if (!open()) {\n return error(`@page missing '{'`);\n }\n let decls = comments();\n let decl;\n while (decl = declaration()) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(`@page missing '}'`);\n }\n return pos({\n type: \"page\",\n selectors: sel,\n declarations: decls\n });\n }\n function atdocument() {\n const pos = position();\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\n if (!m) {\n return;\n }\n const vendor = trim(m[1]);\n const doc = trim(m[2]);\n if (!open()) {\n return error(`@document missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@document missing '}'`);\n }\n return pos({\n type: \"document\",\n document: doc,\n vendor,\n rules: style\n });\n }\n function atfontface() {\n const pos = position();\n const m = match(/^@font-face\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(`@font-face missing '{'`);\n }\n let decls = comments();\n let decl;\n while (decl = declaration()) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(`@font-face missing '}'`);\n }\n return pos({\n type: \"font-face\",\n declarations: decls\n });\n }\n const atimport = _compileAtrule(\"import\");\n const atcharset = _compileAtrule(\"charset\");\n const atnamespace = _compileAtrule(\"namespace\");\n function _compileAtrule(name) {\n const re = new RegExp(\n \"^@\" + name + \"\\\\s*((?:\" + [\n /[^\\\\]\"(?:\\\\\"|[^\"])*\"/.source,\n // consume any quoted parts (checking that the double quote isn't itself escaped)\n /[^\\\\]'(?:\\\\'|[^'])*'/.source,\n // same but for single quotes\n \"[^;]\"\n ].join(\"|\") + \")+);\"\n );\n return () => {\n const pos = position();\n const m = match(re);\n if (!m) {\n return;\n }\n const ret = { type: name };\n ret[name] = m[1].trim();\n return pos(ret);\n };\n }\n function atrule() {\n if (css[0] !== \"@\") {\n return;\n }\n return atkeyframes() || atmedia() || atcustommedia() || atsupports() || atimport() || atcharset() || atnamespace() || atdocument() || atpage() || athost() || atfontface();\n }\n function rule() {\n const pos = position();\n const sel = selector();\n if (!sel) {\n return error(\"selector missing\");\n }\n comments();\n return pos({\n type: \"rule\",\n selectors: sel,\n declarations: declarations()\n });\n }\n return addParent(stylesheet());\n}\nfunction trim(str) {\n return str ? str.replace(/^\\s+|\\s+$/g, \"\") : \"\";\n}\nfunction addParent(obj, parent) {\n const isNode = obj && typeof obj.type === \"string\";\n const childParent = isNode ? obj : parent;\n for (const k of Object.keys(obj)) {\n const value = obj[k];\n if (Array.isArray(value)) {\n value.forEach((v) => {\n addParent(v, childParent);\n });\n } else if (value && typeof value === \"object\") {\n addParent(value, childParent);\n }\n }\n if (isNode) {\n Object.defineProperty(obj, \"parent\", {\n configurable: true,\n writable: true,\n enumerable: false,\n value: parent || null\n });\n }\n return obj;\n}\nconst tagMap = {\n script: \"noscript\",\n // camel case svg element tag names\n altglyph: \"altGlyph\",\n altglyphdef: \"altGlyphDef\",\n altglyphitem: \"altGlyphItem\",\n animatecolor: \"animateColor\",\n animatemotion: \"animateMotion\",\n animatetransform: \"animateTransform\",\n clippath: \"clipPath\",\n feblend: \"feBlend\",\n fecolormatrix: \"feColorMatrix\",\n fecomponenttransfer: \"feComponentTransfer\",\n fecomposite: \"feComposite\",\n feconvolvematrix: \"feConvolveMatrix\",\n fediffuselighting: \"feDiffuseLighting\",\n fedisplacementmap: \"feDisplacementMap\",\n fedistantlight: \"feDistantLight\",\n fedropshadow: \"feDropShadow\",\n feflood: \"feFlood\",\n fefunca: \"feFuncA\",\n fefuncb: \"feFuncB\",\n fefuncg: \"feFuncG\",\n fefuncr: \"feFuncR\",\n fegaussianblur: \"feGaussianBlur\",\n feimage: \"feImage\",\n femerge: \"feMerge\",\n femergenode: \"feMergeNode\",\n femorphology: \"feMorphology\",\n feoffset: \"feOffset\",\n fepointlight: \"fePointLight\",\n fespecularlighting: \"feSpecularLighting\",\n fespotlight: \"feSpotLight\",\n fetile: \"feTile\",\n feturbulence: \"feTurbulence\",\n foreignobject: \"foreignObject\",\n glyphref: \"glyphRef\",\n lineargradient: \"linearGradient\",\n radialgradient: \"radialGradient\"\n};\nfunction getTagName(n) {\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\n if (tagName === \"link\" && n.attributes._cssText) {\n tagName = \"style\";\n }\n return tagName;\n}\nfunction escapeRegExp(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, \"g\");\nfunction addHoverClass(cssText, cache) {\n const cachedStyle = cache?.stylesWithHoverClass.get(cssText);\n if (cachedStyle) return cachedStyle;\n if (cssText.length >= 1e6) {\n return cssText;\n }\n const ast = parse(cssText, {\n silent: true\n });\n if (!ast.stylesheet) {\n return cssText;\n }\n const selectors = [];\n ast.stylesheet.rules.forEach((rule) => {\n if (\"selectors\" in rule) {\n (rule.selectors || []).forEach((selector) => {\n if (HOVER_SELECTOR.test(selector)) {\n selectors.push(selector);\n }\n });\n }\n });\n if (selectors.length === 0) {\n return cssText;\n }\n const selectorMatcher = new RegExp(\n selectors.filter((selector, index) => selectors.indexOf(selector) === index).sort((a, b) => b.length - a.length).map((selector) => {\n return escapeRegExp(selector);\n }).join(\"|\"),\n \"g\"\n );\n const result = cssText.replace(selectorMatcher, (selector) => {\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, \"$1.\\\\:hover\");\n return `${selector}, ${newSelector}`;\n });\n cache?.stylesWithHoverClass.set(cssText, result);\n return result;\n}\nfunction createCache() {\n const stylesWithHoverClass = /* @__PURE__ */ new Map();\n return {\n stylesWithHoverClass\n };\n}\nfunction buildNode(n, options) {\n const { doc, hackCss, cache } = options;\n switch (n.type) {\n case NodeType.Document:\n return doc.implementation.createDocument(null, \"\", null);\n case NodeType.DocumentType:\n return doc.implementation.createDocumentType(\n n.name || \"html\",\n n.publicId,\n n.systemId\n );\n case NodeType.Element: {\n const tagName = getTagName(n);\n let node;\n if (n.isSVG) {\n node = doc.createElementNS(\"http://www.w3.org/2000/svg\", tagName);\n } else {\n if (\n // If the tag name is a custom element name\n n.isCustom && // If the browser supports custom elements\n doc.defaultView?.customElements && // If the custom element hasn't been defined yet\n !doc.defaultView.customElements.get(n.tagName)\n )\n doc.defaultView.customElements.define(\n n.tagName,\n class extends doc.defaultView.HTMLElement {\n }\n );\n node = doc.createElement(tagName);\n }\n const specialAttributes = {};\n for (const name in n.attributes) {\n if (!Object.prototype.hasOwnProperty.call(n.attributes, name)) {\n continue;\n }\n let value = n.attributes[name];\n if (tagName === \"option\" && name === \"selected\" && value === false) {\n continue;\n }\n if (value === null) {\n continue;\n }\n if (value === true) value = \"\";\n if (name.startsWith(\"rr_\")) {\n specialAttributes[name] = value;\n continue;\n }\n const isTextarea = tagName === \"textarea\" && name === \"value\";\n const isRemoteOrDynamicCss = tagName === \"style\" && name === \"_cssText\";\n if (isRemoteOrDynamicCss && hackCss && typeof value === \"string\") {\n value = addHoverClass(value, cache);\n }\n if ((isTextarea || isRemoteOrDynamicCss) && typeof value === \"string\") {\n const child = doc.createTextNode(value);\n for (const c of Array.from(node.childNodes)) {\n if (c.nodeType === node.TEXT_NODE) {\n node.removeChild(c);\n }\n }\n node.appendChild(child);\n continue;\n }\n try {\n if (n.isSVG && name === \"xlink:href\") {\n node.setAttributeNS(\n \"http://www.w3.org/1999/xlink\",\n name,\n value.toString()\n );\n } else if (name === \"onload\" || name === \"onclick\" || name.substring(0, 7) === \"onmouse\") {\n node.setAttribute(\"_\" + name, value.toString());\n } else if (tagName === \"meta\" && n.attributes[\"http-equiv\"] === \"Content-Security-Policy\" && name === \"content\") {\n node.setAttribute(\"csp-content\", value.toString());\n continue;\n } else if (tagName === \"link\" && (n.attributes.rel === \"preload\" || n.attributes.rel === \"modulepreload\")) {\n } else if (tagName === \"link\" && n.attributes.rel === \"prefetch\" && typeof n.attributes.href === \"string\" && extractFileExtension(n.attributes.href) === \"js\") {\n } else if (tagName === \"img\" && n.attributes.srcset && n.attributes.rr_dataURL) {\n node.setAttribute(\n \"rrweb-original-srcset\",\n n.attributes.srcset\n );\n } else {\n node.setAttribute(name, value.toString());\n }\n } catch (error) {\n }\n }\n for (const name in specialAttributes) {\n const value = specialAttributes[name];\n if (tagName === \"canvas\" && name === \"rr_dataURL\") {\n const image = doc.createElement(\"img\");\n image.onload = () => {\n const ctx = node.getContext(\"2d\");\n if (ctx) {\n ctx.drawImage(image, 0, 0, image.width, image.height);\n }\n };\n image.src = value.toString();\n if (node.RRNodeType)\n node.rr_dataURL = value.toString();\n } else if (tagName === \"img\" && name === \"rr_dataURL\") {\n const image = node;\n if (!image.currentSrc.startsWith(\"data:\")) {\n image.setAttribute(\n \"rrweb-original-src\",\n n.attributes.src\n );\n image.src = value.toString();\n }\n }\n if (name === \"rr_width\") {\n node.style.setProperty(\"width\", value.toString());\n } else if (name === \"rr_height\") {\n node.style.setProperty(\"height\", value.toString());\n } else if (name === \"rr_mediaCurrentTime\" && typeof value === \"number\") {\n node.currentTime = value;\n } else if (name === \"rr_mediaState\") {\n switch (value) {\n case \"played\":\n node.play().catch((e) => console.warn(\"media playback error\", e));\n break;\n case \"paused\":\n node.pause();\n break;\n }\n }\n }\n if (n.isShadowHost) {\n if (!node.shadowRoot) {\n node.attachShadow({ mode: \"open\" });\n } else {\n while (node.shadowRoot.firstChild) {\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\n }\n }\n }\n return node;\n }\n case NodeType.Text:\n return doc.createTextNode(\n n.isStyle && hackCss ? addHoverClass(n.textContent, cache) : n.textContent\n );\n case NodeType.CDATA:\n if (!(doc instanceof XMLDocument)) {\n return null;\n }\n return doc.createCDATASection(n.textContent);\n case NodeType.Comment:\n return doc.createComment(n.textContent);\n default:\n return null;\n }\n}\nfunction buildNodeWithSN(n, options) {\n const {\n doc,\n mirror,\n skipChild = false,\n hackCss = true,\n afterAppend,\n cache\n } = options;\n if (mirror.has(n.id)) {\n const nodeInMirror = mirror.getNode(n.id);\n const meta = mirror.getMeta(nodeInMirror);\n if (isNodeMetaEqual(meta, n)) return mirror.getNode(n.id);\n }\n let node = buildNode(n, { doc, hackCss, cache });\n if (!node) {\n return null;\n }\n if (n.rootId && mirror.getNode(n.rootId) !== doc) {\n mirror.replace(n.rootId, doc);\n }\n if (n.type === NodeType.Document) {\n doc.close();\n doc.open();\n if (n.compatMode === \"BackCompat\" && n.childNodes && n.childNodes[0].type !== NodeType.DocumentType) {\n if (n.childNodes[0].type === NodeType.Element && \"xmlns\" in n.childNodes[0].attributes && n.childNodes[0].attributes.xmlns === \"http://www.w3.org/1999/xhtml\") {\n doc.write(\n ''\n );\n } else {\n doc.write(\n ''\n );\n }\n }\n node = doc;\n }\n mirror.add(node, n);\n if ((n.type === NodeType.Document || n.type === NodeType.Element) && !skipChild) {\n for (const childN of n.childNodes) {\n const childNode = buildNodeWithSN(childN, {\n doc,\n mirror,\n skipChild: false,\n hackCss,\n afterAppend,\n cache\n });\n if (!childNode) {\n console.warn(\"Failed to rebuild\", childN);\n continue;\n }\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\n node.shadowRoot.appendChild(childNode);\n } else if (n.type === NodeType.Document && childN.type == NodeType.Element) {\n const htmlElement = childNode;\n let body = null;\n htmlElement.childNodes.forEach((child) => {\n if (child.nodeName === \"BODY\") body = child;\n });\n if (body) {\n htmlElement.removeChild(body);\n node.appendChild(childNode);\n htmlElement.appendChild(body);\n } else {\n node.appendChild(childNode);\n }\n } else {\n node.appendChild(childNode);\n }\n if (afterAppend) {\n afterAppend(childNode, childN.id);\n }\n }\n }\n return node;\n}\nfunction visit(mirror, onVisit) {\n function walk(node) {\n onVisit(node);\n }\n for (const id of mirror.getIds()) {\n if (mirror.has(id)) {\n walk(mirror.getNode(id));\n }\n }\n}\nfunction handleScroll(node, mirror) {\n const n = mirror.getMeta(node);\n if (n?.type !== NodeType.Element) {\n return;\n }\n const el = node;\n for (const name in n.attributes) {\n if (!(Object.prototype.hasOwnProperty.call(n.attributes, name) && name.startsWith(\"rr_\"))) {\n continue;\n }\n const value = n.attributes[name];\n if (name === \"rr_scrollLeft\") {\n el.scrollLeft = value;\n }\n if (name === \"rr_scrollTop\") {\n el.scrollTop = value;\n }\n }\n}\nfunction rebuild(n, options) {\n const {\n doc,\n onVisit,\n hackCss = true,\n afterAppend,\n cache,\n mirror = new Mirror()\n } = options;\n const node = buildNodeWithSN(n, {\n doc,\n mirror,\n skipChild: false,\n hackCss,\n afterAppend,\n cache\n });\n visit(mirror, (visitedNode) => {\n if (onVisit) {\n onVisit(visitedNode);\n }\n handleScroll(visitedNode, mirror);\n });\n return node;\n}\nexport {\n IGNORED_NODE,\n Mirror,\n NodeType,\n addHoverClass,\n buildNodeWithSN,\n classMatchesRegex,\n cleanupSnapshot,\n clearTimeout,\n createCache,\n createMatchPredicate,\n createMirror,\n distanceToMatch,\n escapeImportStatement,\n extractFileExtension,\n filterCSSPropertiesFromInlineStyle,\n fixAllCssProperty,\n fixSafariColons,\n genId,\n getIframeContentDocument,\n getInputType,\n getInputValue,\n ignoreAttribute,\n is2DCanvasBlank,\n isCSSImportRule,\n isCSSStyleRule,\n isElement,\n isNativeShadowDom,\n isNodeMetaEqual,\n isShadowRoot,\n maskInputValue,\n needMaskingText,\n onRequestAnimationFrame,\n rebuild,\n serializeNodeWithId,\n setTimeout,\n shouldMaskInput,\n snapshot,\n stringifyRule,\n stringifyStylesheet,\n toLowerCase,\n toUpperCase,\n transformAttribute,\n visitSnapshot\n};\n//# sourceMappingURL=rrweb-snapshot.js.map\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 if (!attributes['data-sentry-component'] && attributes['data-sentry-element']) {\n attributes['data-sentry-component'] = attributes['data-sentry-element'];\n }\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 type { Breadcrumb, HandlerDataDom } from '@sentry/core';\nimport { htmlTreeAsString } from '@sentry/core';\nimport { record } from '@sentry-internal/rrweb';\nimport type { serializedElementNodeWithId, serializedNodeWithId } from '@sentry-internal/rrweb-snapshot';\nimport { NodeType } from '@sentry-internal/rrweb-snapshot';\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?.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 {\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/core';\nimport { htmlTreeAsString } from '@sentry/core';\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 { browserPerformanceTimeOrigin } from '@sentry/core';\nimport { record } from '@sentry-internal/rrweb';\nimport { WINDOW } from '../constants';\nimport type {\n AllPerformanceEntry,\n AllPerformanceEntryData,\n ExperimentalPerformanceResourceTiming,\n NavigationData,\n PaintData,\n ReplayContainer,\n ReplayPerformanceEntry,\n ResourceData,\n WebVitalData,\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\nexport interface Metric {\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 * 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[] | LayoutShift[];\n}\n\ninterface LayoutShift extends PerformanceEntry {\n value: number;\n sources: LayoutShiftAttribution[];\n hadRecentInput: boolean;\n}\n\ninterface LayoutShiftAttribution {\n node?: Node;\n previousRect: DOMRectReadOnly;\n currentRect: DOMRectReadOnly;\n}\n\n/**\n * Handler creater for web vitals\n */\nexport function webVitalHandler(\n getter: (metric: Metric) => ReplayPerformanceEntry,\n replay: ReplayContainer,\n): (data: { metric: Metric }) => void {\n return ({ metric }) => void replay.replayPerformanceEntries.push(getter(metric));\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 const entryType = ENTRY_TYPES[entry.entryType];\n if (!entryType) {\n return null;\n }\n\n return 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 a LCP metric.\n */\nexport function getLargestContentfulPaint(metric: Metric): ReplayPerformanceEntry {\n const lastEntry = metric.entries[metric.entries.length - 1] as (PerformanceEntry & { element?: Node }) | undefined;\n const node = lastEntry?.element ? [lastEntry.element] : undefined;\n return getWebVital(metric, 'largest-contentful-paint', node);\n}\n\nfunction isLayoutShift(entry: PerformanceEntry): entry is LayoutShift {\n return (entry as LayoutShift).sources !== undefined;\n}\n\n/**\n * Add a CLS event to the replay based on a CLS metric.\n */\nexport function getCumulativeLayoutShift(metric: Metric): ReplayPerformanceEntry {\n const layoutShifts: WebVitalData['attributions'] = [];\n const nodes: Node[] = [];\n for (const entry of metric.entries) {\n if (isLayoutShift(entry)) {\n const nodeIds = [];\n for (const source of entry.sources) {\n if (source.node) {\n nodes.push(source.node);\n const nodeId = record.mirror.getId(source.node);\n if (nodeId) {\n nodeIds.push(nodeId);\n }\n }\n }\n layoutShifts.push({ value: entry.value, nodeIds: nodeIds.length ? nodeIds : undefined });\n }\n }\n\n return getWebVital(metric, 'cumulative-layout-shift', nodes, layoutShifts);\n}\n\n/**\n * Add an INP event to the replay based on an INP metric.\n */\nexport function getInteractionToNextPaint(metric: Metric): ReplayPerformanceEntry {\n const lastEntry = metric.entries[metric.entries.length - 1] as (PerformanceEntry & { target?: Node }) | undefined;\n const node = lastEntry?.target ? [lastEntry.target] : undefined;\n return getWebVital(metric, 'interaction-to-next-paint', node);\n}\n\n/**\n * Add an web vital event to the replay based on the web vital metric.\n */\nfunction getWebVital(\n metric: Metric,\n name: string,\n nodes: Node[] | undefined,\n attributions?: WebVitalData['attributions'],\n): ReplayPerformanceEntry {\n const value = metric.value;\n const rating = metric.rating;\n\n const end = getAbsoluteTime(value);\n\n return {\n type: 'web-vital',\n name,\n start: end,\n end,\n data: {\n value,\n size: value,\n rating,\n nodeIds: nodes ? nodes.map(node => record.mirror.getId(node)) : undefined,\n attributions,\n },\n };\n}\n", "import {\n addClsInstrumentationHandler,\n addInpInstrumentationHandler,\n addLcpInstrumentationHandler,\n addPerformanceInstrumentationHandler,\n} from '@sentry-internal/browser-utils';\nimport type { ReplayContainer } from '../types';\nimport {\n getCumulativeLayoutShift,\n getInteractionToNextPaint,\n getLargestContentfulPaint,\n webVitalHandler,\n} 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(webVitalHandler(getLargestContentfulPaint, replay)),\n addClsInstrumentationHandler(webVitalHandler(getCumulativeLayoutShift, replay)),\n addInpInstrumentationHandler(webVitalHandler(getInteractionToNextPaint, replay)),\n );\n\n // A callback to cleanup all handlers\n return () => {\n clearCallbacks.forEach(clearCallback => clearCallback());\n };\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", "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]),s=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(t,e){for(var i=new n(31),s=0;s<31;++s)i[s]=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,s=0,a=new n(r);s>f]=l}else for(o=new n(i),s=0;s>15-t[s]);return o},p=new t(288);for(c=0;c<144;++c)p[c]=8;for(c=144;c<256;++c)p[c]=9;for(c=256;c<280;++c)p[c]=7;for(c=280;c<288;++c)p[c]=8;var g=new t(32);for(c=0;c<32;++c)g[c]=5;var w=d(p,9,0),y=d(g,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(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},_=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},x=function(r,e){for(var i=[],s=0;sd&&(d=o[s].s);var p=new n(d+1),g=A(i[c-1],p,0);if(g>e){s=0;var w=0,y=g-e,m=1<e))break;w+=m-(1<>=y;w>0;){var M=o[s].s;p[M]=0&&w;--s){var E=o[s].s;p[E]==e&&(--p[E],++w)}g=e}return{t:new t(p),l:g}},A=function(t,n,r){return-1==t.s?Math.max(A(t.l,n,r+1),A(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,s=t[0],a=1,o=function(t){e[i++]=t},h=1;h<=r;++h)if(t[h]==s&&h!=r)++a;else{if(!s&&a>2){for(;a>138;a-=138)o(32754);a>2&&(o(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(o(s),--a;a>6;a-=6)o(8304);a>2&&(o(a-3<<5|8208),a=0)}for(;a--;)o(s);a=1,s=t[h]}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 s=0;s4&&!H[s[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(h,p)+T(f,g)+l,X=T(h,M)+T(f,U)+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=w,P=p,Q=y,R=g;for(B=0;B255){_(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;_(r,m,Q[et]),m+=R[et],et>3&&(_(r,m,rt>>5&8191),m+=i[et])}else _(r,m,N[rt]),m+=P[rt]}return _(r,m,N[256]),m+P[256]},C=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,s=0|r.length,a=0;a!=s;){for(var o=Math.min(a+2655,s);a>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(s,a,o,h,u){if(!u&&(u={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),v=new t(c.length+s.length);v.set(c),v.set(s,c.length),s=v,u.w=c.length}return function(s,a,o,h,u,c){var v=c.z||s.length,d=new t(h+v+5*(1+Math.ceil(v/7e3))+u),p=d.subarray(h,d.length-u),g=c.l,w=7&(c.r||0);if(a){w&&(p[0]=c.r>>3);for(var y=C[a-1],M=y>>13,E=8191&y,z=(1<7e3||q>24576)&&(N>423||!g)){w=U(s,p,0,F,I,S,O,q,G,j-G,w),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(s[j+Q]==s[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=_[J])&32767}if(R){F[q++]=268435456|f[Q]<<18|l[R];var it=31&f[Q],st=31&l[R];O+=e[it]+i[st],++I[257+it],++S[st],B=j+Q,++L}else F[q++]=s[j],++I[s[j]]}}for(j=Math.max(j,B);j=v&&(p[w/8|0]=g,at=v),w=k(p,w+1,s.subarray(j,at))}c.i=v}return b(d,0,h+m(w)+u)}(s,null==a.level?6:a.level,null==a.mem?u.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):20:12+a.mem,o,h,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 s=this.b.length-this.s.z;this.b.set(n.subarray(0,s),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(s),32768),this.s.z=n.length-s+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.prototype.flush=function(){this.ondata||E(5),this.s.l&&E(4),this.p(this.b,!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,s=L(t,n,10+((i=n).filename?i.filename.length+1:0),8),a=s.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)}}(s,n),O(s,a-8,r.d()),O(s,a-4,e),s}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.prototype.flush=function(){j.prototype.flush.call(this)},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(G)return G.encode(n);for(var e=n.length,i=new t(n.length+(n.length>>1)),s=0,a=function(t){i[s++]=t},o=0;oi.length){var h=new t(s+8+(e-o<<1));h.set(i),i=h}var f=n.charCodeAt(o);f<128||r?a(f):f<2048?(a(192|f>>6),a(128|63&f)):f>55295&&f<57344?(a(240|(f=65536+(1047552&f)|1023&n.charCodeAt(++o))>>18),a(128|f>>12&63),a(128|f>>6&63),a(128|63&f)):(a(224|f>>12),a(128|f>>6&63),a(128|63&f))}return b(i,0,s)}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(const r of t)n+=r.length;const r=new Uint8Array(n);for(let n=0,e=0,i=t.length;n{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 r from\"./worker\";function e(){const e=new Blob([r]);return URL.createObjectURL(e)}export{e as getWorkerURL};\n", "import type { ConsoleLevel, SeverityLevel } from '@sentry/core';\nimport { addBreadcrumb, captureException, debug as coreDebug, severityLevelFromString } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\ntype ReplayConsoleLevels = Extract;\nconst CONSOLE_LEVELS: readonly ReplayConsoleLevels[] = ['log', 'warn', 'error'] as const;\nconst PREFIX = '[Replay] ';\n\ninterface LoggerConfig {\n captureExceptions: boolean;\n traceInternals: boolean;\n}\n\ntype CoreDebugLogger = typeof coreDebug;\n\ninterface ReplayDebugLogger extends CoreDebugLogger {\n /**\n * Calls `debug.log` but saves breadcrumb in the next tick due to race\n * conditions before replay is initialized.\n */\n infoTick: CoreDebugLogger['log'];\n /**\n * Captures exceptions (`Error`) if \"capture internal exceptions\" is enabled\n */\n exception: CoreDebugLogger['error'];\n /**\n * Configures the logger with additional debugging behavior\n */\n setConfig(config: Partial): void;\n}\n\nfunction _addBreadcrumb(message: unknown, level: SeverityLevel = 'info'): void {\n addBreadcrumb(\n {\n category: 'console',\n data: {\n logger: 'replay',\n },\n level,\n message: `${PREFIX}${message}`,\n },\n { level },\n );\n}\n\nfunction makeReplayDebugLogger(): ReplayDebugLogger {\n let _capture = false;\n let _trace = false;\n\n const _debug: Partial = {\n exception: () => undefined,\n infoTick: () => undefined,\n setConfig: (opts: Partial) => {\n _capture = !!opts.captureExceptions;\n _trace = !!opts.traceInternals;\n },\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n _debug[name] = (...args: unknown[]) => {\n coreDebug[name](PREFIX, ...args);\n if (_trace) {\n _addBreadcrumb(args.join(''), severityLevelFromString(name));\n }\n };\n });\n\n _debug.exception = (error: unknown, ...message: unknown[]) => {\n if (message.length && _debug.error) {\n _debug.error(...message);\n }\n\n coreDebug.error(PREFIX, error);\n\n if (_capture) {\n captureException(error, {\n mechanism: {\n handled: true,\n type: 'auto.function.replay.debug',\n },\n });\n } else if (_trace) {\n // No need for a breadcrumb if `_capture` is enabled since it should be\n // captured as an exception\n _addBreadcrumb(error, 'error');\n }\n };\n\n _debug.infoTick = (...args: unknown[]) => {\n coreDebug.log(PREFIX, ...args);\n if (_trace) {\n // Wait a tick here to avoid race conditions for some initial logs\n // which may be added before replay is initialized\n setTimeout(() => _addBreadcrumb(args[0]), 0);\n }\n };\n } else {\n CONSOLE_LEVELS.forEach(name => {\n _debug[name] = () => undefined;\n });\n }\n\n return _debug as ReplayDebugLogger;\n}\n\nexport const debug = makeReplayDebugLogger();\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 /** @inheritdoc */\n public waitForCheckout: boolean;\n\n private _totalSize: number;\n\n public constructor() {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n this.waitForCheckout = 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 { DEBUG_BUILD } from '../debug-build';\nimport type { WorkerRequest, WorkerResponse } from '../types';\nimport { debug } from '../util/logger';\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 occurred.\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 DEBUG_BUILD && debug.log('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 && debug.error('Error in compression worker: ', 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/core';\nimport { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { debug } from '../util/logger';\nimport { timestampToMs } from '../util/timestamp';\nimport { EventBufferSizeExceededError } from './error';\nimport { WorkerHandler } from './WorkerHandler';\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 /** @inheritdoc */\n public waitForCheckout: 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 this.waitForCheckout = 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 occurred.\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 successfully 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 && debug.exception(e, '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/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { debug } from '../util/logger';\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 waitForCheckout(): boolean {\n return this._used.waitForCheckout;\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 // eslint-disable-next-line @typescript-eslint/adjacent-overload-signatures\n public set waitForCheckout(value: boolean) {\n this._used.waitForCheckout = 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 DEBUG_BUILD && debug.exception(error, '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, waitForCheckout } = 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 this._compression.waitForCheckout = waitForCheckout;\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\n // Can now clear fallback buffer as it's no longer necessary\n this._fallback.clear();\n } catch (error) {\n DEBUG_BUILD && debug.exception(error, 'Failed to add events when switching buffers.');\n }\n }\n}\n", "import { getWorkerURL } from '@sentry-internal/replay-worker';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { EventBuffer, ReplayWorkerURL } from '../types';\nimport { debug } from '../util/logger';\nimport { EventBufferArray } from './EventBufferArray';\nimport { EventBufferProxy } from './EventBufferProxy';\n\ninterface CreateEventBufferParams {\n useCompression: boolean;\n workerUrl?: ReplayWorkerURL;\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 DEBUG_BUILD && debug.log('Using simple buffer');\n return new EventBufferArray();\n}\n\nfunction _loadWorker(customWorkerUrl?: ReplayWorkerURL): EventBufferProxy | void {\n try {\n const workerUrl = customWorkerUrl || _getWorkerUrl();\n\n if (!workerUrl) {\n return;\n }\n\n DEBUG_BUILD && debug.log(`Using compression worker${customWorkerUrl ? ` from ${customWorkerUrl}` : ''}`);\n const worker = new Worker(workerUrl);\n return new EventBufferProxy(worker);\n } catch (error) {\n DEBUG_BUILD && debug.exception(error, '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 { 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 { 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 { uuid4 } from '@sentry/core';\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 const dirty = session.dirty || false;\n\n return {\n id,\n started,\n lastActivity,\n segmentId,\n sampled,\n previousSessionId,\n dirty,\n };\n}\n", "import type { Sampled, Session, SessionOptions } from '../types';\nimport { isSampled } from '../util/isSampled';\nimport { saveSession } from './saveSession';\nimport { makeSession } from './Session';\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", "import { REPLAY_SESSION_KEY, WINDOW } from '../constants';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Session } from '../types';\nimport { hasSessionStorage } from '../util/hasSessionStorage';\nimport { debug } from '../util/logger';\nimport { makeSession } from './Session';\n\n/**\n * Fetches a session from storage\n */\nexport function fetchSession(): 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 DEBUG_BUILD && debug.infoTick('Loading existing session');\n\n return makeSession(sessionObj);\n } catch {\n return null;\n }\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 { DEBUG_BUILD } from '../debug-build';\nimport type { Session, SessionOptions } from '../types';\nimport { debug } from '../util/logger';\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 sessionIdleExpire,\n maxReplayDuration,\n previousSessionId,\n }: {\n sessionIdleExpire: number;\n maxReplayDuration: number;\n previousSessionId?: string;\n },\n sessionOptions: SessionOptions,\n): Session {\n const existingSession = sessionOptions.stickySession && fetchSession();\n\n // No session exists yet, just create a new one\n if (!existingSession) {\n DEBUG_BUILD && debug.infoTick('Creating new session');\n return createSession(sessionOptions, { previousSessionId });\n }\n\n if (!shouldRefreshSession(existingSession, { sessionIdleExpire, maxReplayDuration })) {\n return existingSession;\n }\n\n DEBUG_BUILD && debug.infoTick('Session in sessionStorage is expired, creating new one...');\n return createSession(sessionOptions, { previousSessionId: existingSession.id });\n}\n", "import { getClient } from '@sentry/core';\nimport { EventType } from '@sentry-internal/rrweb';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { EventBufferSizeExceededError } from '../eventBuffer/error';\nimport type { AddEventResult, RecordingEvent, ReplayContainer, ReplayFrameEvent, ReplayPluginOptions } from '../types';\nimport { debug } from './logger';\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 const { eventBuffer } = replay;\n\n if (!eventBuffer || (eventBuffer.waitForCheckout && !isCheckout)) {\n return null;\n }\n\n const isBufferMode = replay.recordingMode === 'buffer';\n\n try {\n if (isCheckout && isBufferMode) {\n eventBuffer.clear();\n }\n\n if (isCheckout) {\n eventBuffer.hasCheckout = true;\n eventBuffer.waitForCheckout = false;\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 eventBuffer.addEvent(eventAfterPossibleCallback);\n } catch (error) {\n const isExceeded = error && error instanceof EventBufferSizeExceededError;\n const reason = isExceeded ? 'addEventSizeExceeded' : 'addEvent';\n const client = getClient();\n\n if (client) {\n // We are limited in the drop reasons:\n // https://github.com/getsentry/snuba/blob/6c73be60716c2fb1c30ca627883207887c733cbd/rust_snuba/src/processors/outcomes.rs#L39\n const dropReason = isExceeded ? 'buffer_overflow' : 'internal_sdk_error';\n client.recordDroppedEvent(dropReason, 'replay');\n }\n\n if (isExceeded && isBufferMode) {\n // Clear buffer and wait for next checkout\n eventBuffer.clear();\n eventBuffer.waitForCheckout = true;\n\n return null;\n }\n\n replay.handleException(error);\n\n await replay.stop({ reason });\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 DEBUG_BUILD &&\n debug.infoTick(`Skipping event with timestamp ${timestampInMs} because it is after maxReplayDuration`);\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 debug.exception(error, 'An error occurred in the `beforeAddRecordingEvent` callback, skipping the event...');\n return null;\n }\n\n return event;\n}\n", "import type { ErrorEvent, Event, FeedbackEvent, ReplayEvent, TransactionEvent } from '@sentry/core';\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 type { ErrorEvent, Event, TransactionEvent, TransportMakeRequestResponse } from '@sentry/core';\nimport { setTimeout } from '@sentry-internal/browser-utils';\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isTransactionEvent } from '../util/eventUtils';\n\ntype AfterSendEventCallback = (event: Event, sendResponse: TransportMakeRequestResponse) => void;\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nexport function handleAfterSendEvent(replay: ReplayContainer): AfterSendEventCallback {\n return (event: Event, sendResponse: TransportMakeRequestResponse) => {\n if (!replay.isEnabled() || (!isErrorEvent(event) && !isTransactionEvent(event))) {\n return;\n }\n\n const statusCode = sendResponse.statusCode;\n\n // We only want to do stuff on successful error sending, otherwise you get error replays without errors attached\n // We skip if we encountered an non-OK status code\n if (!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?.trace?.trace_id && replayContext.traceIds.size < 100) {\n replayContext.traceIds.add(event.contexts.trace.trace_id);\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(async () => {\n try {\n // Capture current event buffer as new replay\n await replay.sendBufferedReplayOrFlush();\n } catch (err) {\n replay.handleException(err);\n }\n });\n}\n", "import type { ErrorEvent, Event } from '@sentry/core';\nimport { getLocationHref } from '@sentry/core';\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?.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 // With newer React versions, the messages changed to a different website https://react.dev/errors/418\n exceptionValue.match(\n /(reactjs\\.org\\/docs\\/error-decoder\\.html\\?invariant=|react\\.dev\\/errors\\/)(418|419|422|423|425)/,\n ) ||\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 data: {\n url: getLocationHref(),\n },\n });\n addBreadcrumbEvent(replay, breadcrumb);\n }\n}\n", "import type { Breadcrumb } from '@sentry/core';\nimport { getClient, normalize } from '@sentry/core';\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\ntype BreadcrumbWithCategory = Required>;\n\n/**\n * Handle breadcrumbs that Sentry captures, and make sure to capture relevant breadcrumbs to Replay as well.\n */\nexport function handleBreadcrumbs(replay: ReplayContainer): void {\n const client = getClient();\n\n if (!client) {\n return;\n }\n\n client.on('beforeAddBreadcrumb', breadcrumb => beforeAddBreadcrumb(replay, breadcrumb));\n}\n\nfunction beforeAddBreadcrumb(replay: ReplayContainer, breadcrumb: Breadcrumb): void {\n if (!replay.isEnabled() || !isBreadcrumbWithCategory(breadcrumb)) {\n return;\n }\n\n const result = normalizeBreadcrumb(breadcrumb);\n if (result) {\n addBreadcrumbEvent(replay, result);\n }\n}\n\n/** Exported only for tests. */\nexport function normalizeBreadcrumb(breadcrumb: Breadcrumb): Breadcrumb | null {\n if (\n !isBreadcrumbWithCategory(breadcrumb) ||\n [\n // fetch & xhr are handled separately,in handleNetworkBreadcrumbs\n 'fetch',\n 'xhr',\n // These two are breadcrumbs for emitted sentry events, we don't care about them\n 'sentry.event',\n 'sentry.transaction',\n ].includes(breadcrumb.category) ||\n // We capture UI breadcrumbs separately\n breadcrumb.category.startsWith('ui.')\n ) {\n return null;\n }\n\n if (breadcrumb.category === 'console') {\n return normalizeConsoleBreadcrumb(breadcrumb);\n }\n\n return createBreadcrumb(breadcrumb);\n}\n\n/** exported for tests only */\nexport function normalizeConsoleBreadcrumb(\n breadcrumb: Omit & BreadcrumbWithCategory,\n): ReplayFrame {\n const args = 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\nfunction isBreadcrumbWithCategory(breadcrumb: Breadcrumb): breadcrumb is BreadcrumbWithCategory {\n return !!breadcrumb.category;\n}\n", "import type { Event, EventHint } from '@sentry/core';\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?.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?.__rrweb__) {\n return true;\n }\n\n return false;\n}\n", "import type { DynamicSamplingContext } from '@sentry/core';\nimport { getActiveSpan, getCurrentScope, getDynamicSamplingContextFromSpan } from '@sentry/core';\n\n/**\n * Reset the `replay_id` field on the DSC.\n */\nexport function resetReplayIdOnDynamicSamplingContext(): void {\n // Reset DSC on the current scope, if there is one\n const dsc = getCurrentScope().getPropagationContext().dsc;\n if (dsc) {\n delete dsc.replay_id;\n }\n\n // Clear it from frozen DSC on the active span\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n const dsc = getDynamicSamplingContextFromSpan(activeSpan);\n delete (dsc as Partial).replay_id;\n }\n}\n", "import type { FeedbackEvent } from '@sentry/core';\nimport { EventType } from '@sentry-internal/rrweb';\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 } from '@sentry/core';\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 `handleGlobalEvent`, 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 type { Event, EventHint } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { saveSession } from '../session/saveSession';\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isFeedbackEvent, isReplayEvent, isTransactionEvent } from '../util/eventUtils';\nimport { isRrwebError } from '../util/isRrwebError';\nimport { debug } from '../util/logger';\nimport { resetReplayIdOnDynamicSamplingContext } from '../util/resetReplayIdOnDynamicSamplingContext';\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(replay: ReplayContainer): (event: Event, hint: EventHint) => Event | null {\n return Object.assign(\n (event: Event, hint: EventHint) => {\n // Do nothing if replay has been disabled or paused\n if (!replay.isEnabled() || replay.isPaused()) {\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 // prevent exceeding replay durations by removing the expired replayId from the DSC\n resetReplayIdOnDynamicSamplingContext();\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 && debug.log('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 // If we sampled this error in buffer mode, immediately mark the session as \"sampled\"\n // by changing the sampled state from 'buffer' to 'session'. Otherwise, if the application is interrupte\n // before `afterSendEvent` occurs, then the session would remain as \"buffer\" but we have an error event\n // that is tagged with a replay id. This could end up creating replays w/ excessive durations because\n // of the linked error.\n if (isErrorEventSampled && replay.recordingMode === 'buffer' && replay.session?.sampled === 'buffer') {\n const session = replay.session;\n session.dirty = true;\n // Save the session if sticky sessions are enabled to persist the state change\n if (replay.getOptions().stickySession) {\n saveSession(session);\n }\n }\n\n return event;\n },\n { id: 'Replay' },\n );\n}\n", "import { EventType } from '@sentry-internal/rrweb';\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/core';\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 { getClient, isSentryRequestUrl } from '@sentry/core';\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 { 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 { stringMatchesSomePattern } from '@sentry/core';\nimport type { NetworkMetaWarning } from '@sentry-internal/browser-utils';\nimport { serializeFormData } from '@sentry-internal/browser-utils';\nimport { NETWORK_BODY_MAX_SIZE, WINDOW } from '../../constants';\nimport type {\n NetworkBody,\n NetworkRequestData,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n ReplayPerformanceEntry,\n} from '../../types';\n\n/** Get the size of a body. */\nexport function getBodySize(body: RequestInit['body']): number | undefined {\n if (!body) {\n return undefined;\n }\n\n const textEncoder = new TextEncoder();\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/** 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: {\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?.length) {\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.entries(headers).reduce((filteredHeaders: Record, [key, value]) => {\n const normalizedKey = key.toLowerCase();\n // Avoid putting empty strings into the headers\n if (allowedHeaders.includes(normalizedKey) && headers[key]) {\n filteredHeaders[normalizedKey] = value;\n }\n return filteredHeaders;\n }, {});\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 } from '@sentry/core';\nimport type { FetchHint, NetworkMetaWarning } from '@sentry-internal/browser-utils';\nimport { getBodyString, getFetchRequestArgBody, setTimeout } from '@sentry-internal/browser-utils';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n ReplayContainer,\n ReplayNetworkOptions,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n} from '../../types';\nimport { debug } from '../../util/logger';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\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 appropriate).\n */\nexport async function captureFetchBreadcrumbToReplay(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions & {\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 && debug.exception(error, 'Failed to capture fetch breadcrumb');\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): void {\n const { input, response } = hint;\n\n const body = input ? getFetchRequestArgBody(input) : undefined;\n const reqSize = getBodySize(body);\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): 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, debug);\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 networkResponseHeaders,\n }: Pick,\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\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 responseBodySize,\n captureDetails,\n headers,\n }: {\n captureDetails: boolean;\n networkCaptureBodies: boolean;\n responseBodySize: number | undefined;\n headers: Record;\n },\n): ReplayNetworkRequestOrResponse | undefined {\n try {\n const size = bodyText?.length && responseBodySize === undefined ? getBodySize(bodyText) : 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 && debug.exception(error, 'Failed to serialize response body');\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 if (error instanceof Error && error.message.indexOf('Timeout') > -1) {\n DEBUG_BUILD && debug.warn('Parsing text body from response timed out');\n return [undefined, 'BODY_PARSE_TIMEOUT'];\n }\n\n DEBUG_BUILD && debug.exception(error, 'Failed to get text body from response');\n return [undefined, 'BODY_PARSE_ERROR'];\n }\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 && debug.exception(error, 'Failed to clone response body');\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\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, XhrBreadcrumbData } from '@sentry/core';\nimport type { NetworkMetaWarning, XhrHint } from '@sentry-internal/browser-utils';\nimport { getBodyString, parseXhrResponseHeaders, SENTRY_XHR_DATA_KEY } from '@sentry-internal/browser-utils';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { ReplayContainer, ReplayNetworkOptions, ReplayNetworkRequestData } from '../../types';\nimport { debug } from '../../util/logger';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\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 appropriate).\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 && debug.exception(error, 'Failed to capture xhr breadcrumb');\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): void {\n const { xhr, input } = hint;\n\n if (!xhr) {\n return;\n }\n\n const reqSize = getBodySize(input);\n const resSize = xhr.getResponseHeader('content-length')\n ? parseContentLengthHeader(xhr.getResponseHeader('content-length'))\n : _getBodySize(xhr.response, xhr.responseType);\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 // ---- This additional network data below is only captured for URLs defined in `networkDetailAllowUrls` ----\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(parseXhrResponseHeaders(xhr), options.networkResponseHeaders);\n\n const [requestBody, requestWarning] = options.networkCaptureBodies ? getBodyString(input, debug) : [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 _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 && debug.warn('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 (error) {\n DEBUG_BUILD && debug.exception(error, 'Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && debug.log('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): number | undefined {\n try {\n const bodyStr = responseType === 'json' && body && typeof body === 'object' ? JSON.stringify(body) : body;\n return getBodySize(bodyStr);\n } catch {\n return undefined;\n }\n}\n", "import type { Breadcrumb, BreadcrumbHint, FetchBreadcrumbData, XhrBreadcrumbData } from '@sentry/core';\nimport { getClient } from '@sentry/core';\nimport type { FetchHint, XhrHint } from '@sentry-internal/browser-utils';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ReplayContainer, ReplayNetworkOptions } from '../types';\nimport { debug } from '../util/logger';\nimport { captureFetchBreadcrumbToReplay, enrichFetchBreadcrumb } from './util/fetchUtils';\nimport { captureXhrBreadcrumbToReplay, enrichXhrBreadcrumb } from './util/xhrUtils';\n\ninterface ExtendedNetworkBreadcrumbsOptions extends ReplayNetworkOptions {\n replay: ReplayContainer;\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 {\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n } = replay.getOptions();\n\n const options: ExtendedNetworkBreadcrumbsOptions = {\n replay,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n };\n\n if (client) {\n client.on('beforeAddBreadcrumb', (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options, breadcrumb, hint));\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);\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);\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 && debug.exception(e, '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?.xhr;\n}\n\nfunction _isFetchHint(hint?: BreadcrumbHint): hint is FetchHint {\n return hint?.response;\n}\n", "import type { DynamicSamplingContext } from '@sentry/core';\nimport { addEventProcessor, getClient } from '@sentry/core';\nimport {\n addClickKeypressInstrumentationHandler,\n addHistoryInstrumentationHandler,\n} from '@sentry-internal/browser-utils';\nimport { handleAfterSendEvent } from '../coreHandlers/handleAfterSendEvent';\nimport { handleBeforeSendEvent } from '../coreHandlers/handleBeforeSendEvent';\nimport { handleBreadcrumbs } from '../coreHandlers/handleBreadcrumbs';\nimport { handleDomListener } from '../coreHandlers/handleDom';\nimport { handleGlobalEventListener } from '../coreHandlers/handleGlobalEvent';\nimport { handleHistorySpanListener } from '../coreHandlers/handleHistory';\nimport { handleNetworkBreadcrumbs } from '../coreHandlers/handleNetworkBreadcrumbs';\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 client = getClient();\n\n addClickKeypressInstrumentationHandler(handleDomListener(replay));\n addHistoryInstrumentationHandler(handleHistorySpanListener(replay));\n handleBreadcrumbs(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);\n addEventProcessor(eventProcessor);\n\n // If a custom client has no hooks yet, we continue to use the \"old\" implementation\n if (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('spanStart', span => {\n replay.lastActiveSpan = span;\n });\n\n // We may be missing the initial spanStart due to timing issues,\n // so we capture it on finish again.\n client.on('spanEnd', span => {\n replay.lastActiveSpan = span;\n });\n\n // We want to attach the replay id to the feedback event\n client.on('beforeSendFeedback', async (feedbackEvent, options) => {\n const replayId = replay.getSessionId();\n if (options?.includeReplay && replay.isEnabled() && replayId && feedbackEvent.contexts?.feedback) {\n // In case the feedback is sent via API and not through our widget, we want to flush replay\n if (feedbackEvent.contexts.feedback.source === 'api') {\n await replay.sendBufferedReplayOrFlush();\n }\n feedbackEvent.contexts.feedback.replay_id = replayId;\n }\n });\n\n client.on('openFeedbackWidget', async () => {\n await replay.sendBufferedReplayOrFlush();\n });\n }\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 {\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 { debounce as debounceCore } from '@sentry/core';\nimport { setTimeout } from '@sentry-internal/browser-utils';\n\ntype 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 return debounceCore(func, wait, {\n ...options,\n // @ts-expect-error - Not quite sure why these types do not match, but this is fine\n setTimeoutImpl: setTimeout,\n });\n}\n", "import { GLOBAL_OBJ } from '@sentry/core';\n\nconst NAVIGATOR = GLOBAL_OBJ.navigator;\n\n/**\n * Disable sampling mousemove events on iOS browsers as this can cause blocking the main thread\n * https://github.com/getsentry/sentry-javascript/issues/14534\n */\nexport function getRecordingSamplingOptions(): Partial<{ sampling: { mousemove: boolean } }> {\n if (\n /iPhone|iPad|iPod/i.test(NAVIGATOR?.userAgent ?? '') ||\n (/Macintosh/i.test(NAVIGATOR?.userAgent ?? '') && NAVIGATOR?.maxTouchPoints && NAVIGATOR?.maxTouchPoints > 1)\n ) {\n return {\n sampling: {\n mousemove: false,\n },\n };\n }\n\n return {};\n}\n", "import { EventType } from '@sentry-internal/rrweb';\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 { debug } from './logger';\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 && debug.warn('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 const session = replay.session;\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. We have an experimental mode\n // to perform multiple checkouts a session (the idea is to improve\n // seeking during playback), so also only include if segmentId is 0\n // (handled in `addSettingsEvent`).\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 // 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' && session && replay.eventBuffer && !session.dirty) {\n const earliestEvent = replay.eventBuffer.getEarliestTimestamp();\n if (earliestEvent) {\n DEBUG_BUILD &&\n debug.log(`Updating session start time to earliest event in buffer to ${new Date(earliestEvent)}`);\n\n session.started = earliestEvent;\n\n if (replay.getOptions().stickySession) {\n saveSession(session);\n }\n }\n }\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 (session?.previousSessionId) {\n return true;\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", "/**\n * Vendored in from @sentry-internal/rrweb.\n *\n * This is a copy of the function from rrweb, it is not nicely exported there.\n */\nexport function closestElementOfNode(node: Node | null): HTMLElement | null {\n if (!node) {\n return null;\n }\n\n // Catch access to node properties to avoid Firefox \"permission denied\" errors\n try {\n const el: HTMLElement | null = node.nodeType === node.ELEMENT_NODE ? (node as HTMLElement) : node.parentElement;\n return el;\n } catch {\n return null;\n }\n}\n", "import type { DsnComponents, ReplayEnvelope, ReplayEvent, ReplayRecordingData } from '@sentry/core';\nimport { createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader } from '@sentry/core';\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/core';\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 { Client, EventHint, ReplayEvent, Scope } from '@sentry/core';\nimport { getIsolationScope, prepareEvent } from '@sentry/core';\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;\n scope: Scope;\n replayId: string;\n event: ReplayEvent;\n}): Promise {\n const integrations =\n typeof client['_integrations'] === 'object' &&\n client['_integrations'] !== null &&\n !Array.isArray(client['_integrations'])\n ? Object.keys(client['_integrations'])\n : undefined;\n\n const eventHint: EventHint = { event_id, integrations };\n\n client.emit('preprocessEvent', event, eventHint);\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 client.emit('postprocessEvent', preparedEvent, eventHint);\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();\n const { name, version, settings } = metadata?.sdk || {};\n\n preparedEvent.sdk = {\n ...preparedEvent.sdk,\n name: name || 'sentry.javascript.unknown',\n version: version || '0.0.0',\n settings,\n };\n\n return preparedEvent;\n}\n", "import type { RateLimits, ReplayEvent, TransportMakeRequestResponse } from '@sentry/core';\nimport { getClient, getCurrentScope, isRateLimited, updateRateLimits } from '@sentry/core';\nimport { REPLAY_EVENT_NAME, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { SendReplayData } from '../types';\nimport { createReplayEnvelope } from './createReplayEnvelope';\nimport { debug } from './logger';\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?.getTransport();\n const dsn = client?.getDsn();\n\n if (!client || !transport || !dsn || !session.sampled) {\n return Promise.resolve({});\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');\n DEBUG_BUILD && debug.log('An event processor returned `null`, will not send event.');\n return Promise.resolve({});\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: 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 // 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 { setContext } from '@sentry/core';\nimport { setTimeout } from '@sentry-internal/browser-utils';\nimport { RETRY_BASE_INTERVAL, RETRY_MAX_COUNT, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport type { SendReplayData } from '../types';\nimport { RateLimitError, sendReplayRequest, TransportStatusCodeError } 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, onError } = 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 (onError) {\n onError(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 type { ReplayRecordingMode, Span } from '@sentry/core';\nimport { getActiveSpan, getClient, getRootSpan, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, spanToJSON } from '@sentry/core';\nimport { EventType, record } from '@sentry-internal/rrweb';\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';\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 { getRecordingSamplingOptions } from './util/getRecordingSamplingOptions';\nimport { getHandleRecordingEmit } from './util/handleRecordingEmit';\nimport { isExpired } from './util/isExpired';\nimport { isSessionExpired } from './util/isSessionExpired';\nimport { debug } from './util/logger';\nimport { resetReplayIdOnDynamicSamplingContext } from './util/resetReplayIdOnDynamicSamplingContext';\nimport { closestElementOfNode } from './util/rrweb';\nimport { sendReplay } from './util/sendReplay';\nimport { RateLimitError } from './util/sendReplayRequest';\nimport type { SKIPPED } from './util/throttle';\nimport { throttle, THROTTLED } 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 two 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 span.\n * This is only available when performance is enabled.\n */\n public lastActiveSpan?: Span;\n\n /**\n * These are here so we can overwrite them in tests etc.\n * @hidden\n */\n public readonly timeouts: Timeouts;\n\n /** The replay has to be manually started, because no sample rate (neither session or error) was provided. */\n private _requiresManualStart: boolean;\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 /**\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\n /**\n * Handle when page is blurred\n */\n private _handleWindowBlur: () => void;\n\n /**\n * Handle when page is focused\n */\n private _handleWindowFocus: () => void;\n\n /** Ensure page remains active when a key is pressed. */\n private _handleKeyboardEvent: (event: KeyboardEvent) => void;\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._requiresManualStart = 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 // Configure replay debug logger w/ experimental options\n if (DEBUG_BUILD) {\n const experiments = options._experiments;\n debug.setConfig({\n captureExceptions: !!experiments.captureExceptions,\n traceInternals: !!experiments.traceInternals,\n });\n }\n\n // We set these handler properties as class properties, to make binding/unbinding them easier\n this._handleVisibilityChange = () => {\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 this._handleWindowBlur = () => {\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 this._handleWindowFocus = () => {\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 this._handleKeyboardEvent = (event: KeyboardEvent) => {\n handleKeyboardEvent(this, event);\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 /** A wrapper to conditionally capture exceptions. */\n public handleException(error: unknown): void {\n DEBUG_BUILD && debug.exception(error);\n if (this._options.onError) {\n this._options.onError(error);\n }\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 const requiresManualStart = errorSampleRate <= 0 && sessionSampleRate <= 0;\n\n this._requiresManualStart = requiresManualStart;\n\n if (requiresManualStart) {\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 DEBUG_BUILD && debug.exception(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 DEBUG_BUILD && debug.infoTick(`Starting replay in ${this.recordingMode} mode`);\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 log a message 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 DEBUG_BUILD && debug.log('Recording is already in progress');\n return;\n }\n\n if (this._isEnabled && this.recordingMode === 'buffer') {\n DEBUG_BUILD && debug.log('Buffering is in progress, call `flush()` to save the replay');\n return;\n }\n\n DEBUG_BUILD && debug.infoTick('Starting replay in session mode');\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 },\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 this.recordingMode = '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 DEBUG_BUILD && debug.log('Buffering is in progress, call `flush()` to save the replay');\n return;\n }\n\n DEBUG_BUILD && debug.infoTick('Starting replay in buffer mode');\n\n const session = loadOrCreateSession(\n {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\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'\n ? { checkoutEveryNms: BUFFER_CHECKOUT_TIME }\n : // Otherwise, use experimental option w/ min checkout time of 6 minutes\n // This is to improve playback seeking as there could potentially be\n // less mutations to process in the worse cases.\n //\n // checkout by \"N\" events is probably ideal, but means we have less\n // control about the number of checkouts we make (which generally\n // increases replay size)\n this._options._experiments.continuousCheckout && {\n // Minimum checkout time is 6 minutes\n checkoutEveryNms: Math.max(360_000, this._options._experiments.continuousCheckout),\n }),\n emit: getHandleRecordingEmit(this),\n ...getRecordingSamplingOptions(),\n onMutation: this._onMutationHandler.bind(this),\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 // Make sure to reset `recordingMode` to `buffer` to avoid any additional\n // breadcrumbs to trigger a flush (e.g. in `addUpdate()`)\n this.recordingMode = 'buffer';\n\n try {\n DEBUG_BUILD && debug.log(`Stopping Replay${reason ? ` triggered by ${reason}` : ''}`);\n\n resetReplayIdOnDynamicSamplingContext();\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?.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 DEBUG_BUILD && debug.log('Pausing replay');\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 DEBUG_BUILD && debug.log('Resuming replay');\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 DEBUG_BUILD && debug.log('Converting buffer to session');\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.session.dirty = false;\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' || !this._isEnabled) {\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 multiple 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 session (=replay) ID\n *\n * @param onlyIfSampled - If true, will only return the session ID if the session is sampled.\n */\n public getSessionId(onlyIfSampled?: boolean): string | undefined {\n if (onlyIfSampled && this.session?.sampled === false) {\n return undefined;\n }\n\n return 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 const lastActiveSpan = this.lastActiveSpan || getActiveSpan();\n const lastRootSpan = lastActiveSpan && getRootSpan(lastActiveSpan);\n\n const attributes = (lastRootSpan && spanToJSON(lastRootSpan).data) || {};\n const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n if (!lastRootSpan || !source || !['route', 'custom'].includes(source)) {\n return undefined;\n }\n\n return spanToJSON(lastRootSpan).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 /**\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 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 * 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 DEBUG_BUILD && debug.log('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 let performanceEntries = createPerformanceEntries(this.performanceEntries).concat(this.replayPerformanceEntries);\n\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n\n // If we are manually starting, we want to ensure we only include performance entries\n // that are after the initial timestamp\n // The reason for this is that we may have performance entries from the page load, but may decide to start\n // the replay later on, in which case we do not want to include these entries.\n // without this, manually started replays can have events long before the actual replay recording starts,\n // which messes with the timeline etc.\n if (this._requiresManualStart) {\n const initialTimestampInSeconds = this._context.initialTimestamp / 1000;\n performanceEntries = performanceEntries.filter(entry => entry.start >= initialTimestampInSeconds);\n }\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 replay was started manually (=no sample rate was given),\n // We do not want to back-port the initial timestamp\n if (!session || !eventBuffer || this._requiresManualStart) {\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 && debug.error('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?.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 accommodate 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 timestamp,\n onError: err => this.handleException(err),\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 const dropReason = err instanceof RateLimitError ? 'ratelimit_backoff' : 'send_error';\n client.recordDroppedEvent(dropReason, '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 async _flush({\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 && debug.error('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 DEBUG_BUILD &&\n debug.log(\n `Session duration (${Math.floor(duration / 1000)}s) is too ${\n tooShort ? 'short' : 'long'\n }, not sending replay.`,\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 DEBUG_BUILD && debug.log('Flushing initial segment without checkout.');\n // TODO FN: Evaluate if we want to stop here, or remove this again?\n }\n\n const _flushInProgress = !!this._flushLock;\n\n // this._flushLock acts as a lock so that future calls to `_flush()` will\n // be blocked until current flush is finished (i.e. this promise resolves)\n if (!this._flushLock) {\n this._flushLock = this._runFlush();\n }\n\n try {\n await this._flushLock;\n } catch (err) {\n this.handleException(err);\n } finally {\n this._flushLock = undefined;\n\n if (_flushInProgress) {\n // Wait for previous flush to finish, then call the debounced\n // `_flush()`. It's possible there are other flush requests queued and\n // waiting for it to resolve. We want to reduce all outstanding\n // requests (as well as any new flush requests that occur within a\n // second of the locked flush completing) into a single flush.\n this._debouncedFlush();\n }\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: MutationRecord[]): boolean {\n const { ignoreMutations } = this._options._experiments;\n if (ignoreMutations?.length) {\n if (\n mutations.some(mutation => {\n const el = closestElementOfNode(mutation.target);\n const selector = ignoreMutations.join(',');\n return el?.matches(selector);\n })\n ) {\n return false;\n }\n }\n\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\ninterface MutationRecord {\n type: string;\n target: Node;\n oldValue: string | null;\n addedNodes: NodeList;\n removedNodes: NodeList;\n attributeName: string | null;\n}\n", "import type { ReplayIntegrationPrivacyOptions } from '../types';\n\ntype GetPrivacyOptions = Required>;\n\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(selectors: string[], defaultSelectors: string[]): string {\n return [\n ...selectors,\n // sentry defaults\n ...defaultSelectors,\n ].join(',');\n}\n\n/**\n * Returns privacy related configuration for use in rrweb\n */\nexport function getPrivacyOptions({ mask, unmask, block, unblock, ignore }: GetPrivacyOptions): GetPrivacyReturn {\n const defaultBlockedElements = ['base', 'iframe[srcdoc]:not([src])'];\n\n const maskSelector = getOption(mask, ['.sentry-mask', '[data-sentry-mask]']);\n const unmaskSelector = getOption(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(block, ['.sentry-block', '[data-sentry-block]', ...defaultBlockedElements]),\n unblockSelector: getOption(unblock, []),\n ignoreSelector: getOption(ignore, ['.sentry-ignore', '[data-sentry-ignore]', 'input[type=\"file\"]']),\n };\n\n return options;\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 precedence\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", "import type { BrowserClientReplayOptions, Client, Integration, IntegrationFn, ReplayRecordingMode } from '@sentry/core';\nimport { consoleSandbox, isBrowser, parseSampleRate } from '@sentry/core';\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 InitialReplayPluginOptions,\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\n/**\n * Sentry integration for [Session Replay](https://sentry.io/for/session-replay/).\n *\n * See the [Replay documentation](https://docs.sentry.io/platforms/javascript/guides/session-replay/) for more information.\n *\n * @example\n *\n * ```\n * Sentry.init({\n * dsn: '__DSN__',\n * integrations: [Sentry.replayIntegration()],\n * });\n * ```\n */\nexport const replayIntegration = ((options?: ReplayConfiguration) => {\n return new Replay(options);\n}) satisfies IntegrationFn;\n\n/**\n * Replay integration\n */\nexport class Replay implements Integration {\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 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', 'aria-label'],\n unmask = [],\n block = [],\n unblock = [],\n ignore = [],\n maskFn,\n\n beforeAddRecordingEvent,\n beforeErrorSampling,\n onError,\n }: ReplayConfiguration = {}) {\n this.name = 'Replay';\n\n const privacyOptions = getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n });\n\n this._recordingOptions = {\n maskAllInputs,\n maskAllText,\n 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 {\n // ignore errors here\n // this can happen if the error is frozen or does not allow mutation for other reasons\n }\n },\n // experimental support for recording iframes from different origins\n recordCrossOriginIframes: Boolean(_experiments.recordCrossOriginIframes),\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 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 onError,\n\n _experiments,\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 this._recordingOptions.ignoreCSSAttributes = new Set(['background-image']);\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 afterAllSetup(client: Client): void {\n if (!isBrowser() || this._replay) {\n return;\n }\n\n this._setup(client);\n this._initialize(client);\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will log a message 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 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 * If replay is not enabled, a new session replay is started.\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) {\n return Promise.resolve();\n }\n\n // assuming a session should be recorded in this case\n if (!this._replay.isEnabled()) {\n this._replay.start();\n return Promise.resolve();\n }\n\n return this._replay.sendBufferedReplayOrFlush(options);\n }\n\n /**\n * Get the current session ID.\n *\n * @param onlyIfSampled - If true, will only return the session ID if the session is sampled.\n *\n */\n public getReplayId(onlyIfSampled?: boolean): string | undefined {\n if (!this._replay?.isEnabled()) {\n return;\n }\n\n return this._replay.getSessionId(onlyIfSampled);\n }\n\n /**\n * Get the current recording mode. This can be either `session` or `buffer`.\n *\n * `session`: Recording the whole session, sending it continuously\n * `buffer`: Always keeping 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 getRecordingMode(): ReplayRecordingMode | undefined {\n if (!this._replay?.isEnabled()) {\n return;\n }\n\n return this._replay.recordingMode;\n }\n\n /**\n * Initializes replay.\n */\n protected _initialize(client: Client): void {\n if (!this._replay) {\n return;\n }\n\n this._maybeLoadFromReplayCanvasIntegration(client);\n this._replay.initializeSampling();\n }\n\n /** Setup the integration. */\n private _setup(client: Client): void {\n // Client is not available in constructor, so we need to wait until setupOnce\n const finalOptions = loadReplayOptionsFromClient(this._initialOptions, client);\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(client: Client): 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 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, client: Client): ReplayPluginOptions {\n const opt = client.getOptions() as BrowserClientReplayOptions;\n\n const finalOptions: ReplayPluginOptions = {\n sessionSampleRate: 0,\n errorSampleRate: 0,\n ...initialOptions,\n };\n\n const replaysSessionSampleRate = parseSampleRate(opt.replaysSessionSampleRate);\n const replaysOnErrorSampleRate = parseSampleRate(opt.replaysOnErrorSampleRate);\n\n if (replaysSessionSampleRate == null && replaysOnErrorSampleRate == null) {\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 (replaysSessionSampleRate != null) {\n finalOptions.sessionSampleRate = replaysSessionSampleRate;\n }\n\n if (replaysOnErrorSampleRate != null) {\n finalOptions.errorSampleRate = 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 { getClient } from '@sentry/core';\nimport type { replayIntegration } from '../integration';\n\n/**\n * This is a small utility to get a type-safe instance of the Replay integration.\n */\nexport function getReplay(): ReturnType | undefined {\n const client = getClient();\n return client?.getIntegrationByName>('Replay');\n}\n", "import { WINDOW } from '../helpers';\n\n/**\n * Checks if the baggage header has Sentry values.\n */\nexport function baggageHeaderHasSentryValues(baggageHeader: string): boolean {\n return baggageHeader.split(',').some(value => value.trim().startsWith('sentry-'));\n}\n\n/**\n * Gets the full URL from a given URL string.\n */\nexport function 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\n/**\n * Checks if the entry is a PerformanceResourceTiming.\n */\nexport function 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 Headers object from a record of string key-value pairs, and returns undefined if it fails.\n */\nexport function createHeadersSafely(headers: Record | undefined): Headers | undefined {\n try {\n return new Headers(headers);\n } catch {\n // noop\n return undefined;\n }\n}\n", "import type {\n Client,\n HandlerDataXhr,\n RequestHookInfo,\n ResponseHookInfo,\n SentryWrappedXMLHttpRequest,\n Span,\n} from '@sentry/core';\nimport {\n addFetchEndInstrumentationHandler,\n addFetchInstrumentationHandler,\n getActiveSpan,\n getClient,\n getLocationHref,\n getTraceData,\n hasSpansEnabled,\n instrumentFetchRequest,\n parseUrl,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SentryNonRecordingSpan,\n setHttpStatus,\n spanToJSON,\n startInactiveSpan,\n stringMatchesSomePattern,\n stripUrlQueryAndFragment,\n} from '@sentry/core';\nimport type { XhrHint } from '@sentry-internal/browser-utils';\nimport {\n addPerformanceInstrumentationHandler,\n addXhrInstrumentationHandler,\n parseXhrResponseHeaders,\n resourceTimingToSpanAttributes,\n SENTRY_XHR_DATA_KEY,\n} from '@sentry-internal/browser-utils';\nimport type { BrowserClient } from '../client';\nimport { baggageHeaderHasSentryValues, createHeadersSafely, getFullURL, isPerformanceResourceTiming } from './utils';\n\n/** Options for Request Instrumentation */\nexport interface RequestInstrumentationOptions {\n /**\n * List of strings and/or Regular Expressions used to determine which outgoing requests will have `sentry-trace` and `baggage`\n * headers attached.\n *\n * **Default:** If this option is not provided, tracing headers will be attached to all outgoing requests.\n * If you are using a browser SDK, by default, tracing headers will only be attached to outgoing requests to the same origin.\n *\n * **Disclaimer:** Carelessly setting this option in browser environments may result into CORS errors!\n * Only attach tracing headers to requests to the same origin, or to requests to services you can control CORS headers of.\n * Cross-origin requests, meaning requests to a different domain, for example a request to `https://api.example.com/` while you're on `https://example.com/`, take special care.\n * If you are attaching headers to cross-origin requests, make sure the backend handling the request returns a `\"Access-Control-Allow-Headers: sentry-trace, baggage\"` header to ensure your requests aren't blocked.\n *\n * If you provide a `tracePropagationTargets` array, the entries you provide will be matched against the entire URL of the outgoing request.\n * If you are using a browser SDK, the entries will also be matched against the pathname of the outgoing requests.\n * This is so you can have matchers for relative requests, for example, `/^\\/api/` if you want to trace requests to your `/api` routes on the same domain.\n *\n * If any of the two match any of the provided values, tracing headers will be attached to the outgoing request.\n * Both, the string values, and the RegExes you provide in the array will match if they partially match the URL or pathname.\n *\n * Examples:\n * - `tracePropagationTargets: [/^\\/api/]` and request to `https://same-origin.com/api/posts`:\n * - Tracing headers will be attached because the request is sent to the same origin and the regex matches the pathname \"/api/posts\".\n * - `tracePropagationTargets: [/^\\/api/]` and request to `https://different-origin.com/api/posts`:\n * - Tracing headers will not be attached because the pathname will only be compared when the request target lives on the same origin.\n * - `tracePropagationTargets: [/^\\/api/, 'https://external-api.com']` and request to `https://external-api.com/v1/data`:\n * - Tracing headers will be attached because the request URL matches the string `'https://external-api.com'`.\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 * Flag to disable tracking of long-lived streams, like server-sent events (SSE) via fetch.\n * Do not enable this in case you have live streams or very long running streams.\n *\n * Disabled by default since it can lead to issues with streams using the `cancel()` api\n * (https://github.com/getsentry/sentry-javascript/issues/13950)\n *\n * Default: false\n */\n trackFetchStreamPerformance: 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 /**\n * Is called when spans are started for outgoing requests.\n */\n onRequestSpanStart?(span: Span, requestInformation: RequestHookInfo): void;\n\n /**\n * Is called when spans end for outgoing requests, providing access to response headers.\n */\n onRequestSpanEnd?(span: Span, responseInformation: ResponseHookInfo): void;\n}\n\nconst responseToSpanId = new WeakMap();\nconst spanIdToEndTimestamp = new Map();\n\nexport const defaultRequestInstrumentationOptions: RequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n enableHTTPTimings: true,\n trackFetchStreamPerformance: false,\n};\n\n/** Registers span creators for xhr and fetch requests */\nexport function instrumentOutgoingRequests(client: Client, _options?: Partial): void {\n const {\n traceFetch,\n traceXHR,\n trackFetchStreamPerformance,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n tracePropagationTargets,\n onRequestSpanStart,\n onRequestSpanEnd,\n } = {\n ...defaultRequestInstrumentationOptions,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_: string) => true;\n\n const shouldAttachHeadersWithTargets = (url: string): boolean => shouldAttachHeaders(url, tracePropagationTargets);\n\n const spans: Record = {};\n\n const propagateTraceparent = (client as BrowserClient).getOptions().propagateTraceparent;\n\n if (traceFetch) {\n // Keeping track of http requests, whose body payloads resolved later than the initial resolved request\n // e.g. streaming using server sent events (SSE)\n client.addEventProcessor(event => {\n if (event.type === 'transaction' && event.spans) {\n event.spans.forEach(span => {\n if (span.op === 'http.client') {\n const updatedTimestamp = spanIdToEndTimestamp.get(span.span_id);\n if (updatedTimestamp) {\n span.timestamp = updatedTimestamp / 1000;\n spanIdToEndTimestamp.delete(span.span_id);\n }\n }\n });\n }\n return event;\n });\n\n if (trackFetchStreamPerformance) {\n addFetchEndInstrumentationHandler(handlerData => {\n if (handlerData.response) {\n const span = responseToSpanId.get(handlerData.response);\n if (span && handlerData.endTimestamp) {\n spanIdToEndTimestamp.set(span, handlerData.endTimestamp);\n }\n }\n });\n }\n\n addFetchInstrumentationHandler(handlerData => {\n const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans, {\n propagateTraceparent,\n onRequestSpanEnd,\n });\n\n if (handlerData.response && handlerData.fetchData.__span) {\n responseToSpanId.set(handlerData.response, handlerData.fetchData.__span);\n }\n\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 if (enableHTTPTimings) {\n addHTTPTimings(createdSpan);\n }\n\n onRequestSpanStart?.(createdSpan, { headers: handlerData.headers });\n }\n });\n }\n\n if (traceXHR) {\n addXhrInstrumentationHandler(handlerData => {\n const createdSpan = xhrCallback(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeadersWithTargets,\n spans,\n propagateTraceparent,\n onRequestSpanEnd,\n );\n\n if (createdSpan) {\n if (enableHTTPTimings) {\n addHTTPTimings(createdSpan);\n }\n\n onRequestSpanStart?.(createdSpan, {\n headers: createHeadersSafely(handlerData.xhr.__sentry_xhr_v3__?.request_headers),\n });\n }\n });\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 span.setAttributes(resourceTimingToSpanAttributes(entry));\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 * A function that determines whether to attach tracing headers to a request.\n * We only export this function for testing purposes.\n */\nexport function shouldAttachHeaders(\n targetUrl: string,\n tracePropagationTargets: (string | RegExp)[] | undefined,\n): boolean {\n // window.location.href not being defined is an edge case in the browser but we need to handle it.\n // Potentially dangerous situations where it may not be defined: Browser Extensions, Web Workers, patching of the location obj\n const href = getLocationHref();\n\n if (!href) {\n // If there is no window.location.origin, we default to only attaching tracing headers to relative requests, i.e. ones that start with `/`\n // BIG DISCLAIMER: Users can call URLs with a double slash (fetch(\"//example.com/api\")), this is a shorthand for \"send to the same protocol\",\n // so we need a to exclude those requests, because they might be cross origin.\n const isRelativeSameOriginRequest = !!targetUrl.match(/^\\/(?!\\/)/);\n if (!tracePropagationTargets) {\n return isRelativeSameOriginRequest;\n } else {\n return stringMatchesSomePattern(targetUrl, tracePropagationTargets);\n }\n } else {\n let resolvedUrl;\n let currentOrigin;\n\n // URL parsing may fail, we default to not attaching trace headers in that case.\n try {\n resolvedUrl = new URL(targetUrl, href);\n currentOrigin = new URL(href).origin;\n } catch {\n return false;\n }\n\n const isSameOriginRequest = resolvedUrl.origin === currentOrigin;\n if (!tracePropagationTargets) {\n return isSameOriginRequest;\n } else {\n return (\n stringMatchesSomePattern(resolvedUrl.toString(), tracePropagationTargets) ||\n (isSameOriginRequest && stringMatchesSomePattern(resolvedUrl.pathname, tracePropagationTargets))\n );\n }\n }\n}\n\n/**\n * Create and track xhr request spans\n *\n * @returns Span if a span was created, otherwise void.\n */\nfunction xhrCallback(\n handlerData: HandlerDataXhr,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record,\n propagateTraceparent?: boolean,\n onRequestSpanEnd?: RequestInstrumentationOptions['onRequestSpanEnd'],\n): Span | undefined {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr?.[SENTRY_XHR_DATA_KEY];\n\n if (!xhr || xhr.__sentry_own_request__ || !sentryXhrData) {\n return undefined;\n }\n\n const { url, method } = sentryXhrData;\n\n const shouldCreateSpanResult = hasSpansEnabled() && shouldCreateSpan(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 onRequestSpanEnd?.(span, {\n headers: createHeadersSafely(parseXhrResponseHeaders(xhr as XMLHttpRequest & SentryWrappedXMLHttpRequest)),\n error: handlerData.error,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const fullUrl = getFullURL(url);\n const parsedUrl = fullUrl ? parseUrl(fullUrl) : parseUrl(url);\n\n const urlForSpanName = stripUrlQueryAndFragment(url);\n\n const hasParent = !!getActiveSpan();\n\n const span =\n shouldCreateSpanResult && hasParent\n ? startInactiveSpan({\n name: `${method} ${urlForSpanName}`,\n attributes: {\n url,\n type: 'xhr',\n 'http.method': method,\n 'http.url': fullUrl,\n 'server.address': parsedUrl?.host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.client',\n ...(parsedUrl?.search && { 'http.query': parsedUrl?.search }),\n ...(parsedUrl?.hash && { 'http.fragment': parsedUrl?.hash }),\n },\n })\n : new SentryNonRecordingSpan();\n\n xhr.__sentry_xhr_span_id__ = span.spanContext().spanId;\n spans[xhr.__sentry_xhr_span_id__] = span;\n\n if (shouldAttachHeaders(url)) {\n addTracingHeadersToXhrRequest(\n xhr,\n // If performance is disabled (TWP) or there's no active root span (pageload/navigation/interaction),\n // we do not want to use the span as base for the trace headers,\n // which means that the headers will be generated from the scope and the sampling decision is deferred\n hasSpansEnabled() && hasParent ? span : undefined,\n propagateTraceparent,\n );\n }\n\n const client = getClient();\n if (client) {\n client.emit('beforeOutgoingRequestSpan', span, handlerData as XhrHint);\n }\n\n return span;\n}\n\nfunction addTracingHeadersToXhrRequest(\n xhr: SentryWrappedXMLHttpRequest,\n span?: Span,\n propagateTraceparent?: boolean,\n): void {\n const { 'sentry-trace': sentryTrace, baggage, traceparent } = getTraceData({ span, propagateTraceparent });\n\n if (sentryTrace) {\n setHeaderOnXhr(xhr, sentryTrace, baggage, traceparent);\n }\n}\n\nfunction setHeaderOnXhr(\n xhr: SentryWrappedXMLHttpRequest,\n sentryTraceHeader: string,\n sentryBaggageHeader: string | undefined,\n traceparentHeader: string | undefined,\n): void {\n const originalHeaders = xhr.__sentry_xhr_v3__?.request_headers;\n\n if (originalHeaders?.['sentry-trace'] || !xhr.setRequestHeader) {\n // bail if a sentry-trace header is already set\n return;\n }\n\n try {\n xhr.setRequestHeader('sentry-trace', sentryTraceHeader);\n\n if (traceparentHeader && !originalHeaders?.['traceparent']) {\n xhr.setRequestHeader('traceparent', traceparentHeader);\n }\n\n if (sentryBaggageHeader) {\n // only add our headers if\n // - no pre-existing baggage header exists\n // - or it is set and doesn't yet contain sentry values\n const originalBaggageHeader = originalHeaders?.['baggage'];\n if (!originalBaggageHeader || !baggageHeaderHasSentryValues(originalBaggageHeader)) {\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 xhr.setRequestHeader('baggage', sentryBaggageHeader);\n }\n }\n } catch {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n}\n", "import { debug, getActiveSpan, getRootSpan, SPAN_STATUS_ERROR, spanToJSON } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\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 const activeSpan = getActiveSpan();\n if (!activeSpan) {\n return;\n }\n\n const rootSpan = getRootSpan(activeSpan);\n\n if (WINDOW.document.hidden && rootSpan) {\n const cancelledStatus = 'cancelled';\n\n const { op, status } = spanToJSON(rootSpan);\n\n if (DEBUG_BUILD) {\n debug.log(`[Tracing] Transaction: ${cancelledStatus} -> since tab moved to the background, op: ${op}`);\n }\n\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 rootSpan.setStatus({ code: SPAN_STATUS_ERROR, message: cancelledStatus });\n }\n\n rootSpan.setAttribute('sentry.cancellation_reason', 'document.hidden');\n rootSpan.end();\n }\n });\n } else {\n DEBUG_BUILD && debug.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n", "import type { Client, PropagationContext, Span, SpanContextData } from '@sentry/core';\nimport {\n debug,\n getCurrentScope,\n getRootSpan,\n SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,\n SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE,\n spanToJSON,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../exports';\n\nexport interface PreviousTraceInfo {\n /**\n * Span context of the previous trace's local root span\n */\n spanContext: SpanContextData;\n\n /**\n * Timestamp in seconds when the previous trace was started\n */\n startTimestamp: number;\n\n /**\n * sample rate of the previous trace\n */\n sampleRate: number;\n\n /**\n * The sample rand of the previous trace\n */\n sampleRand: number;\n}\n\n// 1h in seconds\nexport const PREVIOUS_TRACE_MAX_DURATION = 3600;\n\n// session storage key\nexport const PREVIOUS_TRACE_KEY = 'sentry_previous_trace';\n\nexport const PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE = 'sentry.previous_trace';\n\n/**\n * Takes care of linking traces and applying the (consistent) sampling behavoiour based on the passed options\n * @param options - options for linking traces and consistent trace sampling (@see BrowserTracingOptions)\n * @param client - Sentry client\n */\nexport function linkTraces(\n client: Client,\n {\n linkPreviousTrace,\n consistentTraceSampling,\n }: {\n linkPreviousTrace: 'session-storage' | 'in-memory';\n consistentTraceSampling: boolean;\n },\n): void {\n const useSessionStorage = linkPreviousTrace === 'session-storage';\n\n let inMemoryPreviousTraceInfo = useSessionStorage ? getPreviousTraceFromSessionStorage() : undefined;\n\n client.on('spanStart', span => {\n if (getRootSpan(span) !== span) {\n return;\n }\n\n const oldPropagationContext = getCurrentScope().getPropagationContext();\n inMemoryPreviousTraceInfo = addPreviousTraceSpanLink(inMemoryPreviousTraceInfo, span, oldPropagationContext);\n\n if (useSessionStorage) {\n storePreviousTraceInSessionStorage(inMemoryPreviousTraceInfo);\n }\n });\n\n let isFirstTraceOnPageload = true;\n if (consistentTraceSampling) {\n /*\n When users opt into `consistentTraceSampling`, we need to ensure that we propagate\n the previous trace's sample rate and rand to the current trace. This is necessary because otherwise, span\n metric extrapolation is inaccurate, as we'd propagate too high of a sample rate for the subsequent traces.\n\n So therefore, we pretend that the previous trace was the parent trace of the newly started trace. To do that,\n we mutate the propagation context of the current trace and set the sample rate and sample rand of the previous trace.\n Timing-wise, it is fine because it happens before we even sample the root span.\n\n @see https://github.com/getsentry/sentry-javascript/issues/15754\n */\n client.on('beforeSampling', mutableSamplingContextData => {\n if (!inMemoryPreviousTraceInfo) {\n return;\n }\n\n const scope = getCurrentScope();\n const currentPropagationContext = scope.getPropagationContext();\n\n // We do not want to force-continue the sampling decision if we continue a trace\n // that was started on the backend. Most prominently, this will happen in MPAs where\n // users hard-navigate between pages. In this case, the sampling decision of a potentially\n // started trace on the server takes precedence.\n // Why? We want to prioritize inter-trace consistency over intra-trace consistency.\n if (isFirstTraceOnPageload && currentPropagationContext.parentSpanId) {\n isFirstTraceOnPageload = false;\n return;\n }\n\n scope.setPropagationContext({\n ...currentPropagationContext,\n dsc: {\n ...currentPropagationContext.dsc,\n sample_rate: String(inMemoryPreviousTraceInfo.sampleRate),\n sampled: String(spanContextSampled(inMemoryPreviousTraceInfo.spanContext)),\n },\n sampleRand: inMemoryPreviousTraceInfo.sampleRand,\n });\n\n mutableSamplingContextData.parentSampled = spanContextSampled(inMemoryPreviousTraceInfo.spanContext);\n mutableSamplingContextData.parentSampleRate = inMemoryPreviousTraceInfo.sampleRate;\n\n mutableSamplingContextData.spanAttributes = {\n ...mutableSamplingContextData.spanAttributes,\n [SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]: inMemoryPreviousTraceInfo.sampleRate,\n };\n });\n }\n}\n\n/**\n * Adds a previous_trace span link to the passed span if the passed\n * previousTraceInfo is still valid.\n *\n * @returns the updated previous trace info (based on the current span/trace) to\n * be used on the next call\n */\nexport function addPreviousTraceSpanLink(\n previousTraceInfo: PreviousTraceInfo | undefined,\n span: Span,\n oldPropagationContext: PropagationContext,\n): PreviousTraceInfo {\n const spanJson = spanToJSON(span);\n\n function getSampleRate(): number {\n try {\n return (\n Number(oldPropagationContext.dsc?.sample_rate) ?? Number(spanJson.data?.[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE])\n );\n } catch {\n return 0;\n }\n }\n\n const updatedPreviousTraceInfo = {\n spanContext: span.spanContext(),\n startTimestamp: spanJson.start_timestamp,\n sampleRate: getSampleRate(),\n sampleRand: oldPropagationContext.sampleRand,\n };\n\n if (!previousTraceInfo) {\n return updatedPreviousTraceInfo;\n }\n\n const previousTraceSpanCtx = previousTraceInfo.spanContext;\n if (previousTraceSpanCtx.traceId === spanJson.trace_id) {\n // This means, we're still in the same trace so let's not update the previous trace info\n // or add a link to the current span.\n // Once we move away from the long-lived, route-based trace model, we can remove this cases\n return previousTraceInfo;\n }\n\n // Only add the link if the startTimeStamp of the previous trace's root span is within\n // PREVIOUS_TRACE_MAX_DURATION (1h) of the current root span's startTimestamp\n // This is done to\n // - avoid adding links to \"stale\" traces\n // - enable more efficient querying for previous/next traces in Sentry\n if (Date.now() / 1000 - previousTraceInfo.startTimestamp <= PREVIOUS_TRACE_MAX_DURATION) {\n if (DEBUG_BUILD) {\n debug.log(\n `Adding previous_trace ${previousTraceSpanCtx} link to span ${{\n op: spanJson.op,\n ...span.spanContext(),\n }}`,\n );\n }\n\n span.addLink({\n context: previousTraceSpanCtx,\n attributes: {\n [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: 'previous_trace',\n },\n });\n\n // TODO: Remove this once EAP can store span links. We currently only set this attribute so that we\n // can obtain the previous trace information from the EAP store. Long-term, EAP will handle\n // span links and then we should remove this again. Also throwing in a TODO(v11), to remind us\n // to check this at v11 time :)\n span.setAttribute(\n PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE,\n `${previousTraceSpanCtx.traceId}-${previousTraceSpanCtx.spanId}-${\n spanContextSampled(previousTraceSpanCtx) ? 1 : 0\n }`,\n );\n }\n\n return updatedPreviousTraceInfo;\n}\n\n/**\n * Stores @param previousTraceInfo in sessionStorage.\n */\nexport function storePreviousTraceInSessionStorage(previousTraceInfo: PreviousTraceInfo): void {\n try {\n WINDOW.sessionStorage.setItem(PREVIOUS_TRACE_KEY, JSON.stringify(previousTraceInfo));\n } catch (e) {\n // Ignore potential errors (e.g. if sessionStorage is not available)\n DEBUG_BUILD && debug.warn('Could not store previous trace in sessionStorage', e);\n }\n}\n\n/**\n * Retrieves the previous trace from sessionStorage if available.\n */\nexport function getPreviousTraceFromSessionStorage(): PreviousTraceInfo | undefined {\n try {\n const previousTraceInfo = WINDOW.sessionStorage?.getItem(PREVIOUS_TRACE_KEY);\n // @ts-expect-error - intentionally risking JSON.parse throwing when previousTraceInfo is null to save bundle size\n return JSON.parse(previousTraceInfo);\n } catch {\n return undefined;\n }\n}\n\n/**\n * see {@link import('@sentry/core').spanIsSampled}\n */\nexport function spanContextSampled(ctx: SpanContextData): boolean {\n return ctx.traceFlags === 0x1;\n}\n", "/* eslint-disable max-lines */\nimport type {\n Client,\n IntegrationFn,\n RequestHookInfo,\n ResponseHookInfo,\n Span,\n StartSpanOptions,\n TransactionSource,\n} from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n browserPerformanceTimeOrigin,\n dateTimestampInSeconds,\n debug,\n generateSpanId,\n generateTraceId,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromSpan,\n getIsolationScope,\n getLocationHref,\n GLOBAL_OBJ,\n hasSpansEnabled,\n parseStringToURLObject,\n propagationContextFromHeaders,\n registerSpanErrorInstrumentation,\n SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n spanIsSampled,\n spanToJSON,\n startIdleSpan,\n startInactiveSpan,\n timestampInSeconds,\n TRACING_DEFAULTS,\n} from '@sentry/core';\nimport {\n addHistoryInstrumentationHandler,\n addPerformanceEntries,\n registerInpInteractionListener,\n startTrackingElementTiming,\n startTrackingINP,\n startTrackingInteractions,\n startTrackingLongAnimationFrames,\n startTrackingLongTasks,\n startTrackingWebVitals,\n} from '@sentry-internal/browser-utils';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getHttpRequestData, WINDOW } from '../helpers';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { linkTraces } from './linkedTraces';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\n\nexport const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\ninterface RouteInfo {\n name: string | undefined;\n source: TransactionSource | undefined;\n}\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions {\n /**\n * The time that has to pass without any span being created.\n * If this time is exceeded, the idle span will finish.\n *\n * Default: 1000 (ms)\n */\n idleTimeout: number;\n\n /**\n * The max. time an idle span may run.\n * If this time is exceeded, the idle span will finish no matter what.\n *\n * Default: 30000 (ms)\n */\n finalTimeout: number;\n\n /**\n The max. time an idle span may run.\n * If this time is exceeded, the idle span will finish no matter what.\n *\n * Default: 15000 (ms)\n */\n childSpanTimeout: 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 long animation frames and add them to the corresponding transaction.\n *\n * Default: false\n */\n enableLongAnimationFrame: boolean;\n\n /**\n * If true, Sentry will capture first input delay and add it to the corresponding transaction.\n *\n * Default: true\n */\n enableInp: boolean;\n\n /**\n * If true, Sentry will capture [element timing](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceElementTiming)\n * information and add it to the corresponding transaction.\n *\n * Default: true\n */\n enableElementTiming: boolean;\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 * Flag to disable tracking of long-lived streams, like server-sent events (SSE) via fetch.\n * Do not enable this in case you have live streams or very long running streams.\n *\n * Default: false\n */\n trackFetchStreamPerformance: 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 * Resource spans with `op`s matching strings in the array will not be emitted.\n *\n * Default: []\n */\n ignoreResourceSpans: Array<'resouce.script' | 'resource.css' | 'resource.img' | 'resource.other' | string>;\n\n /**\n * Spans created from the following browser Performance APIs,\n *\n * - [`performance.mark(...)`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark)\n * - [`performance.measure(...)`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/measure)\n *\n * will not be emitted if their names match strings in this array.\n *\n * This is useful, if you come across `mark` or `measure` spans in your Sentry traces\n * that you want to ignore. For example, sometimes, browser extensions or libraries\n * emit these entries on their own, which might not be relevant to your application.\n *\n * * @example\n * ```ts\n * Sentry.init({\n * integrations: [\n * Sentry.browserTracingIntegration({\n * ignorePerformanceApiSpans: ['myMeasurement', /myMark/],\n * }),\n * ],\n * });\n *\n * // no spans will be created for these:\n * performance.mark('myMark');\n * performance.measure('myMeasurement');\n *\n * // spans will be created for these:\n * performance.mark('authenticated');\n * performance.measure('input-duration', ...);\n * ```\n *\n * Default: [] - By default, all `mark` and `measure` entries are sent as spans.\n */\n ignorePerformanceApiSpans: Array;\n\n /**\n * By default, the SDK will try to detect redirects and avoid creating separate spans for them.\n * If you want to opt-out of this behavior, you can set this option to `false`.\n *\n * Default: true\n */\n detectRedirects: boolean;\n\n /**\n * Link the currently started trace to a previous trace (e.g. a prior pageload, navigation or\n * manually started span). When enabled, this option will allow you to navigate between traces\n * in the Sentry UI.\n *\n * You can set this option to the following values:\n *\n * - `'in-memory'`: The previous trace data will be stored in memory.\n * This is useful for single-page applications and enabled by default.\n *\n * - `'session-storage'`: The previous trace data will be stored in the `sessionStorage`.\n * This is useful for multi-page applications or static sites but it means that the\n * Sentry SDK writes to the browser's `sessionStorage`.\n *\n * - `'off'`: The previous trace data will not be stored or linked.\n *\n * You can also use {@link BrowserTracingOptions.consistentTraceSampling} to get\n * consistent trace sampling of subsequent traces. Otherwise, by default, your\n * `tracesSampleRate` or `tracesSampler` config significantly influences how often\n * traces will be linked.\n *\n * @default 'in-memory' - see explanation above\n */\n linkPreviousTrace: 'in-memory' | 'session-storage' | 'off';\n\n /**\n * If true, Sentry will consistently sample subsequent traces based on the\n * sampling decision of the initial trace. For example, if the initial page\n * load trace was sampled positively, all subsequent traces (e.g. navigations)\n * are also sampled positively. In case the initial trace was sampled negatively,\n * all subsequent traces are also sampled negatively.\n *\n * This option allows you to get consistent, linked traces within a user journey\n * while maintaining an overall quota based on your trace sampling settings.\n *\n * This option is only effective if {@link BrowserTracingOptions.linkPreviousTrace}\n * is enabled (i.e. not set to `'off'`).\n *\n * @default `false` - this is an opt-in feature.\n */\n consistentTraceSampling: boolean;\n\n /**\n * If set to `true`, the pageload span will not end itself automatically, unless it\n * runs until the {@link BrowserTracingOptions.finalTimeout} (30 seconds by default) is reached.\n *\n * Set this option to `true`, if you want full control over the pageload span duration.\n * You can use `Sentry.reportPageLoaded()` to manually end the pageload span whenever convenient.\n * Be aware that you have to ensure that this is always called, regardless of the chosen route\n * or path in the application.\n *\n * @default `false`. By default, the pageload span will end itself automatically, based on\n * the {@link BrowserTracingOptions.finalTimeout}, {@link BrowserTracingOptions.idleTimeout}\n * and {@link BrowserTracingOptions.childSpanTimeout}. This is more convenient to use but means\n * that the pageload duration can be arbitrary and might not be fully representative of a perceived\n * page load time.\n */\n enableReportPageLoaded: boolean;\n\n /**\n * _experiments allows the user to send options to define how this integration works.\n *\n * Default: undefined\n */\n _experiments: Partial<{\n enableInteractions: boolean;\n enableStandaloneClsSpans: boolean;\n enableStandaloneLcpSpans: 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 /**\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 /**\n * This callback is invoked directly after a span is started for an outgoing fetch or XHR request.\n * You can use it to annotate the span with additional data or attributes, for example by setting\n * attributes based on the passed request headers.\n */\n onRequestSpanStart?(span: Span, requestInformation: RequestHookInfo): void;\n\n /**\n * Is called when spans end for outgoing requests, providing access to response headers.\n */\n onRequestSpanEnd?(span: Span, responseInformation: ResponseHookInfo): void;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {\n ...TRACING_DEFAULTS,\n instrumentNavigation: true,\n instrumentPageLoad: true,\n markBackgroundSpan: true,\n enableLongTask: true,\n enableLongAnimationFrame: true,\n enableInp: true,\n enableElementTiming: true,\n ignoreResourceSpans: [],\n ignorePerformanceApiSpans: [],\n detectRedirects: true,\n linkPreviousTrace: 'in-memory',\n consistentTraceSampling: false,\n enableReportPageLoaded: false,\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.\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 latestRoute: RouteInfo = {\n name: undefined,\n source: undefined,\n };\n\n /**\n * This is just a small wrapper that makes `document` optional.\n * We want to be extra-safe and always check that this exists, to ensure weird environments do not blow up.\n */\n const optionalWindowDocument = WINDOW.document as (typeof WINDOW)['document'] | undefined;\n\n const {\n enableInp,\n enableElementTiming,\n enableLongTask,\n enableLongAnimationFrame,\n _experiments: { enableInteractions, enableStandaloneClsSpans, enableStandaloneLcpSpans },\n beforeStartSpan,\n idleTimeout,\n finalTimeout,\n childSpanTimeout,\n markBackgroundSpan,\n traceFetch,\n traceXHR,\n trackFetchStreamPerformance,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n ignoreResourceSpans,\n ignorePerformanceApiSpans,\n instrumentPageLoad,\n instrumentNavigation,\n detectRedirects,\n linkPreviousTrace,\n consistentTraceSampling,\n enableReportPageLoaded,\n onRequestSpanStart,\n onRequestSpanEnd,\n } = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ...options,\n };\n\n let _collectWebVitals: undefined | (() => void);\n let lastInteractionTimestamp: number | undefined;\n\n let _pageloadSpan: Span | undefined;\n\n /** Create routing idle transaction. */\n function _createRouteSpan(client: Client, startSpanOptions: StartSpanOptions, makeActive = true): void {\n const isPageloadSpan = startSpanOptions.op === 'pageload';\n\n const initialSpanName = startSpanOptions.name;\n const finalStartSpanOptions: StartSpanOptions = beforeStartSpan\n ? beforeStartSpan(startSpanOptions)\n : startSpanOptions;\n\n const attributes = finalStartSpanOptions.attributes || {};\n\n // If `finalStartSpanOptions.name` is different than `startSpanOptions.name`\n // it is because `beforeStartSpan` set a custom name. Therefore we set the source to 'custom'.\n if (initialSpanName !== finalStartSpanOptions.name) {\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'custom';\n finalStartSpanOptions.attributes = attributes;\n }\n\n if (!makeActive) {\n // We want to ensure this has 0s duration\n const now = dateTimestampInSeconds();\n startInactiveSpan({\n ...finalStartSpanOptions,\n startTime: now,\n }).end(now);\n return;\n }\n\n latestRoute.name = finalStartSpanOptions.name;\n latestRoute.source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n\n const idleSpan = startIdleSpan(finalStartSpanOptions, {\n idleTimeout,\n finalTimeout,\n childSpanTimeout,\n // should wait for finish signal if it's a pageload transaction\n disableAutoFinish: isPageloadSpan,\n beforeSpanEnd: span => {\n // This will generally always be defined here, because it is set in `setup()` of the integration\n // but technically, it is optional, so we guard here to be extra safe\n _collectWebVitals?.();\n addPerformanceEntries(span, {\n recordClsOnPageloadSpan: !enableStandaloneClsSpans,\n recordLcpOnPageloadSpan: !enableStandaloneLcpSpans,\n ignoreResourceSpans,\n ignorePerformanceApiSpans,\n });\n setActiveIdleSpan(client, undefined);\n\n // A trace should stay consistent over the entire timespan of one route - even after the pageload/navigation ended.\n // Only when another navigation happens, we want to create a new trace.\n // This way, e.g. errors that occur after the pageload span ended are still associated to the pageload trace.\n const scope = getCurrentScope();\n const oldPropagationContext = scope.getPropagationContext();\n\n scope.setPropagationContext({\n ...oldPropagationContext,\n traceId: idleSpan.spanContext().traceId,\n sampled: spanIsSampled(idleSpan),\n dsc: getDynamicSamplingContextFromSpan(span),\n });\n\n if (isPageloadSpan) {\n // clean up the stored pageload span on the intergration.\n _pageloadSpan = undefined;\n }\n },\n trimIdleSpanEndTimestamp: !enableReportPageLoaded,\n });\n\n if (isPageloadSpan && enableReportPageLoaded) {\n _pageloadSpan = idleSpan;\n }\n\n setActiveIdleSpan(client, idleSpan);\n\n function emitFinish(): void {\n if (optionalWindowDocument && ['interactive', 'complete'].includes(optionalWindowDocument.readyState)) {\n client.emit('idleSpanEnableAutoFinish', idleSpan);\n }\n }\n\n // Enable auto finish of the pageload span if users are not explicitly ending it\n if (isPageloadSpan && !enableReportPageLoaded && optionalWindowDocument) {\n optionalWindowDocument.addEventListener('readystatechange', () => {\n emitFinish();\n });\n\n emitFinish();\n }\n }\n\n return {\n name: BROWSER_TRACING_INTEGRATION_ID,\n setup(client) {\n registerSpanErrorInstrumentation();\n\n _collectWebVitals = startTrackingWebVitals({\n recordClsStandaloneSpans: enableStandaloneClsSpans || false,\n recordLcpStandaloneSpans: enableStandaloneLcpSpans || false,\n client,\n });\n\n if (enableInp) {\n startTrackingINP();\n }\n\n if (enableElementTiming) {\n startTrackingElementTiming();\n }\n\n if (\n enableLongAnimationFrame &&\n GLOBAL_OBJ.PerformanceObserver &&\n PerformanceObserver.supportedEntryTypes &&\n PerformanceObserver.supportedEntryTypes.includes('long-animation-frame')\n ) {\n startTrackingLongAnimationFrames();\n } else if (enableLongTask) {\n startTrackingLongTasks();\n }\n\n if (enableInteractions) {\n startTrackingInteractions();\n }\n\n if (detectRedirects && optionalWindowDocument) {\n const interactionHandler = (): void => {\n lastInteractionTimestamp = timestampInSeconds();\n };\n addEventListener('click', interactionHandler, { capture: true });\n addEventListener('keydown', interactionHandler, { capture: true, passive: true });\n }\n\n function maybeEndActiveSpan(): void {\n const activeSpan = getActiveIdleSpan(client);\n\n if (activeSpan && !spanToJSON(activeSpan).timestamp) {\n DEBUG_BUILD && debug.log(`[Tracing] Finishing current active span with op: ${spanToJSON(activeSpan).op}`);\n // If there's an open active span, we need to finish it before creating an new one.\n activeSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, 'cancelled');\n activeSpan.end();\n }\n }\n\n client.on('startNavigationSpan', (startSpanOptions, navigationOptions) => {\n if (getClient() !== client) {\n return;\n }\n\n if (navigationOptions?.isRedirect) {\n DEBUG_BUILD &&\n debug.warn('[Tracing] Detected redirect, navigation span will not be the root span, but a child span.');\n _createRouteSpan(\n client,\n {\n op: 'navigation.redirect',\n ...startSpanOptions,\n },\n false,\n );\n return;\n }\n\n // Reset the last interaction timestamp since we now start a new navigation.\n // Any subsequent navigation span starts could again be a redirect, so we\n // should reset our heuristic detectors.\n lastInteractionTimestamp = undefined;\n\n maybeEndActiveSpan();\n\n getIsolationScope().setPropagationContext({\n traceId: generateTraceId(),\n sampleRand: Math.random(),\n propagationSpanId: hasSpansEnabled() ? undefined : generateSpanId(),\n });\n\n const scope = getCurrentScope();\n scope.setPropagationContext({\n traceId: generateTraceId(),\n sampleRand: Math.random(),\n propagationSpanId: hasSpansEnabled() ? undefined : generateSpanId(),\n });\n\n // We reset this to ensure we do not have lingering incorrect data here\n // places that call this hook may set this where appropriate - else, the URL at span sending time is used\n scope.setSDKProcessingMetadata({\n normalizedRequest: undefined,\n });\n\n _createRouteSpan(client, {\n op: 'navigation',\n ...startSpanOptions,\n // Navigation starts a new trace and is NOT parented under any active interaction (e.g. ui.action.click)\n parentSpan: null,\n forceTransaction: true,\n });\n });\n\n client.on('startPageLoadSpan', (startSpanOptions, traceOptions = {}) => {\n if (getClient() !== client) {\n return;\n }\n maybeEndActiveSpan();\n\n const sentryTrace = traceOptions.sentryTrace || getMetaContent('sentry-trace');\n const baggage = traceOptions.baggage || getMetaContent('baggage');\n\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n\n const scope = getCurrentScope();\n scope.setPropagationContext(propagationContext);\n if (!hasSpansEnabled()) {\n // for browser, we wanna keep the spanIds consistent during the entire lifetime of the trace\n // this works by setting the propagationSpanId to a random spanId so that we have a consistent\n // span id to propagate in TwP mode (!hasSpansEnabled())\n scope.getPropagationContext().propagationSpanId = generateSpanId();\n }\n\n // We store the normalized request data on the scope, so we get the request data at time of span creation\n // otherwise, the URL etc. may already be of the following navigation, and we'd report the wrong URL\n scope.setSDKProcessingMetadata({\n normalizedRequest: getHttpRequestData(),\n });\n\n _createRouteSpan(client, {\n op: 'pageload',\n ...startSpanOptions,\n });\n });\n\n client.on('endPageloadSpan', () => {\n if (enableReportPageLoaded && _pageloadSpan) {\n _pageloadSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, 'reportPageLoaded');\n _pageloadSpan.end();\n }\n });\n },\n\n afterAllSetup(client) {\n let startingUrl: string | undefined = getLocationHref();\n\n if (linkPreviousTrace !== 'off') {\n linkTraces(client, { linkPreviousTrace, consistentTraceSampling });\n }\n\n if (WINDOW.location) {\n if (instrumentPageLoad) {\n const origin = browserPerformanceTimeOrigin();\n startBrowserTracingPageLoadSpan(client, {\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTime: origin ? origin / 1000 : undefined,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.pageload.browser',\n },\n });\n }\n\n if (instrumentNavigation) {\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?.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n startingUrl = undefined;\n const parsed = parseStringToURLObject(to);\n const activeSpan = getActiveIdleSpan(client);\n const navigationIsRedirect =\n activeSpan && detectRedirects && isRedirect(activeSpan, lastInteractionTimestamp);\n\n startBrowserTracingNavigationSpan(\n client,\n {\n name: parsed?.pathname || WINDOW.location.pathname,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.navigation.browser',\n },\n },\n { url: to, isRedirect: navigationIsRedirect },\n );\n });\n }\n }\n\n if (markBackgroundSpan) {\n registerBackgroundTabDetection();\n }\n\n if (enableInteractions) {\n registerInteractionListener(client, idleTimeout, finalTimeout, childSpanTimeout, latestRoute);\n }\n\n if (enableInp) {\n registerInpInteractionListener();\n }\n\n instrumentOutgoingRequests(client, {\n traceFetch,\n traceXHR,\n trackFetchStreamPerformance,\n tracePropagationTargets: client.getOptions().tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n onRequestSpanStart,\n onRequestSpanEnd,\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Manually start a page load span.\n * This will only do something if a browser tracing integration integration has been setup.\n *\n * If you provide a custom `traceOptions` object, it will be used to continue the trace\n * instead of the default behavior, which is to look it up on the tags.\n */\nexport function startBrowserTracingPageLoadSpan(\n client: Client,\n spanOptions: StartSpanOptions,\n traceOptions?: { sentryTrace?: string | undefined; baggage?: string | undefined },\n): Span | undefined {\n client.emit('startPageLoadSpan', spanOptions, traceOptions);\n getCurrentScope().setTransactionName(spanOptions.name);\n\n const pageloadSpan = getActiveIdleSpan(client);\n\n if (pageloadSpan) {\n client.emit('afterStartPageLoadSpan', pageloadSpan);\n }\n\n return pageloadSpan;\n}\n\n/**\n * Manually start a navigation span.\n * This will only do something if a browser tracing integration has been setup.\n */\nexport function startBrowserTracingNavigationSpan(\n client: Client,\n spanOptions: StartSpanOptions,\n options?: { url?: string; isRedirect?: boolean },\n): Span | undefined {\n const { url, isRedirect } = options || {};\n client.emit('beforeStartNavigationSpan', spanOptions, { isRedirect });\n client.emit('startNavigationSpan', spanOptions, { isRedirect });\n\n const scope = getCurrentScope();\n scope.setTransactionName(spanOptions.name);\n\n // We store the normalized request data on the scope, so we get the request data at time of span creation\n // otherwise, the URL etc. may already be of the following navigation, and we'd report the wrong URL\n if (url && !isRedirect) {\n scope.setSDKProcessingMetadata({\n normalizedRequest: {\n ...getHttpRequestData(),\n url,\n },\n });\n }\n\n return getActiveIdleSpan(client);\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | undefined {\n /**\n * This is just a small wrapper that makes `document` optional.\n * We want to be extra-safe and always check that this exists, to ensure weird environments do not blow up.\n */\n const optionalWindowDocument = WINDOW.document as (typeof WINDOW)['document'] | undefined;\n\n const metaTag = optionalWindowDocument?.querySelector(`meta[name=${metaName}]`);\n return metaTag?.getAttribute('content') || undefined;\n}\n\n/** Start listener for interaction transactions */\nfunction registerInteractionListener(\n client: Client,\n idleTimeout: BrowserTracingOptions['idleTimeout'],\n finalTimeout: BrowserTracingOptions['finalTimeout'],\n childSpanTimeout: BrowserTracingOptions['childSpanTimeout'],\n latestRoute: RouteInfo,\n): void {\n /**\n * This is just a small wrapper that makes `document` optional.\n * We want to be extra-safe and always check that this exists, to ensure weird environments do not blow up.\n */\n const optionalWindowDocument = WINDOW.document as (typeof WINDOW)['document'] | undefined;\n\n let inflightInteractionSpan: Span | undefined;\n const registerInteractionTransaction = (): void => {\n const op = 'ui.action.click';\n\n const activeIdleSpan = getActiveIdleSpan(client);\n if (activeIdleSpan) {\n const currentRootSpanOp = spanToJSON(activeIdleSpan).op;\n if (['navigation', 'pageload'].includes(currentRootSpanOp as string)) {\n DEBUG_BUILD &&\n debug.warn(`[Tracing] Did not create ${op} span because a pageload or navigation span is in progress.`);\n return undefined;\n }\n }\n\n if (inflightInteractionSpan) {\n inflightInteractionSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, 'interactionInterrupted');\n inflightInteractionSpan.end();\n inflightInteractionSpan = undefined;\n }\n\n if (!latestRoute.name) {\n DEBUG_BUILD && debug.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n inflightInteractionSpan = startIdleSpan(\n {\n name: latestRoute.name,\n op,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: latestRoute.source || 'url',\n },\n },\n {\n idleTimeout,\n finalTimeout,\n childSpanTimeout,\n },\n );\n };\n\n if (optionalWindowDocument) {\n addEventListener('click', registerInteractionTransaction, { capture: true });\n }\n}\n\n// We store the active idle span on the client object, so we can access it from exported functions\nconst ACTIVE_IDLE_SPAN_PROPERTY = '_sentry_idleSpan';\nfunction getActiveIdleSpan(client: Client): Span | undefined {\n return (client as { [ACTIVE_IDLE_SPAN_PROPERTY]?: Span })[ACTIVE_IDLE_SPAN_PROPERTY];\n}\n\nfunction setActiveIdleSpan(client: Client, span: Span | undefined): void {\n addNonEnumerableProperty(client, ACTIVE_IDLE_SPAN_PROPERTY, span);\n}\n\n// The max. time in seconds between two pageload/navigation spans that makes us consider the second one a redirect\nconst REDIRECT_THRESHOLD = 1.5;\n\nfunction isRedirect(activeSpan: Span, lastInteractionTimestamp: number | undefined): boolean {\n const spanData = spanToJSON(activeSpan);\n\n const now = dateTimestampInSeconds();\n\n // More than REDIRECT_THRESHOLD seconds since last navigation/pageload span?\n // --> never consider this a redirect\n const startTimestamp = spanData.start_timestamp;\n if (now - startTimestamp > REDIRECT_THRESHOLD) {\n return false;\n }\n\n // A click happened in the last REDIRECT_THRESHOLD seconds?\n // --> never consider this a redirect\n if (lastInteractionTimestamp && now - lastInteractionTimestamp <= REDIRECT_THRESHOLD) {\n return false;\n }\n\n return true;\n}\n", "import * as Sentry from \"@sentry/browser\";\n\nconst config = window.params.sentry;\n\n// According to the sentry docs, there is still some overhead even\n// when enabled is set to false, so we skip init entirely instead \u2014 an\n// init'd-but-disabled SDK still wraps window.onerror and installs the\n// tracing and replay integrations.\n// https://docs.sentry.io/platforms/javascript/configuration/options/#enabled\nif (window.params.environment !== \"test\" && config.enabled) {\n Sentry.init({\n dsn: config.dsn,\n serverName: config.server_name,\n integrations: [\n Sentry.browserTracingIntegration(),\n Sentry.replayIntegration(),\n ],\n // Tracing (keep this 0 otherwise we get insane Sentry bills)\n tracesSampleRate: 0,\n // Set 'tracePropagationTargets' to control for which URLs distributed tracing should be enabled\n tracePropagationTargets: [/^https:\\/\\/autoraptor\\.com/],\n // Session Replay (keep this 0 otherwise we get insane Sentry bills)\n replaysSessionSampleRate: 0,\n replaysOnErrorSampleRate: 0,\n environment: config.environment,\n // Drop benign noise: fetch aborts and WebKit's \"Load failed\" / \"I/O read\n // operation failed\" happen when the user navigates away or the connection\n // drops mid-request. Not actionable.\n ignoreErrors: [\n \"AbortError\",\n \"The operation was aborted.\",\n \"Load failed\",\n \"Failed to fetch\",\n \"The I/O read operation failed.\",\n \"NetworkError when attempting to fetch resource.\",\n \"UnknownError: An internal error was encountered in the Indexed Database server\",\n ],\n // Drop errors thrown from third-party scripts we can't fix (e.g. HubSpot\n // tracking's hstc.autotrack throwing \"e.includes is not a function\").\n denyUrls: [\n /js\\.hs-analytics\\.net/,\n /js\\.hubspot\\.com/,\n /js\\.hs-scripts\\.com/,\n ],\n beforeSend(event, hint) {\n const error = hint && hint.originalException;\n const message = (error && error.message) || (event.message || \"\");\n\n // Unify grouping for variants of \"window.amplitude is undefined\" so\n // ad-blocker-caused errors don't fragment across 7+ issues.\n if (\n /amplitude/i.test(message) ||\n /reading ['\"]add['\"]/.test(message) ||\n /window\\.amplitude\\.add/.test(message)\n ) {\n event.fingerprint = [\"amplitude-undefined\"];\n }\n\n return event;\n },\n });\n}\n", "import * as Sentry from \"@sentry/browser\";\n\n/**\n * ErrorNotifier is a simple wrapper that forwards errors along with extra\n * context to Sentry. Use it like so:\n *\n * ErrorNotifier.notify({\n * error: error.error_message,\n * context: {\n * display_message: error.display_message,\n * error_code: error.error_code,\n * error_type: error.error_type,\n * },\n * });\n */\nconst ErrorNotifier = {\n notify({ error, context }) {\n // Create a new Error instance using the provided error message.\n const err = new Error(error);\n\n if (window.params.environment === \"test\" || !window.params.sentry.enabled) {\n console.log(`(${window.params.environment}) Error: `, error, context);\n return;\n }\n\n // Use Sentry.withScope to attach additional context to this event.\n Sentry.withScope((scope) => {\n // Add all provided context as extra data.\n scope.setExtras(context);\n\n // Optionally, set specific tags for more fine-grained filtering.\n if (context.error_code) {\n scope.setTag(\"error_code\", context.error_code);\n }\n if (context.error_type) {\n scope.setTag(\"error_type\", context.error_type);\n }\n if (context.display_message) {\n scope.setExtra(\"display_message\", context.display_message);\n }\n\n // Capture the exception with Sentry.\n Sentry.captureException(err);\n });\n },\n};\n\nexport default ErrorNotifier;\n", "if (!Array.prototype.first) {\n Array.prototype.first = function() {\n return this[0];\n };\n}\n", "const transparent = s => s === \"rgba(0, 0, 0, 0)\";\n\njQuery.fn.highlight = function () {\n let altered_color;\n const original_color = this.css(\"backgroundColor\");\n if (transparent(this.css(\"backgroundColor\"))) {\n let item = this;\n while ((item = item.parent())) {\n if (!transparent(item.css(\"backgroundColor\"))) {\n this.css({ backgroundColor: item.css(\"backgroundColor\") });\n altered_color = true;\n break;\n }\n }\n }\n // pick a bogus property (i) to animate\n return $({ i: 1 }).animate({ i: 0 }, {\n duration: 2500,\n step: (now, fx) => {\n return this.css({ background: `rgba(255,255,153, ${now})` });\n },\n\n complete: () => {\n if (altered_color) { return this.css({ backgroundColor: original_color }); }\n },\n },\n );\n};\n", "window.UI.Spinners = class Spinners {\n static id (o) {\n return \"#\" + o + \"_spinner\";\n }\n\n static show (o) {\n return $(this.id(o)).show();\n }\n\n static hide (o) {\n return $(this.id(o)).hide();\n }\n};\n\n// user for a delayed spinner (so far AJAX always shows a spinner for a bit)\nwindow.UI.Spinner = class Spinner {\n constructor (img) {\n this.img = img;\n this.start = new Date();\n this.delay = 500;\n this.img.show();\n }\n\n for (d) {\n this.delay = d;\n }\n\n hide () {\n const now = new Date();\n if ((now - this.start) > this.delay) {\n return this.img.hide();\n } else {\n const duration = this.delay - (now - this.start);\n return setTimeout(() => this.hide(), duration);\n }\n }\n};\n", "export function fullyVisible(element) {\n if (element === null || element === undefined) return;\n const { top, left, bottom, right } = element.getBoundingClientRect();\n const { innerHeight, innerWidth } = window;\n return (top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth);\n}\n", "export function trackEvent(eventData, element) {\n if (typeof gtag === \"function\") {\n const {\n account_id,\n dealership_id,\n upsheet_id,\n parameter1,\n parameter2,\n category,\n action,\n label,\n value,\n } = eventData;\n\n const elementData = element\n ? {\n account_id: element.closest(\"[data-ga-account-id]\")?.dataset.gaAccountId,\n dealership_id: element.closest(\"[data-ga-dealership-id]\")?.dataset.gaDealershipId,\n upsheet_id: element.closest(\"[data-ga-upsheet-id]\")?.dataset.gaUpsheetId,\n parameter1: element.closest(\"[data-ga-parameter1]\")?.dataset.gaParameter1,\n parameter2: element.closest(\"[data-ga-parameter2]\")?.dataset.gaParameter2,\n category: element.closest(\"[data-ga-category]\")?.dataset.gaCategory,\n action: element.closest(\"[data-ga-action]\")?.dataset.gaAction,\n label: element.closest(\"[data-ga-label]\")?.dataset.gaLabel,\n value: element.closest(\"[data-ga-value]\")?.dataset.gaValue,\n }\n : {};\n\n const platform = (window.AR_TRACK_CONTEXT && window.AR_TRACK_CONTEXT.platform) || undefined;\n const pwa_installed = (window.AR_TRACK_CONTEXT && window.AR_TRACK_CONTEXT.isStandalone) || false;\n\n gtag(\"event\", action || elementData.action, {\n event_account_id: account_id || elementData.account_id,\n event_dealership_id: dealership_id || elementData.dealership_id,\n event_upsheet_id: upsheet_id || elementData.upsheet_id,\n event_parameter1: parameter1 || elementData.parameter1,\n event_parameter2: parameter2 || elementData.parameter2,\n event_category: category || elementData.category,\n event_label: label || elementData.label,\n event_value: value || elementData.value,\n pwa_platform: platform,\n pwa_installed,\n });\n }\n\n if (window.amplitude && typeof window.amplitude.track === \"function\") {\n const { action, category, label, value } = eventData;\n const platform = (window.AR_TRACK_CONTEXT && window.AR_TRACK_CONTEXT.platform) || undefined;\n const pwa_installed = (window.AR_TRACK_CONTEXT && window.AR_TRACK_CONTEXT.isStandalone) || false;\n\n const eventName = action || \"custom_event\";\n const eventProps = {\n category,\n label,\n value,\n pwa_platform: platform,\n pwa_installed,\n };\n\n try {\n window.amplitude.track(eventName, eventProps);\n } catch (e) {\n // no-op\n }\n }\n}\n", "import type { PostHog } from '../posthog-core'\nimport { SessionIdManager } from '../sessionid'\nimport {\n DeadClicksAutoCaptureConfig,\n ExternalIntegrationKind,\n Properties,\n RemoteConfig,\n SiteAppLoader,\n SessionStartReason,\n} from '../types'\nimport type {\n ConversationsRemoteConfig,\n GetMessagesResponse,\n GetTicketsOptions,\n GetTicketsResponse,\n MarkAsReadResponse,\n RestoreFromTokenResponse,\n RequestRestoreLinkResponse,\n SendMessageResponse,\n UserProvidedTraits,\n} from '../posthog-conversations-types'\n// only importing types here, so won't affect the bundle\n// eslint-disable-next-line posthog-js/no-external-replay-imports\nimport type { SessionRecordingStatus, TriggerType } from '../extensions/replay/external/triggerMatching'\nimport { eventWithTime } from '../extensions/replay/types/rrweb-types'\nimport { ErrorTracking } from '@posthog/core'\n\n/*\n * Global helpers to protect access to browser globals in a way that is safer for different targets\n * like DOM, SSR, Web workers etc.\n *\n * NOTE: Typically we want the \"window\" but globalThis works for both the typical browser context as\n * well as other contexts such as the web worker context. Window is still exported for any bits that explicitly require it.\n * If in doubt - export the global you need from this file and use that as an optional value. This way the code path is forced\n * to handle the case where the global is not available.\n */\n\n// eslint-disable-next-line no-restricted-globals\nconst win: (Window & typeof globalThis) | undefined = typeof window !== 'undefined' ? window : undefined\n\nexport type AssignableWindow = Window &\n typeof globalThis & {\n /*\n * Main PostHog instance\n */\n posthog: any\n\n /*\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n */\n __PosthogExtensions__?: PostHogExtensions\n\n /**\n * When loading remote config, we assign it to this global configuration\n * for ease of sharing it with the rest of the SDK\n */\n _POSTHOG_REMOTE_CONFIG?: Record<\n string,\n {\n config: RemoteConfig\n siteApps: SiteAppLoader[]\n }\n >\n\n /**\n * If this is set on the window, our logger will log to the console\n * for ease of debugging. Used for testing purposes only.\n *\n * @see {Config.DEBUG} from config.ts\n */\n POSTHOG_DEBUG: any\n\n // Exposed by the browser\n doNotTrack: any\n\n // See entrypoints/customizations.full.ts\n posthogCustomizations: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/exception-autocapture.ts\n *\n * @deprecated use `__PosthogExtensions__.errorWrappingFunctions` instead\n */\n posthogErrorWrappingFunctions: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.rrweb` instead\n */\n rrweb: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.rrwebConsoleRecord` instead\n */\n rrwebConsoleRecord: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.getRecordNetworkPlugin` instead\n */\n getRecordNetworkPlugin: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/web-vitals.ts\n *\n * @deprecated use `__PosthogExtensions__.postHogWebVitalsCallbacks` instead\n */\n postHogWebVitalsCallbacks: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/tracing-headers.ts\n *\n * @deprecated use `__PosthogExtensions__.postHogTracingHeadersPatchFns` instead\n */\n postHogTracingHeadersPatchFns: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/surveys.ts\n *\n * @deprecated use `__PosthogExtensions__.generateSurveys` instead\n */\n extendPostHogWithSurveys: any\n\n /*\n * These are used to handle our toolbar state.\n * @see {Toolbar} from extensions/toolbar.ts\n */\n ph_load_toolbar: any\n ph_load_editor: any\n ph_toolbar_state: any\n } & Record<`__$$ph_site_app_${string}`, any>\n\n/**\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n * changes to this interface can be breaking changes for users of the SDK\n */\n\nexport type ExternalExtensionKind = 'intercom-integration' | 'crisp-chat-integration'\n\nexport type PostHogExtensionKind =\n | 'toolbar'\n | 'exception-autocapture'\n | 'web-vitals'\n | 'web-vitals-with-attribution'\n | 'recorder'\n | 'lazy-recorder'\n | 'tracing-headers'\n | 'surveys'\n | 'logs'\n | 'conversations'\n | 'product-tours'\n | 'dead-clicks-autocapture'\n | 'remote-config'\n | ExternalExtensionKind\n\nexport interface LazyLoadedSessionRecordingInterface {\n start: (startReason?: SessionStartReason) => void\n stop: () => void\n discard: () => void\n sessionId: string\n status: SessionRecordingStatus\n onRRwebEmit: (rawEvent: eventWithTime) => void\n log: (message: string, level: 'log' | 'warn' | 'error') => void\n sdkDebugProperties: Properties\n overrideLinkedFlag: () => void\n overrideSampling: () => void\n overrideTrigger: (triggerType: TriggerType) => void\n isStarted: boolean\n tryAddCustomEvent(tag: string, payload: any): boolean\n}\n\nexport interface LazyLoadedDeadClicksAutocaptureInterface {\n start: (observerTarget: Node) => void\n stop: () => void\n}\n\nexport interface LazyLoadedConversationsInterface {\n // Widget control\n show: () => void\n hide: () => void\n isVisible: () => boolean\n\n // Lifecycle\n reset: () => void\n\n // Identity verification\n setIdentity: () => void\n clearIdentity: () => void\n\n // API methods\n sendMessage: (message: string, userTraits?: UserProvidedTraits, newTicket?: boolean) => Promise\n getMessages: (ticketId?: string, after?: string) => Promise\n markAsRead: (ticketId?: string) => Promise\n getTickets: (options?: GetTicketsOptions) => Promise\n requestRestoreLink: (email: string) => Promise\n restoreFromToken: (restoreToken: string) => Promise\n restoreFromUrlToken: () => Promise\n getCurrentTicketId: () => string | null\n getWidgetSessionId: () => string\n}\n\ninterface PostHogExtensions {\n loadExternalDependency?: (\n posthog: PostHog,\n kind: PostHogExtensionKind,\n callback: (error?: string | Event, event?: Event) => void\n ) => void\n\n loadSiteApp?: (posthog: PostHog, appUrl: string, callback: (error?: string | Event, event?: Event) => void) => void\n\n errorWrappingFunctions?: {\n wrapOnError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n wrapUnhandledRejection: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n wrapConsoleError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n }\n rrweb?: { record: any; version: string; wasMaxDepthReached?: () => boolean; resetMaxDepthState?: () => void }\n rrwebPlugins?: { getRecordConsolePlugin: any; getRecordNetworkPlugin?: any }\n generateSurveys?: (posthog: PostHog, isSurveysEnabled: boolean) => any | undefined\n generateProductTours?: (posthog: PostHog, isEnabled: boolean) => any | undefined\n logs?: {\n initializeLogs?: (posthog: PostHog) => any | undefined\n }\n postHogWebVitalsCallbacks?: {\n onLCP: (metric: any) => void\n onCLS: (metric: any) => void\n onFCP: (metric: any) => void\n onINP: (metric: any) => void\n }\n /**\n * @deprecated\n *\n * this was introduced briefly, it is now always a no-op and only kept for backwards compatibility\n */\n loadWebVitalsCallbacks?: (useAttribution?: boolean) => PostHogExtensions['postHogWebVitalsCallbacks']\n tracingHeadersPatchFns?: {\n _patchFetch: (hostnames: string[], distinctId: string, sessionManager?: SessionIdManager) => () => void\n _patchXHR: (hostnames: string[], distinctId: string, sessionManager?: SessionIdManager) => () => void\n }\n initDeadClicksAutocapture?: (\n ph: PostHog,\n config: DeadClicksAutoCaptureConfig\n ) => LazyLoadedDeadClicksAutocaptureInterface\n integrations?: {\n [K in ExternalIntegrationKind]?: { start: (posthog: PostHog) => void; stop: () => void }\n }\n initSessionRecording?: (ph: PostHog) => LazyLoadedSessionRecordingInterface\n initConversations?: (config: ConversationsRemoteConfig, posthog: PostHog) => LazyLoadedConversationsInterface\n}\n\nconst global: typeof globalThis | undefined = typeof globalThis !== 'undefined' ? globalThis : win\n\n// React Native polyfills for posthog-js compatibility\nif (typeof self === 'undefined') {\n ;(global as any).self = global\n}\nif (typeof File === 'undefined') {\n ;(global as any).File = function () {}\n}\n\nexport const navigator = global?.navigator\nexport const document = global?.document\nexport const location = global?.location\nexport const fetch = global?.fetch\nexport const XMLHttpRequest =\n global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined\nexport const AbortController = global?.AbortController\nexport const CompressionStream = global?.CompressionStream\nexport const userAgent = navigator?.userAgent\nexport const assignableWindow: AssignableWindow = win ?? ({} as any)\n\nexport { win as window }\n", "import packageInfo from '../package.json'\n\n// overridden in posthog-core,\n// e.g. Config.DEBUG = Config.DEBUG || instance.config.debug\nconst Config = {\n DEBUG: false,\n LIB_VERSION: packageInfo.version,\n LIB_NAME: 'web',\n /** The actual JS SDK version, unaffected by _overrideSDKInfo. Used for the `ver` request param. */\n JS_SDK_VERSION: packageInfo.version,\n}\n\nexport default Config\n", "function isGzipSupported() {\n return 'CompressionStream' in globalThis;\n}\nconst isNativeAsyncGzipReadError = (error)=>{\n if (!error || 'object' != typeof error) return false;\n const name = 'name' in error ? String(error.name) : '';\n return 'NotReadableError' === name;\n};\nasync function gzipCompress(input, isDebug = true, options) {\n try {\n const dataStream = new Blob([\n input\n ], {\n type: 'text/plain'\n }).stream();\n const compressedStream = dataStream.pipeThrough(new CompressionStream('gzip'));\n return await new Response(compressedStream).blob();\n } catch (error) {\n if (options?.rethrow) throw error;\n if (isDebug) console.error('Failed to gzip compress data', error);\n return null;\n }\n}\nexport { gzipCompress, isGzipSupported, isNativeAsyncGzipReadError };\n", "var types_PostHogPersistedProperty = /*#__PURE__*/ function(PostHogPersistedProperty) {\n PostHogPersistedProperty[\"AnonymousId\"] = \"anonymous_id\";\n PostHogPersistedProperty[\"DistinctId\"] = \"distinct_id\";\n PostHogPersistedProperty[\"Props\"] = \"props\";\n PostHogPersistedProperty[\"EnablePersonProcessing\"] = \"enable_person_processing\";\n PostHogPersistedProperty[\"PersonMode\"] = \"person_mode\";\n PostHogPersistedProperty[\"FeatureFlagDetails\"] = \"feature_flag_details\";\n PostHogPersistedProperty[\"FeatureFlags\"] = \"feature_flags\";\n PostHogPersistedProperty[\"FeatureFlagPayloads\"] = \"feature_flag_payloads\";\n PostHogPersistedProperty[\"BootstrapFeatureFlagDetails\"] = \"bootstrap_feature_flag_details\";\n PostHogPersistedProperty[\"BootstrapFeatureFlags\"] = \"bootstrap_feature_flags\";\n PostHogPersistedProperty[\"BootstrapFeatureFlagPayloads\"] = \"bootstrap_feature_flag_payloads\";\n PostHogPersistedProperty[\"OverrideFeatureFlags\"] = \"override_feature_flags\";\n PostHogPersistedProperty[\"Queue\"] = \"queue\";\n PostHogPersistedProperty[\"OptedOut\"] = \"opted_out\";\n PostHogPersistedProperty[\"SessionId\"] = \"session_id\";\n PostHogPersistedProperty[\"SessionStartTimestamp\"] = \"session_start_timestamp\";\n PostHogPersistedProperty[\"SessionLastTimestamp\"] = \"session_timestamp\";\n PostHogPersistedProperty[\"PersonProperties\"] = \"person_properties\";\n PostHogPersistedProperty[\"GroupProperties\"] = \"group_properties\";\n PostHogPersistedProperty[\"InstalledAppBuild\"] = \"installed_app_build\";\n PostHogPersistedProperty[\"InstalledAppVersion\"] = \"installed_app_version\";\n PostHogPersistedProperty[\"SessionReplay\"] = \"session_replay\";\n PostHogPersistedProperty[\"SurveyLastSeenDate\"] = \"survey_last_seen_date\";\n PostHogPersistedProperty[\"SurveysSeen\"] = \"surveys_seen\";\n PostHogPersistedProperty[\"Surveys\"] = \"surveys\";\n PostHogPersistedProperty[\"RemoteConfig\"] = \"remote_config\";\n PostHogPersistedProperty[\"FlagsEndpointWasHit\"] = \"flags_endpoint_was_hit\";\n PostHogPersistedProperty[\"DeviceId\"] = \"device_id\";\n return PostHogPersistedProperty;\n}({});\nvar types_Compression = /*#__PURE__*/ function(Compression) {\n Compression[\"GZipJS\"] = \"gzip-js\";\n Compression[\"Base64\"] = \"base64\";\n return Compression;\n}({});\nconst FeatureFlagError = {\n ERRORS_WHILE_COMPUTING: 'errors_while_computing_flags',\n FLAG_MISSING: 'flag_missing',\n QUOTA_LIMITED: 'quota_limited',\n TIMEOUT: 'timeout',\n CONNECTION_ERROR: 'connection_error',\n UNKNOWN_ERROR: 'unknown_error',\n apiError: (status)=>`api_error_${status}`\n};\nvar types_SurveyPosition = /*#__PURE__*/ function(SurveyPosition) {\n SurveyPosition[\"TopLeft\"] = \"top_left\";\n SurveyPosition[\"TopCenter\"] = \"top_center\";\n SurveyPosition[\"TopRight\"] = \"top_right\";\n SurveyPosition[\"MiddleLeft\"] = \"middle_left\";\n SurveyPosition[\"MiddleCenter\"] = \"middle_center\";\n SurveyPosition[\"MiddleRight\"] = \"middle_right\";\n SurveyPosition[\"Left\"] = \"left\";\n SurveyPosition[\"Right\"] = \"right\";\n SurveyPosition[\"Center\"] = \"center\";\n return SurveyPosition;\n}({});\nvar types_SurveyWidgetType = /*#__PURE__*/ function(SurveyWidgetType) {\n SurveyWidgetType[\"Button\"] = \"button\";\n SurveyWidgetType[\"Tab\"] = \"tab\";\n SurveyWidgetType[\"Selector\"] = \"selector\";\n return SurveyWidgetType;\n}({});\nvar types_SurveyType = /*#__PURE__*/ function(SurveyType) {\n SurveyType[\"Popover\"] = \"popover\";\n SurveyType[\"API\"] = \"api\";\n SurveyType[\"Widget\"] = \"widget\";\n SurveyType[\"ExternalSurvey\"] = \"external_survey\";\n return SurveyType;\n}({});\nvar types_SurveyQuestionDescriptionContentType = /*#__PURE__*/ function(SurveyQuestionDescriptionContentType) {\n SurveyQuestionDescriptionContentType[\"Html\"] = \"html\";\n SurveyQuestionDescriptionContentType[\"Text\"] = \"text\";\n return SurveyQuestionDescriptionContentType;\n}({});\nvar types_SurveyValidationType = /*#__PURE__*/ function(SurveyValidationType) {\n SurveyValidationType[\"MinLength\"] = \"min_length\";\n SurveyValidationType[\"MaxLength\"] = \"max_length\";\n return SurveyValidationType;\n}({});\nvar types_SurveyRatingDisplay = /*#__PURE__*/ function(SurveyRatingDisplay) {\n SurveyRatingDisplay[\"Number\"] = \"number\";\n SurveyRatingDisplay[\"Emoji\"] = \"emoji\";\n return SurveyRatingDisplay;\n}({});\nvar types_SurveyQuestionType = /*#__PURE__*/ function(SurveyQuestionType) {\n SurveyQuestionType[\"Open\"] = \"open\";\n SurveyQuestionType[\"MultipleChoice\"] = \"multiple_choice\";\n SurveyQuestionType[\"SingleChoice\"] = \"single_choice\";\n SurveyQuestionType[\"Rating\"] = \"rating\";\n SurveyQuestionType[\"Link\"] = \"link\";\n return SurveyQuestionType;\n}({});\nvar types_SurveyQuestionBranchingType = /*#__PURE__*/ function(SurveyQuestionBranchingType) {\n SurveyQuestionBranchingType[\"NextQuestion\"] = \"next_question\";\n SurveyQuestionBranchingType[\"End\"] = \"end\";\n SurveyQuestionBranchingType[\"ResponseBased\"] = \"response_based\";\n SurveyQuestionBranchingType[\"SpecificQuestion\"] = \"specific_question\";\n return SurveyQuestionBranchingType;\n}({});\nvar types_SurveyMatchType = /*#__PURE__*/ function(SurveyMatchType) {\n SurveyMatchType[\"Regex\"] = \"regex\";\n SurveyMatchType[\"NotRegex\"] = \"not_regex\";\n SurveyMatchType[\"Exact\"] = \"exact\";\n SurveyMatchType[\"IsNot\"] = \"is_not\";\n SurveyMatchType[\"Icontains\"] = \"icontains\";\n SurveyMatchType[\"NotIcontains\"] = \"not_icontains\";\n return SurveyMatchType;\n}({});\nvar types_SurveySchedule = /*#__PURE__*/ function(SurveySchedule) {\n SurveySchedule[\"Once\"] = \"once\";\n SurveySchedule[\"Recurring\"] = \"recurring\";\n SurveySchedule[\"Always\"] = \"always\";\n return SurveySchedule;\n}({});\nvar types_ActionStepStringMatching = /*#__PURE__*/ function(ActionStepStringMatching) {\n ActionStepStringMatching[\"Contains\"] = \"contains\";\n ActionStepStringMatching[\"Exact\"] = \"exact\";\n ActionStepStringMatching[\"Regex\"] = \"regex\";\n return ActionStepStringMatching;\n}({});\nconst knownUnsafeEditableEvent = [\n '$snapshot',\n '$pageview',\n '$pageleave',\n '$set',\n 'survey dismissed',\n 'survey sent',\n 'survey shown',\n '$identify',\n '$groupidentify',\n '$create_alias',\n '$$client_ingestion_warning',\n '$web_experiment_applied',\n '$feature_enrollment_update',\n '$feature_flag_called'\n];\nexport { types_ActionStepStringMatching as ActionStepStringMatching, types_Compression as Compression, FeatureFlagError, types_PostHogPersistedProperty as PostHogPersistedProperty, types_SurveyMatchType as SurveyMatchType, types_SurveyPosition as SurveyPosition, types_SurveyQuestionBranchingType as SurveyQuestionBranchingType, types_SurveyQuestionDescriptionContentType as SurveyQuestionDescriptionContentType, types_SurveyQuestionType as SurveyQuestionType, types_SurveyRatingDisplay as SurveyRatingDisplay, types_SurveySchedule as SurveySchedule, types_SurveyType as SurveyType, types_SurveyValidationType as SurveyValidationType, types_SurveyWidgetType as SurveyWidgetType, knownUnsafeEditableEvent };\n", "const DEFAULT_BLOCKED_UA_STRS = [\n 'amazonbot',\n 'amazonproductbot',\n 'app.hypefactors.com',\n 'applebot',\n 'archive.org_bot',\n 'awariobot',\n 'backlinksextendedbot',\n 'baiduspider',\n 'bingbot',\n 'bingpreview',\n 'chrome-lighthouse',\n 'dataforseobot',\n 'deepscan',\n 'duckduckbot',\n 'facebookexternal',\n 'facebookcatalog',\n 'http://yandex.com/bots',\n 'hubspot',\n 'ia_archiver',\n 'leikibot',\n 'linkedinbot',\n 'meta-externalagent',\n 'mj12bot',\n 'msnbot',\n 'nessus',\n 'petalbot',\n 'pinterest',\n 'prerender',\n 'rogerbot',\n 'screaming frog',\n 'sebot-wa',\n 'sitebulb',\n 'slackbot',\n 'slurp',\n 'trendictionbot',\n 'turnitin',\n 'twitterbot',\n 'vercel-screenshot',\n 'vercelbot',\n 'yahoo! slurp',\n 'yandexbot',\n 'zoombot',\n 'bot.htm',\n 'bot.php',\n '(bot;',\n 'bot/',\n 'crawler',\n 'ahrefsbot',\n 'ahrefssiteaudit',\n 'semrushbot',\n 'siteauditbot',\n 'splitsignalbot',\n 'gptbot',\n 'oai-searchbot',\n 'chatgpt-user',\n 'perplexitybot',\n 'better uptime bot',\n 'sentryuptimebot',\n 'uptimerobot',\n 'headlesschrome',\n 'cypress',\n 'google-hoteladsverifier',\n 'adsbot-google',\n 'apis-google',\n 'duplexweb-google',\n 'feedfetcher-google',\n 'google favicon',\n 'google web preview',\n 'google-read-aloud',\n 'googlebot',\n 'googleother',\n 'google-cloudvertexbot',\n 'googleweblight',\n 'mediapartners-google',\n 'storebot-google',\n 'google-inspectiontool',\n 'bytespider'\n];\nconst isBlockedUA = function(ua, customBlockedUserAgents = []) {\n if (!ua) return false;\n const uaLower = ua.toLowerCase();\n return DEFAULT_BLOCKED_UA_STRS.concat(customBlockedUserAgents).some((blockedUA)=>{\n const blockedUaLower = blockedUA.toLowerCase();\n return -1 !== uaLower.indexOf(blockedUaLower);\n });\n};\nexport { DEFAULT_BLOCKED_UA_STRS, isBlockedUA };\n", "function includes(str, needle) {\n return -1 !== str.indexOf(needle);\n}\nconst trim = function(str) {\n return str.trim();\n};\nconst stripLeadingDollar = function(s) {\n return s.replace(/^\\$/, '');\n};\nfunction isDistinctIdStringLike(value) {\n return [\n 'distinct_id',\n 'distinctid'\n ].includes(value.toLowerCase());\n}\nfunction deepSortKeys(value) {\n if (null === value || 'object' != typeof value) return value;\n if (Array.isArray(value)) return value.map(deepSortKeys);\n return Object.keys(value).sort().reduce((acc, key)=>{\n acc[key] = deepSortKeys(value[key]);\n return acc;\n }, {});\n}\nfunction getPersonPropertiesHash(distinct_id, userPropertiesToSet, userPropertiesToSetOnce) {\n return JSON.stringify({\n distinct_id,\n userPropertiesToSet: userPropertiesToSet ? deepSortKeys(userPropertiesToSet) : void 0,\n userPropertiesToSetOnce: userPropertiesToSetOnce ? deepSortKeys(userPropertiesToSetOnce) : void 0\n });\n}\nexport { getPersonPropertiesHash, includes, isDistinctIdStringLike, stripLeadingDollar, trim };\n", "import { knownUnsafeEditableEvent } from \"../types.mjs\";\nimport { includes } from \"./string-utils.mjs\";\nconst nativeIsArray = Array.isArray;\nconst ObjProto = Object.prototype;\nconst type_utils_hasOwnProperty = ObjProto.hasOwnProperty;\nconst type_utils_toString = ObjProto.toString;\nconst isArray = nativeIsArray || function(obj) {\n return '[object Array]' === type_utils_toString.call(obj);\n};\nconst isFunction = (x)=>'function' == typeof x;\nconst isNativeFunction = (x)=>isFunction(x) && -1 !== x.toString().indexOf('[native code]');\nconst isObject = (x)=>x === Object(x) && !isArray(x);\nconst isEmptyObject = (x)=>{\n if (isObject(x)) {\n for(const key in x)if (type_utils_hasOwnProperty.call(x, key)) return false;\n return true;\n }\n return false;\n};\nconst isUndefined = (x)=>void 0 === x;\nconst isString = (x)=>'[object String]' == type_utils_toString.call(x);\nconst isEmptyString = (x)=>isString(x) && 0 === x.trim().length;\nconst isNull = (x)=>null === x;\nconst isNullish = (x)=>isUndefined(x) || isNull(x);\nconst isNumber = (x)=>'[object Number]' == type_utils_toString.call(x) && x === x;\nconst isPositiveNumber = (value)=>isNumber(value) && value > 0;\nconst isBoolean = (x)=>'[object Boolean]' === type_utils_toString.call(x);\nconst isFormData = (x)=>x instanceof FormData;\nconst isFile = (x)=>x instanceof File;\nconst isPlainError = (x)=>x instanceof Error;\nconst isKnownUnsafeEditableEvent = (x)=>includes(knownUnsafeEditableEvent, x);\nfunction isPrimitive(value) {\n return null === value || 'object' != typeof value;\n}\nfunction isBuiltin(candidate, className) {\n return Object.prototype.toString.call(candidate) === `[object ${className}]`;\n}\nfunction isError(candidate) {\n switch(Object.prototype.toString.call(candidate)){\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object DOMError]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(candidate, Error);\n }\n}\nfunction isErrorEvent(event) {\n return isBuiltin(event, 'ErrorEvent');\n}\nfunction isEvent(candidate) {\n return 'undefined' != typeof Event && isInstanceOf(candidate, Event);\n}\nfunction isPlainObject(candidate) {\n return isBuiltin(candidate, 'Object');\n}\nfunction isInstanceOf(candidate, base) {\n try {\n return candidate instanceof base;\n } catch {\n return false;\n }\n}\nconst yesLikeValues = [\n true,\n 'true',\n 1,\n '1',\n 'yes'\n];\nconst isYesLike = (val)=>includes(yesLikeValues, val);\nconst noLikeValues = [\n false,\n 'false',\n 0,\n '0',\n 'no'\n];\nconst isNoLike = (val)=>includes(noLikeValues, val);\nexport { type_utils_hasOwnProperty as hasOwnProperty, isArray, isBoolean, isBuiltin, isEmptyObject, isEmptyString, isError, isErrorEvent, isEvent, isFile, isFormData, isFunction, isKnownUnsafeEditableEvent, isNativeFunction, isNoLike, isNull, isNullish, isNumber, isObject, isPlainError, isPlainObject, isPositiveNumber, isPrimitive, isString, isUndefined, isYesLike, noLikeValues, yesLikeValues };\n", "import { isNumber } from \"./type-utils.mjs\";\nfunction clampToRange(value, min, max, logger, fallbackValue) {\n if (min > max) {\n logger.warn('min cannot be greater than max.');\n min = max;\n }\n if (isNumber(value)) if (value > max) {\n logger.warn(' cannot be greater than max: ' + max + '. Using max value instead.');\n return max;\n } else {\n if (!(value < min)) return value;\n logger.warn(' cannot be less than min: ' + min + '. Using min value instead.');\n return min;\n }\n logger.warn(' must be a number. using max or fallback. max: ' + max + ', fallback: ' + fallbackValue);\n return clampToRange(fallbackValue || max, min, max, logger);\n}\nfunction getRemoteConfigBool(field, key, defaultValue = true) {\n if (null == field) return defaultValue;\n if ('boolean' == typeof field) return field;\n if ('object' == typeof field) {\n const value = field[key];\n return 'boolean' == typeof value ? value : defaultValue;\n }\n return defaultValue;\n}\nfunction getRemoteConfigNumber(field, key) {\n if (null == field || 'object' != typeof field) return;\n const value = field[key];\n if ('number' == typeof value && Number.isFinite(value)) return value;\n if ('string' == typeof value) {\n const trimmed = value.trim();\n if ('' === trimmed) return;\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : void 0;\n }\n}\nfunction isValidSampleRate(value) {\n return 'number' == typeof value && Number.isFinite(value) && value >= 0 && value <= 1;\n}\nexport { clampToRange, getRemoteConfigBool, getRemoteConfigNumber, isValidSampleRate };\n", "import { clampToRange } from \"./number-utils.mjs\";\nconst ONE_DAY_IN_MS = 86400000;\nclass BucketedRateLimiter {\n constructor(options){\n this._buckets = {};\n this._onBucketRateLimited = options._onBucketRateLimited;\n this._bucketSize = clampToRange(options.bucketSize, 0, 100, options._logger);\n this._refillRate = clampToRange(options.refillRate, 0, this._bucketSize, options._logger);\n this._refillInterval = clampToRange(options.refillInterval, 0, ONE_DAY_IN_MS, options._logger);\n }\n _applyRefill(bucket, now) {\n const elapsedMs = now - bucket.lastAccess;\n const refillIntervals = Math.floor(elapsedMs / this._refillInterval);\n if (refillIntervals > 0) {\n const tokensToAdd = refillIntervals * this._refillRate;\n bucket.tokens = Math.min(bucket.tokens + tokensToAdd, this._bucketSize);\n bucket.lastAccess = bucket.lastAccess + refillIntervals * this._refillInterval;\n }\n }\n consumeRateLimit(key) {\n const now = Date.now();\n const keyStr = String(key);\n let bucket = this._buckets[keyStr];\n if (bucket) this._applyRefill(bucket, now);\n else {\n bucket = {\n tokens: this._bucketSize,\n lastAccess: now\n };\n this._buckets[keyStr] = bucket;\n }\n if (0 === bucket.tokens) return true;\n bucket.tokens--;\n if (0 === bucket.tokens) this._onBucketRateLimited?.(key);\n return 0 === bucket.tokens;\n }\n stop() {\n this._buckets = {};\n }\n}\nexport { BucketedRateLimiter };\n", "import { includes } from \"./string-utils.mjs\";\nimport { isFunction, isUndefined } from \"./type-utils.mjs\";\nconst FACEBOOK = 'Facebook';\nconst MOBILE = 'Mobile';\nconst IOS = 'iOS';\nconst ANDROID = 'Android';\nconst TABLET = 'Tablet';\nconst ANDROID_TABLET = ANDROID + ' ' + TABLET;\nconst IPAD = 'iPad';\nconst APPLE = 'Apple';\nconst APPLE_WATCH = APPLE + ' Watch';\nconst SAFARI = 'Safari';\nconst BLACKBERRY = 'BlackBerry';\nconst SAMSUNG = 'Samsung';\nconst SAMSUNG_BROWSER = SAMSUNG + 'Browser';\nconst SAMSUNG_INTERNET = SAMSUNG + ' Internet';\nconst CHROME = 'Chrome';\nconst CHROME_OS = CHROME + ' OS';\nconst CHROME_IOS = CHROME + ' ' + IOS;\nconst INTERNET_EXPLORER = 'Internet Explorer';\nconst INTERNET_EXPLORER_MOBILE = INTERNET_EXPLORER + ' ' + MOBILE;\nconst OPERA = 'Opera';\nconst OPERA_MINI = OPERA + ' Mini';\nconst EDGE = 'Edge';\nconst MICROSOFT_EDGE = 'Microsoft ' + EDGE;\nconst FIREFOX = 'Firefox';\nconst FIREFOX_IOS = FIREFOX + ' ' + IOS;\nconst NINTENDO = 'Nintendo';\nconst PLAYSTATION = 'PlayStation';\nconst XBOX = 'Xbox';\nconst ANDROID_MOBILE = ANDROID + ' ' + MOBILE;\nconst MOBILE_SAFARI = MOBILE + ' ' + SAFARI;\nconst WINDOWS = 'Windows';\nconst WINDOWS_PHONE = WINDOWS + ' Phone';\nconst NOKIA = 'Nokia';\nconst OUYA = 'Ouya';\nconst GENERIC = 'Generic';\nconst GENERIC_MOBILE = GENERIC + ' ' + MOBILE.toLowerCase();\nconst GENERIC_TABLET = GENERIC + ' ' + TABLET.toLowerCase();\nconst KONQUEROR = 'Konqueror';\nconst BROWSER_VERSION_REGEX_SUFFIX = '(\\\\d+(\\\\.\\\\d+)?)';\nconst DEFAULT_BROWSER_VERSION_REGEX = new RegExp('Version/' + BROWSER_VERSION_REGEX_SUFFIX);\nconst XBOX_REGEX = new RegExp(XBOX, 'i');\nconst PLAYSTATION_REGEX = new RegExp(PLAYSTATION + ' \\\\w+', 'i');\nconst NINTENDO_REGEX = new RegExp(NINTENDO + ' \\\\w+', 'i');\nconst BLACKBERRY_REGEX = new RegExp(BLACKBERRY + '|PlayBook|BB10', 'i');\nconst windowsVersionMap = {\n 'NT3.51': 'NT 3.11',\n 'NT4.0': 'NT 4.0',\n '5.0': '2000',\n '5.1': 'XP',\n '5.2': 'XP',\n '6.0': 'Vista',\n '6.1': '7',\n '6.2': '8',\n '6.3': '8.1',\n '6.4': '10',\n '10.0': '10'\n};\nfunction isSafari(userAgent) {\n return includes(userAgent, SAFARI) && !includes(userAgent, CHROME) && !includes(userAgent, ANDROID);\n}\nconst safariCheck = (ua, vendor)=>vendor && includes(vendor, APPLE) || isSafari(ua);\nconst detectBrowser = function(user_agent, vendor) {\n vendor = vendor || '';\n if (includes(user_agent, ' OPR/') && includes(user_agent, 'Mini')) return OPERA_MINI;\n if (includes(user_agent, ' OPR/')) return OPERA;\n if (BLACKBERRY_REGEX.test(user_agent)) return BLACKBERRY;\n if (includes(user_agent, 'IE' + MOBILE) || includes(user_agent, 'WPDesktop')) return INTERNET_EXPLORER_MOBILE;\n if (includes(user_agent, SAMSUNG_BROWSER)) return SAMSUNG_INTERNET;\n else if (includes(user_agent, EDGE) || includes(user_agent, 'Edg/')) return MICROSOFT_EDGE;\n else if (includes(user_agent, 'FBIOS')) return FACEBOOK + ' ' + MOBILE;\n else if (includes(user_agent, 'UCWEB') || includes(user_agent, 'UCBrowser')) return 'UC Browser';\n else if (includes(user_agent, 'CriOS')) return CHROME_IOS;\n else if (includes(user_agent, 'CrMo')) return CHROME;\n else if (includes(user_agent, CHROME)) return CHROME;\n else if (includes(user_agent, ANDROID) && includes(user_agent, SAFARI)) return ANDROID_MOBILE;\n else if (includes(user_agent, 'FxiOS')) return FIREFOX_IOS;\n else if (includes(user_agent.toLowerCase(), KONQUEROR.toLowerCase())) return KONQUEROR;\n else if (safariCheck(user_agent, vendor)) return includes(user_agent, MOBILE) ? MOBILE_SAFARI : SAFARI;\n else if (includes(user_agent, FIREFOX)) return FIREFOX;\n else if (includes(user_agent, 'MSIE') || includes(user_agent, 'Trident/')) return INTERNET_EXPLORER;\n else if (includes(user_agent, 'Gecko')) return FIREFOX;\n return '';\n};\nconst versionRegexes = {\n [INTERNET_EXPLORER_MOBILE]: [\n new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [MICROSOFT_EDGE]: [\n new RegExp(EDGE + '?\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [CHROME]: [\n new RegExp('(' + CHROME + '|CrMo)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [CHROME_IOS]: [\n new RegExp('CriOS\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n 'UC Browser': [\n new RegExp('(UCBrowser|UCWEB)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [SAFARI]: [\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [MOBILE_SAFARI]: [\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [OPERA]: [\n new RegExp('(' + OPERA + '|OPR)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [FIREFOX]: [\n new RegExp(FIREFOX + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [FIREFOX_IOS]: [\n new RegExp('FxiOS\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [KONQUEROR]: [\n new RegExp('Konqueror[:/]?' + BROWSER_VERSION_REGEX_SUFFIX, 'i')\n ],\n [BLACKBERRY]: [\n new RegExp(BLACKBERRY + ' ' + BROWSER_VERSION_REGEX_SUFFIX),\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [ANDROID_MOBILE]: [\n new RegExp('android\\\\s' + BROWSER_VERSION_REGEX_SUFFIX, 'i')\n ],\n [SAMSUNG_INTERNET]: [\n new RegExp(SAMSUNG_BROWSER + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [INTERNET_EXPLORER]: [\n new RegExp('(rv:|MSIE )' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n Mozilla: [\n new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)\n ]\n};\nconst detectBrowserVersion = function(userAgent, vendor) {\n const browser = detectBrowser(userAgent, vendor);\n const regexes = versionRegexes[browser];\n if (isUndefined(regexes)) return null;\n for(let i = 0; i < regexes.length; i++){\n const regex = regexes[i];\n const matches = userAgent.match(regex);\n if (matches) return parseFloat(matches[matches.length - 2]);\n }\n return null;\n};\nconst osMatchers = [\n [\n new RegExp(XBOX + '; ' + XBOX + ' (.*?)[);]', 'i'),\n (match)=>[\n XBOX,\n match && match[1] || ''\n ]\n ],\n [\n new RegExp(NINTENDO, 'i'),\n [\n NINTENDO,\n ''\n ]\n ],\n [\n new RegExp(PLAYSTATION, 'i'),\n [\n PLAYSTATION,\n ''\n ]\n ],\n [\n BLACKBERRY_REGEX,\n [\n BLACKBERRY,\n ''\n ]\n ],\n [\n new RegExp(WINDOWS, 'i'),\n (_, user_agent)=>{\n if (/Phone/.test(user_agent) || /WPDesktop/.test(user_agent)) return [\n WINDOWS_PHONE,\n ''\n ];\n if (new RegExp(MOBILE).test(user_agent) && !/IEMobile\\b/.test(user_agent)) return [\n WINDOWS + ' ' + MOBILE,\n ''\n ];\n const match = /Windows NT ([0-9.]+)/i.exec(user_agent);\n if (match && match[1]) {\n const version = match[1];\n let osVersion = windowsVersionMap[version] || '';\n if (/arm/i.test(user_agent)) osVersion = 'RT';\n return [\n WINDOWS,\n osVersion\n ];\n }\n return [\n WINDOWS,\n ''\n ];\n }\n ],\n [\n /((iPhone|iPad|iPod).*?OS (\\d+)_(\\d+)_?(\\d+)?|iPhone)/,\n (match)=>{\n if (match && match[3]) {\n const versionParts = [\n match[3],\n match[4],\n match[5] || '0'\n ];\n return [\n IOS,\n versionParts.join('.')\n ];\n }\n return [\n IOS,\n ''\n ];\n }\n ],\n [\n /(watch.*\\/(\\d+\\.\\d+\\.\\d+)|watch os,(\\d+\\.\\d+),)/i,\n (match)=>{\n let version = '';\n if (match && match.length >= 3) version = isUndefined(match[2]) ? match[3] : match[2];\n return [\n 'watchOS',\n version\n ];\n }\n ],\n [\n new RegExp('(' + ANDROID + ' (\\\\d+)\\\\.(\\\\d+)\\\\.?(\\\\d+)?|' + ANDROID + ')', 'i'),\n (match)=>{\n if (match && match[2]) {\n const versionParts = [\n match[2],\n match[3],\n match[4] || '0'\n ];\n return [\n ANDROID,\n versionParts.join('.')\n ];\n }\n return [\n ANDROID,\n ''\n ];\n }\n ],\n [\n /Mac OS X (\\d+)[_.](\\d+)[_.]?(\\d+)?/i,\n (match)=>{\n const result = [\n 'Mac OS X',\n ''\n ];\n if (match && match[1]) {\n const versionParts = [\n match[1],\n match[2],\n match[3] || '0'\n ];\n result[1] = versionParts.join('.');\n }\n return result;\n }\n ],\n [\n /Mac/i,\n [\n 'Mac OS X',\n ''\n ]\n ],\n [\n /CrOS/,\n [\n CHROME_OS,\n ''\n ]\n ],\n [\n /Linux|debian/i,\n [\n 'Linux',\n ''\n ]\n ]\n];\nconst detectOS = function(user_agent) {\n for(let i = 0; i < osMatchers.length; i++){\n const [rgex, resultOrFn] = osMatchers[i];\n const match = rgex.exec(user_agent);\n const result = match && (isFunction(resultOrFn) ? resultOrFn(match, user_agent) : resultOrFn);\n if (result) return result;\n }\n return [\n '',\n ''\n ];\n};\nconst detectDevice = function(user_agent) {\n if (NINTENDO_REGEX.test(user_agent)) return NINTENDO;\n if (PLAYSTATION_REGEX.test(user_agent)) return PLAYSTATION;\n if (XBOX_REGEX.test(user_agent)) return XBOX;\n if (new RegExp(OUYA, 'i').test(user_agent)) return OUYA;\n if (new RegExp('(' + WINDOWS_PHONE + '|WPDesktop)', 'i').test(user_agent)) return WINDOWS_PHONE;\n else if (/iPad/.test(user_agent)) return IPAD;\n else if (/iPod/.test(user_agent)) return 'iPod Touch';\n else if (/iPhone/.test(user_agent)) return 'iPhone';\n else if (/(watch)(?: ?os[,/]|\\d,\\d\\/)[\\d.]+/i.test(user_agent)) return APPLE_WATCH;\n else if (BLACKBERRY_REGEX.test(user_agent)) return BLACKBERRY;\n else if (/(kobo)\\s(ereader|touch)/i.test(user_agent)) return 'Kobo';\n else if (new RegExp(NOKIA, 'i').test(user_agent)) return NOKIA;\n else if (/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\\))/i.test(user_agent) || /(kf[a-z]+)( bui|\\)).+silk\\//i.test(user_agent)) return 'Kindle Fire';\n else if (/(Android|ZTE)/i.test(user_agent)) if (!(!new RegExp(MOBILE).test(user_agent) || /(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(user_agent))) return ANDROID;\n else {\n if (/pixel[\\daxl ]{1,6}/i.test(user_agent) && !/pixel c/i.test(user_agent) || /(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(user_agent) || /lmy47v/i.test(user_agent) && !/QTAQZ3/i.test(user_agent)) return ANDROID;\n return ANDROID_TABLET;\n }\n else if (new RegExp('(pda|' + MOBILE + ')', 'i').test(user_agent)) return GENERIC_MOBILE;\n else if (new RegExp(TABLET, 'i').test(user_agent) && !new RegExp(TABLET + ' pc', 'i').test(user_agent)) return GENERIC_TABLET;\n else return '';\n};\nconst detectDeviceType = function(user_agent, options) {\n const device = detectDevice(user_agent);\n if (device === IPAD || device === ANDROID_TABLET || 'Kobo' === device || 'Kindle Fire' === device || device === GENERIC_TABLET) return TABLET;\n if (device === NINTENDO || device === XBOX || device === PLAYSTATION || device === OUYA) return 'Console';\n if (device === APPLE_WATCH) return 'Wearable';\n if (device) return MOBILE;\n if (options?.userAgentDataPlatform === 'Android' && (options?.maxTouchPoints ?? 0) > 0) {\n const shortSide = Math.min(options?.screenWidth ?? 0, options?.screenHeight ?? 0);\n const shortSideDp = shortSide / (options?.devicePixelRatio ?? 1);\n return shortSideDp >= 600 ? TABLET : MOBILE;\n }\n return 'Desktop';\n};\nexport { detectBrowser, detectBrowserVersion, detectDevice, detectDeviceType, detectOS };\n", "let parsedStackResults;\nlet lastKeysCount;\nlet cachedFilenameChunkIds;\nfunction getFilenameToChunkIdMap(stackParser) {\n const chunkIdMap = globalThis._posthogChunkIds;\n if (!chunkIdMap) return;\n const chunkIdKeys = Object.keys(chunkIdMap);\n if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount) return cachedFilenameChunkIds;\n lastKeysCount = chunkIdKeys.length;\n cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey)=>{\n if (!parsedStackResults) parsedStackResults = {};\n const result = parsedStackResults[stackKey];\n if (result) acc[result[0]] = result[1];\n else {\n const parsedStack = stackParser(stackKey);\n for(let i = parsedStack.length - 1; i >= 0; i--){\n const stackFrame = parsedStack[i];\n const filename = stackFrame?.filename;\n const chunkId = chunkIdMap[stackKey];\n if (filename && chunkId) {\n acc[filename] = chunkId;\n parsedStackResults[stackKey] = [\n filename,\n chunkId\n ];\n break;\n }\n }\n }\n return acc;\n }, {});\n return cachedFilenameChunkIds;\n}\nexport { getFilenameToChunkIdMap };\n", "export * from \"./bot-detection.mjs\";\nexport * from \"./bucketed-rate-limiter.mjs\";\nexport * from \"./number-utils.mjs\";\nexport * from \"./string-utils.mjs\";\nexport * from \"./type-utils.mjs\";\nexport * from \"./promise-queue.mjs\";\nexport * from \"./logger.mjs\";\nexport * from \"./user-agent-utils.mjs\";\nconst STRING_FORMAT = 'utf8';\nfunction assert(truthyValue, message) {\n if (!truthyValue || 'string' != typeof truthyValue || isEmpty(truthyValue)) throw new Error(message);\n}\nfunction isEmpty(truthyValue) {\n if (0 === truthyValue.trim().length) return true;\n return false;\n}\nfunction removeTrailingSlash(url) {\n return url?.replace(/\\/+$/, '');\n}\nasync function retriable(fn, props) {\n let lastError = null;\n for(let i = 0; i < props.retryCount + 1; i++){\n if (i > 0) await new Promise((r)=>setTimeout(r, props.retryDelay));\n try {\n const res = await fn();\n return res;\n } catch (e) {\n lastError = e;\n if (!props.retryCheck(e)) throw e;\n }\n }\n throw lastError;\n}\nfunction currentTimestamp() {\n return new Date().getTime();\n}\nfunction currentISOTime() {\n return new Date().toISOString();\n}\nfunction safeSetTimeout(fn, timeout) {\n const t = setTimeout(fn, timeout);\n t?.unref && t?.unref();\n return t;\n}\nconst isPromise = (obj)=>obj && 'function' == typeof obj.then;\nconst isError = (x)=>x instanceof Error;\nfunction getFetch() {\n return 'undefined' != typeof fetch ? fetch : void 0 !== globalThis.fetch ? globalThis.fetch : void 0;\n}\nfunction allSettled(promises) {\n return Promise.all(promises.map((p)=>(p ?? Promise.resolve()).then((value)=>({\n status: 'fulfilled',\n value\n }), (reason)=>({\n status: 'rejected',\n reason\n }))));\n}\nexport { STRING_FORMAT, allSettled, assert, currentISOTime, currentTimestamp, getFetch, isError, isPromise, removeTrailingSlash, retriable, safeSetTimeout };\n", "import { isArray } from \"../utils/index.mjs\";\nimport { getFilenameToChunkIdMap } from \"./chunk-ids.mjs\";\nconst MAX_CAUSE_RECURSION = 4;\nclass ErrorPropertiesBuilder {\n constructor(coercers, stackParser, modifiers = []){\n this.coercers = coercers;\n this.stackParser = stackParser;\n this.modifiers = modifiers;\n }\n buildFromUnknown(input, hint = {}) {\n const providedMechanism = hint && hint.mechanism;\n const mechanism = providedMechanism || {\n handled: true,\n type: 'generic'\n };\n const coercingContext = this.buildCoercingContext(mechanism, hint, 0);\n const exceptionWithCause = coercingContext.apply(input);\n const parsingContext = this.buildParsingContext(hint);\n const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);\n const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);\n return {\n $exception_list: exceptionList,\n $exception_level: 'error'\n };\n }\n async modifyFrames(exceptionList) {\n for (const exc of exceptionList)if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames)) exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);\n return exceptionList;\n }\n coerceFallback(ctx) {\n return {\n type: 'Error',\n value: 'Unknown error',\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n parseStacktrace(err, ctx) {\n let cause;\n if (null != err.cause) cause = this.parseStacktrace(err.cause, ctx);\n let stack;\n if ('' != err.stack && null != err.stack) stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);\n return {\n ...err,\n cause,\n stack\n };\n }\n applyChunkIds(frames, chunkIdMap) {\n return frames.map((frame)=>{\n if (frame.filename && chunkIdMap) frame.chunk_id = chunkIdMap[frame.filename];\n return frame;\n });\n }\n applyCoercers(input, ctx) {\n for (const adapter of this.coercers)if (adapter.match(input)) return adapter.coerce(input, ctx);\n return this.coerceFallback(ctx);\n }\n async applyModifiers(frames) {\n let newFrames = frames;\n for (const modifier of this.modifiers)newFrames = await modifier(newFrames);\n return newFrames;\n }\n convertToExceptionList(exceptionWithStack, mechanism) {\n const currentException = {\n type: exceptionWithStack.type,\n value: exceptionWithStack.value,\n mechanism: {\n type: mechanism.type ?? 'generic',\n handled: mechanism.handled ?? true,\n synthetic: exceptionWithStack.synthetic ?? false\n }\n };\n if (exceptionWithStack.stack) currentException.stacktrace = {\n type: 'raw',\n frames: exceptionWithStack.stack\n };\n const exceptionList = [\n currentException\n ];\n if (null != exceptionWithStack.cause) exceptionList.push(...this.convertToExceptionList(exceptionWithStack.cause, {\n ...mechanism,\n handled: true\n }));\n return exceptionList;\n }\n buildParsingContext(hint) {\n const context = {\n chunkIdMap: getFilenameToChunkIdMap(this.stackParser),\n skipFirstLines: hint.skipFirstLines ?? 1\n };\n return context;\n }\n buildCoercingContext(mechanism, hint, depth = 0) {\n const coerce = (input, depth)=>{\n if (!(depth <= MAX_CAUSE_RECURSION)) return;\n {\n const ctx = this.buildCoercingContext(mechanism, hint, depth);\n return this.applyCoercers(input, ctx);\n }\n };\n const context = {\n ...hint,\n syntheticException: 0 == depth ? hint.syntheticException : void 0,\n mechanism,\n apply: (input)=>coerce(input, depth),\n next: (input)=>coerce(input, depth + 1)\n };\n return context;\n }\n}\nexport { ErrorPropertiesBuilder };\n", "import { isUndefined } from \"../../utils/index.mjs\";\nconst UNKNOWN_FUNCTION = '?';\nfunction createFrame(platform, filename, func, lineno, colno) {\n const frame = {\n platform,\n filename,\n function: '' === func ? UNKNOWN_FUNCTION : func,\n in_app: true\n };\n if (!isUndefined(lineno)) frame.lineno = lineno;\n if (!isUndefined(colno)) frame.colno = colno;\n return frame;\n}\nexport { UNKNOWN_FUNCTION, createFrame };\n", "import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nconst extractSafariExtensionDetails = (func, filename)=>{\n const isSafariExtension = -1 !== func.indexOf('safari-extension');\n const isSafariWebExtension = -1 !== func.indexOf('safari-web-extension');\n return isSafariExtension || isSafariWebExtension ? [\n -1 !== func.indexOf('@') ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`\n ] : [\n func,\n filename\n ];\n};\nexport { extractSafariExtensionDetails };\n", "import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nimport { extractSafariExtensionDetails } from \"./safari.mjs\";\nconst chromeRegexNoFnName = /^\\s*at (\\S+?)(?::(\\d+))(?::(\\d+))\\s*$/i;\nconst chromeRegex = /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\nconst chromeStackLineParser = (line, platform)=>{\n const noFnParts = chromeRegexNoFnName.exec(line);\n if (noFnParts) {\n const [, filename, line, col] = noFnParts;\n return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);\n }\n const parts = chromeRegex.exec(line);\n if (parts) {\n const isEval = parts[2] && 0 === parts[2].indexOf('eval');\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n if (subMatch) {\n parts[2] = subMatch[1];\n parts[3] = subMatch[2];\n parts[4] = subMatch[3];\n }\n }\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n return createFrame(platform, filename, func, parts[3] ? +parts[3] : void 0, parts[4] ? +parts[4] : void 0);\n }\n};\nexport { chromeStackLineParser };\n", "import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nimport { extractSafariExtensionDetails } from \"./safari.mjs\";\nconst geckoREgex = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\nconst geckoStackLineParser = (line, platform)=>{\n const parts = geckoREgex.exec(line);\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n if (subMatch) {\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = '';\n }\n }\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n return createFrame(platform, filename, func, parts[4] ? +parts[4] : void 0, parts[5] ? +parts[5] : void 0);\n }\n};\nexport { geckoStackLineParser };\n", "import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nimport { chromeStackLineParser } from \"./chrome.mjs\";\nimport { geckoStackLineParser } from \"./gecko.mjs\";\nimport { winjsStackLineParser } from \"./winjs.mjs\";\nimport { opera10StackLineParser, opera11StackLineParser } from \"./opera.mjs\";\nimport { nodeStackLineParser } from \"./node.mjs\";\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STACKTRACE_FRAME_LIMIT = 50;\nfunction reverseAndStripFrames(stack) {\n if (!stack.length) return [];\n const localStack = Array.from(stack);\n localStack.reverse();\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame)=>({\n ...frame,\n filename: frame.filename || getLastStackFrame(localStack).filename,\n function: frame.function || UNKNOWN_FUNCTION\n }));\n}\nfunction getLastStackFrame(arr) {\n return arr[arr.length - 1] || {};\n}\nfunction createDefaultStackParser() {\n return createStackParser(\"web:javascript\", chromeStackLineParser, geckoStackLineParser);\n}\nfunction createStackParser(platform, ...parsers) {\n return (stack, skipFirstLines = 0)=>{\n const frames = [];\n const lines = stack.split('\\n');\n for(let i = skipFirstLines; i < lines.length; i++){\n const line = lines[i];\n if (line.length > 1024) continue;\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n if (!cleanedLine.match(/\\S*Error: /)) {\n for (const parser of parsers){\n const frame = parser(cleanedLine, platform);\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n if (frames.length >= STACKTRACE_FRAME_LIMIT) break;\n }\n }\n return reverseAndStripFrames(frames);\n };\n}\nexport { chromeStackLineParser, createDefaultStackParser, createStackParser, geckoStackLineParser, nodeStackLineParser, opera10StackLineParser, opera11StackLineParser, reverseAndStripFrames, winjsStackLineParser };\n", "import { isBuiltin, isString } from \"../../utils/index.mjs\";\nclass DOMExceptionCoercer {\n match(err) {\n return this.isDOMException(err) || this.isDOMError(err);\n }\n coerce(err, ctx) {\n const hasStack = isString(err.stack);\n return {\n type: this.getType(err),\n value: this.getValue(err),\n stack: hasStack ? err.stack : void 0,\n cause: err.cause ? ctx.next(err.cause) : void 0,\n synthetic: false\n };\n }\n getType(candidate) {\n return this.isDOMError(candidate) ? 'DOMError' : 'DOMException';\n }\n getValue(err) {\n const name = err.name || (this.isDOMError(err) ? 'DOMError' : 'DOMException');\n const message = err.message ? `${name}: ${err.message}` : name;\n return message;\n }\n isDOMException(err) {\n return isBuiltin(err, 'DOMException');\n }\n isDOMError(err) {\n return isBuiltin(err, 'DOMError');\n }\n}\nexport { DOMExceptionCoercer };\n", "import { isPlainError } from \"../../utils/index.mjs\";\nclass ErrorCoercer {\n match(err) {\n return isPlainError(err);\n }\n coerce(err, ctx) {\n return {\n type: this.getType(err),\n value: this.getMessage(err, ctx),\n stack: this.getStack(err),\n cause: err.cause ? ctx.next(err.cause) : void 0,\n synthetic: false\n };\n }\n getType(err) {\n return err.name || err.constructor.name;\n }\n getMessage(err, _ctx) {\n const message = err.message;\n if (message.error && 'string' == typeof message.error.message) return String(message.error.message);\n return String(message);\n }\n getStack(err) {\n return err.stacktrace || err.stack || void 0;\n }\n}\nexport { ErrorCoercer };\n", "import { isErrorEvent } from \"../../utils/index.mjs\";\nclass ErrorEventCoercer {\n constructor(){}\n match(err) {\n return isErrorEvent(err) && void 0 != err.error;\n }\n coerce(err, ctx) {\n const exceptionLike = ctx.apply(err.error);\n if (!exceptionLike) return {\n type: 'ErrorEvent',\n value: err.message,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n return exceptionLike;\n }\n}\nexport { ErrorEventCoercer };\n", "const ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\nclass StringCoercer {\n match(input) {\n return 'string' == typeof input;\n }\n coerce(input, ctx) {\n const [type, value] = this.getInfos(input);\n return {\n type: type ?? 'Error',\n value: value ?? input,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n getInfos(candidate) {\n let type = 'Error';\n let value = candidate;\n const groups = candidate.match(ERROR_TYPES_PATTERN);\n if (groups) {\n type = groups[1];\n value = groups[2];\n }\n return [\n type,\n value\n ];\n }\n}\nexport { StringCoercer };\n", "const severityLevels = [\n 'fatal',\n 'error',\n 'warning',\n 'log',\n 'info',\n 'debug'\n];\nexport { severityLevels };\n", "function truncate(str, max = 0) {\n if ('string' != typeof str || 0 === max) return str;\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\nfunction extractExceptionKeysForMessage(err, maxLength = 40) {\n const keys = Object.keys(err);\n keys.sort();\n if (!keys.length) return '[object has no keys]';\n for(let i = keys.length; i > 0; i--){\n const serialized = keys.slice(0, i).join(', ');\n if (!(serialized.length > maxLength)) {\n if (i === keys.length) return serialized;\n return serialized.length <= maxLength ? serialized : `${serialized.slice(0, maxLength)}...`;\n }\n }\n return '';\n}\nexport { extractExceptionKeysForMessage, truncate };\n", "import { isEmptyString, isError, isEvent, isString } from \"../../utils/index.mjs\";\nimport { severityLevels } from \"../types.mjs\";\nimport { extractExceptionKeysForMessage } from \"./utils.mjs\";\nclass ObjectCoercer {\n match(candidate) {\n return 'object' == typeof candidate && null !== candidate;\n }\n coerce(candidate, ctx) {\n const errorProperty = this.getErrorPropertyFromObject(candidate);\n if (errorProperty) return ctx.apply(errorProperty);\n return {\n type: this.getType(candidate),\n value: this.getValue(candidate),\n stack: ctx.syntheticException?.stack,\n level: this.isSeverityLevel(candidate.level) ? candidate.level : 'error',\n synthetic: true\n };\n }\n getType(err) {\n return isEvent(err) ? err.constructor.name : 'Error';\n }\n getValue(err) {\n if ('name' in err && 'string' == typeof err.name) {\n let message = `'${err.name}' captured as exception`;\n if ('message' in err && 'string' == typeof err.message) message += ` with message: '${err.message}'`;\n return message;\n }\n if ('message' in err && 'string' == typeof err.message) return err.message;\n const className = this.getObjectClassName(err);\n const keys = extractExceptionKeysForMessage(err);\n return `${className && 'Object' !== className ? `'${className}'` : 'Object'} captured as exception with keys: ${keys}`;\n }\n isSeverityLevel(x) {\n return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;\n }\n getErrorPropertyFromObject(obj) {\n for(const prop in obj)if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n const value = obj[prop];\n if (isError(value)) return value;\n }\n }\n getObjectClassName(obj) {\n try {\n const prototype = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : void 0;\n } catch (e) {\n return;\n }\n }\n}\nexport { ObjectCoercer };\n", "import { isEvent } from \"../../utils/index.mjs\";\nimport { extractExceptionKeysForMessage } from \"./utils.mjs\";\nclass EventCoercer {\n match(err) {\n return isEvent(err);\n }\n coerce(evt, ctx) {\n const constructorName = evt.constructor.name;\n return {\n type: constructorName,\n value: `${constructorName} captured as exception with keys: ${extractExceptionKeysForMessage(evt)}`,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n}\nexport { EventCoercer };\n", "import { isPrimitive } from \"../../utils/index.mjs\";\nclass PrimitiveCoercer {\n match(candidate) {\n return isPrimitive(candidate);\n }\n coerce(value, ctx) {\n return {\n type: 'Error',\n value: `Primitive value captured as exception: ${String(value)}`,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n}\nexport { PrimitiveCoercer };\n", "import { isBuiltin, isEvent, isPrimitive } from \"../../utils/index.mjs\";\nclass PromiseRejectionEventCoercer {\n match(err) {\n return isBuiltin(err, 'PromiseRejectionEvent') || this.isCustomEventWrappingRejection(err);\n }\n isCustomEventWrappingRejection(err) {\n if (!isEvent(err)) return false;\n try {\n const detail = err.detail;\n return null != detail && 'object' == typeof detail && 'reason' in detail;\n } catch {\n return false;\n }\n }\n coerce(err, ctx) {\n const reason = this.getUnhandledRejectionReason(err);\n if (isPrimitive(reason)) return {\n type: 'UnhandledRejection',\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n return ctx.apply(reason);\n }\n getUnhandledRejectionReason(error) {\n try {\n if ('reason' in error) return error.reason;\n if ('detail' in error && null != error.detail && 'object' == typeof error.detail && 'reason' in error.detail) return error.detail.reason;\n } catch {}\n return error;\n }\n}\nexport { PromiseRejectionEventCoercer };\n", "import Config from '../config'\nimport { isUndefined } from '@posthog/core'\nimport { assignableWindow, window } from './globals'\nimport type { Logger } from '@posthog/core'\n\ntype CreateLoggerOptions = {\n debugEnabled?: boolean\n}\n\ntype PosthogJsLogger = Omit & {\n _log: (level: 'log' | 'warn' | 'error', ...args: any[]) => void\n uninitializedWarning: (methodName: string) => void\n createLogger: (prefix: string, options?: CreateLoggerOptions) => PosthogJsLogger\n}\n\nconst _createLogger = (prefix: string, { debugEnabled }: CreateLoggerOptions = {}): PosthogJsLogger => {\n const logger: PosthogJsLogger = {\n _log: (level: 'log' | 'warn' | 'error', ...args: any[]) => {\n if (\n window &&\n (Config.DEBUG || assignableWindow.POSTHOG_DEBUG || debugEnabled) &&\n !isUndefined(window.console) &&\n window.console\n ) {\n const consoleLog =\n '__rrweb_original__' in window.console[level]\n ? (window.console[level] as any)['__rrweb_original__']\n : window.console[level]\n\n // eslint-disable-next-line no-console\n consoleLog(prefix, ...args)\n }\n },\n\n info: (...args: any[]) => {\n logger._log('log', ...args)\n },\n\n warn: (...args: any[]) => {\n logger._log('warn', ...args)\n },\n\n error: (...args: any[]) => {\n logger._log('error', ...args)\n },\n\n critical: (...args: any[]) => {\n // Critical errors are always logged to the console\n // eslint-disable-next-line no-console\n console.error(prefix, ...args)\n },\n\n uninitializedWarning: (methodName: string) => {\n logger.error(`You must initialize PostHog before calling ${methodName}`)\n },\n\n createLogger: (additionalPrefix: string, options?: CreateLoggerOptions) =>\n _createLogger(`${prefix} ${additionalPrefix}`, options),\n }\n return logger\n}\n\nexport const logger = _createLogger('[PostHog.js]')\n\nexport const createLogger = logger.createLogger\n", "import type { PostHog } from '../posthog-core'\nimport { assignableWindow, document, PostHogExtensionKind } from '../utils/globals'\nimport { createLogger } from '../utils/logger'\n\nconst logger = createLogger('[ExternalScriptsLoader]')\n\nconst loadScript = (posthog: PostHog, url: string, callback: (error?: string | Event, event?: Event) => void) => {\n if (posthog.config.disable_external_dependency_loading) {\n logger.warn(`${url} was requested but loading of external scripts is disabled.`)\n return callback('Loading of external scripts is disabled')\n }\n\n // If we add a script more than once then the browser will parse and execute it\n // So, even if idempotent we waste parsing and processing time\n const existingScripts = document?.querySelectorAll('script')\n if (existingScripts) {\n for (let i = 0; i < existingScripts.length; i++) {\n if (existingScripts[i].src === url) {\n const alreadyExistingScriptTag = existingScripts[i]\n\n if ((alreadyExistingScriptTag as any).__posthog_loading_callback_fired) {\n // script already exists and fired its load event,\n // we call the callback again, they need to be idempotent\n return callback()\n }\n\n // eslint-disable-next-line posthog-js/no-add-event-listener\n alreadyExistingScriptTag.addEventListener('load', (event) => {\n // it hasn't already loaded\n // we probably called loadScript twice in quick succession,\n // so we attach a callback to the onload event\n ;(alreadyExistingScriptTag as any).__posthog_loading_callback_fired = true\n callback(undefined, event)\n })\n alreadyExistingScriptTag.onerror = (error) => callback(error)\n\n return // and finish processing here\n }\n }\n }\n\n const addScript = () => {\n if (!document) {\n return callback('document not found')\n }\n let scriptTag: HTMLScriptElement | null = document.createElement('script')\n scriptTag.type = 'text/javascript'\n scriptTag.crossOrigin = 'anonymous'\n scriptTag.src = url\n scriptTag.onload = (event) => {\n // mark the script as having had its callback fired, so we can avoid double-calling it\n ;(scriptTag as any).__posthog_loading_callback_fired = true\n callback(undefined, event)\n }\n scriptTag.onerror = (error) => callback(error)\n\n if (posthog.config.prepare_external_dependency_script) {\n scriptTag = posthog.config.prepare_external_dependency_script(scriptTag)\n }\n\n if (!scriptTag) {\n return callback('prepare_external_dependency_script returned null')\n }\n\n if (posthog.config.external_scripts_inject_target === 'head') {\n document.head.appendChild(scriptTag)\n } else {\n const scripts = document.querySelectorAll('body > script')\n if (scripts.length > 0) {\n scripts[0].parentNode?.insertBefore(scriptTag, scripts[0])\n } else {\n document.body.appendChild(scriptTag)\n }\n }\n }\n\n if (document?.body) {\n addScript()\n } else {\n // Inlining this because we don't care about `passive: true` here\n // and this saves us ~3% of the bundle size\n // eslint-disable-next-line posthog-js/no-add-event-listener\n document?.addEventListener('DOMContentLoaded', addScript)\n }\n}\n\nassignableWindow.__PosthogExtensions__ = assignableWindow.__PosthogExtensions__ || {}\nassignableWindow.__PosthogExtensions__.loadExternalDependency = (\n posthog: PostHog,\n kind: PostHogExtensionKind,\n callback: (error?: string | Event, event?: Event) => void\n): void => {\n // remote-config always loads from the token-specific path\n if (kind === 'remote-config') {\n const url = posthog.requestRouter.endpointFor('assets', `/array/${posthog.config.token}/config.js`)\n loadScript(posthog, url, callback)\n return\n }\n\n let url: string\n\n if (posthog.config.__preview_external_dependency_versioned_paths) {\n // posthog.version is baked into the executing array.js bundle, so this points at\n // the exact semver-qualified sibling asset without relying on alias redirects.\n url = posthog.requestRouter.endpointFor('assets', `/static/${posthog.version}/${kind}.js`)\n } else {\n let scriptUrlToLoad = `/static/${kind}.js?v=${posthog.version}`\n\n if (kind === 'toolbar') {\n // toolbar.js has a 24-hour CDN TTL but contains a rotating token valid for\n // only 5 minutes. Bust the cache on a 5-minute boundary so the browser always\n // fetches a fresh copy with a valid token.\n const fiveMinutesInMillis = 5 * 60 * 1000\n const timestampToNearestFiveMinutes = Math.floor(Date.now() / fiveMinutesInMillis) * fiveMinutesInMillis\n scriptUrlToLoad = `${scriptUrlToLoad}&t=${timestampToNearestFiveMinutes}`\n }\n\n url = posthog.requestRouter.endpointFor('assets', scriptUrlToLoad)\n }\n\n loadScript(posthog, url, callback)\n}\n\nassignableWindow.__PosthogExtensions__.loadSiteApp = (\n posthog: PostHog,\n url: string,\n callback: (error?: string | Event, event?: Event) => void\n): void => {\n const scriptUrl = posthog.requestRouter.endpointFor('api', url)\n\n loadScript(posthog, scriptUrl, callback)\n}\n", "/*\n * Constants\n */\n\n/* PROPERTY KEYS */\n\n// This key is deprecated, but we want to check for it to see whether aliasing is allowed.\nexport const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id'\nexport const DISTINCT_ID = 'distinct_id'\nexport const DEVICE_ID = '$device_id'\nexport const ALIAS_ID_KEY = '__alias'\nexport const CAMPAIGN_IDS_KEY = '__cmpns'\nexport const EVENT_TIMERS_KEY = '__timers'\nexport const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side'\nexport const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side'\nexport const EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE = '$exception_capture_enabled_server_side'\nexport const ERROR_TRACKING_SUPPRESSION_RULES = '$error_tracking_suppression_rules'\nexport const ERROR_TRACKING_CAPTURE_EXTENSION_EXCEPTIONS = '$error_tracking_capture_extension_exceptions'\nexport const WEB_VITALS_ENABLED_SERVER_SIDE = '$web_vitals_enabled_server_side'\nexport const DEAD_CLICKS_ENABLED_SERVER_SIDE = '$dead_clicks_enabled_server_side'\nexport const PRODUCT_TOURS_ENABLED_SERVER_SIDE = '$product_tours_enabled_server_side'\nexport const WEB_VITALS_ALLOWED_METRICS = '$web_vitals_allowed_metrics'\nexport const SESSION_RECORDING_REMOTE_CONFIG = '$session_recording_remote_config'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = '$console_log_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = '$session_recording_network_payload_capture'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MASKING = '$session_recording_masking'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_CANVAS_RECORDING = '$session_recording_canvas_recording'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SAMPLE_RATE = '$replay_sample_rate'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MINIMUM_DURATION = '$replay_minimum_duration'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SCRIPT_CONFIG = '$replay_script_config'\nexport const SESSION_RECORDING_OVERRIDE_SAMPLING = '$replay_override_sampling'\nexport const SESSION_RECORDING_OVERRIDE_LINKED_FLAG = '$replay_override_linked_flag'\nexport const SESSION_RECORDING_OVERRIDE_URL_TRIGGER = '$replay_override_url_trigger'\nexport const SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER = '$replay_override_event_trigger'\nexport const SESSION_ID = '$sesid'\nexport const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled'\nexport const SESSION_RECORDING_PAST_MINIMUM_DURATION = '$session_past_minimum_duration'\nexport const SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION = '$session_recording_url_trigger_activated_session'\nexport const SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION = '$session_recording_event_trigger_activated_session'\n// V2 Trigger Groups: Per-group persistence key prefixes (suffix with group ID)\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX = '$posthog_sr_group_event_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX = '$posthog_sr_group_url_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX = '$posthog_sr_group_sampling_'\nexport const SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP = '$debug_first_full_snapshot_timestamp'\nexport const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags'\nexport const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features'\nexport const PERSISTENCE_FEATURE_FLAG_DETAILS = '$feature_flag_details'\nexport const PERSISTENCE_FEATURE_FLAG_PAYLOADS = '$feature_flag_payloads'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS = '$override_feature_flag_payloads'\nexport const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties'\nexport const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties'\nexport const SURVEYS = '$surveys'\nexport const SURVEYS_ACTIVATED = '$surveys_activated'\nexport const PRODUCT_TOURS = 'ph_product_tours'\nexport const PRODUCT_TOURS_ACTIVATED = '$product_tours_activated'\nexport const CONVERSATIONS = '$conversations'\nexport const FLAG_CALL_REPORTED = '$flag_call_reported'\nexport const FLAG_CALL_REPORTED_SESSION_ID = '$flag_call_reported_session_id'\nexport const PERSISTENCE_FEATURE_FLAG_ERRORS = '$feature_flag_errors'\nexport const PERSISTENCE_FEATURE_FLAG_EVALUATED_AT = '$feature_flag_evaluated_at'\nexport const USER_STATE = '$user_state'\nexport const CLIENT_SESSION_PROPS = '$client_session_props'\nexport const CAPTURE_RATE_LIMIT = '$capture_rate_limit'\n\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_CAMPAIGN_PARAMS = '$initial_campaign_params'\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_REFERRER_INFO = '$initial_referrer_info'\nexport const INITIAL_PERSON_INFO = '$initial_person_info'\nexport const ENABLE_PERSON_PROCESSING = '$epp'\nexport const TOOLBAR_ID = '__POSTHOG_TOOLBAR__'\nexport const TOOLBAR_CONTAINER_CLASS = 'toolbar-global-fade-container'\n\n/**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * Sentinel value for distinct id, device id, session id. Signals that the server should generate the value\n * */\nexport const COOKIELESS_SENTINEL_VALUE = '$posthog_cookieless'\nexport const COOKIELESS_MODE_FLAG_PROPERTY = '$cookieless_mode'\n\nexport const WEB_EXPERIMENTS = '$web_experiments'\n\n// These are properties that are reserved and will not be automatically included in events\nexport const PERSISTENCE_RESERVED_PROPERTIES = [\n PEOPLE_DISTINCT_ID_KEY,\n ALIAS_ID_KEY,\n CAMPAIGN_IDS_KEY,\n EVENT_TIMERS_KEY,\n SESSION_RECORDING_ENABLED_SERVER_SIDE,\n HEATMAPS_ENABLED_SERVER_SIDE,\n SESSION_ID,\n ENABLED_FEATURE_FLAGS,\n ERROR_TRACKING_SUPPRESSION_RULES,\n USER_STATE,\n PERSISTENCE_EARLY_ACCESS_FEATURES,\n PERSISTENCE_FEATURE_FLAG_DETAILS,\n STORED_GROUP_PROPERTIES_KEY,\n STORED_PERSON_PROPERTIES_KEY,\n SURVEYS,\n FLAG_CALL_REPORTED,\n FLAG_CALL_REPORTED_SESSION_ID,\n PERSISTENCE_FEATURE_FLAG_ERRORS,\n PERSISTENCE_FEATURE_FLAG_EVALUATED_AT,\n CLIENT_SESSION_PROPS,\n CAPTURE_RATE_LIMIT,\n INITIAL_CAMPAIGN_PARAMS,\n INITIAL_REFERRER_INFO,\n ENABLE_PERSON_PROCESSING,\n INITIAL_PERSON_INFO,\n PRODUCT_TOURS,\n PRODUCT_TOURS_ACTIVATED,\n PRODUCT_TOURS_ENABLED_SERVER_SIDE,\n SURVEYS_ACTIVATED,\n SESSION_RECORDING_REMOTE_CONFIG,\n PERSISTENCE_FEATURE_FLAG_PAYLOADS,\n PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS,\n]\n\nexport const SURVEYS_REQUEST_TIMEOUT_MS = 10000\nexport const LOAD_EXT_NOT_FOUND = 'PostHog loadExternalDependency extension not found.'\n\n/* EVENT NAMES - interned to reduce bundle size */\n/* COOKIELESS MODE VALUES */\nexport const COOKIELESS_ON_REJECT = 'on_reject' as const\nexport const COOKIELESS_ALWAYS = 'always' as const\n\n/* USER STATE VALUES */\nexport const USER_STATE_ANONYMOUS = 'anonymous'\nexport const USER_STATE_IDENTIFIED = 'identified'\n\n/* PERSON PROFILE MODES */\nexport const PERSON_PROFILES_IDENTIFIED_ONLY = 'identified_only' as const\n\n/* DOM EVENT NAMES - interned to reduce bundle size */\nexport const DOM_EVENT_VISIBILITYCHANGE = 'visibilitychange'\nexport const DOM_EVENT_BEFOREUNLOAD = 'beforeunload'\n\nexport const EVENT_PAGEVIEW = '$pageview'\nexport const EVENT_PAGELEAVE = '$pageleave'\nexport const EVENT_IDENTIFY = '$identify'\nexport const EVENT_GROUPIDENTIFY = '$groupidentify'\n\n/* Z-INDEX HIERARCHY: tours > surveys > support */\nexport const Z_INDEX_TOURS = 2147483646\nexport const Z_INDEX_SURVEYS = 2147483645\nexport const Z_INDEX_CONVERSATIONS = 2147483644\n", "import { PostHogConfig, Properties } from '../types'\nimport { logger } from './logger'\nimport { isFormData, isNullish, isNumber, isString, hasOwnProperty, isArray } from '@posthog/core'\n\nexport function find(value: T[], predicate: (value: T) => boolean): T | undefined {\n for (let i = 0; i < value.length; i++) {\n if (predicate(value[i])) {\n return value[i]\n }\n }\n return undefined\n}\n\nexport function eachArray(obj: E[] | null | undefined, iterator: (value: E, key: number) => void): void {\n if (isArray(obj)) {\n obj.forEach(iterator)\n }\n}\n\nexport function each(obj: any, iterator: (value: any, key: any) => void): void {\n if (isNullish(obj)) {\n return\n }\n if (isArray(obj)) {\n obj.forEach(iterator)\n return\n }\n if (isFormData(obj)) {\n obj.forEach((val: any, key: any) => iterator(val, key))\n return\n }\n for (const key in obj) {\n if (hasOwnProperty.call(obj, key)) {\n iterator(obj[key], key)\n }\n }\n}\n\nexport const extend = function (obj: Record, ...args: Record[]): Record {\n for (const source of args) {\n for (const prop in source) {\n if (source[prop] !== void 0) {\n obj[prop] = source[prop]\n }\n }\n }\n return obj\n}\n\n/**\n * Object.entries() polyfill\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\n */\nexport function entries(obj: Record): [string, T][] {\n const ownProps = Object.keys(obj)\n let i = ownProps.length\n const resArray = new Array(i) // preallocate the Array\n\n while (i--) {\n resArray[i] = [ownProps[i], obj[ownProps[i]]]\n }\n return resArray\n}\n\nexport const trySafe = function (fn: () => T): T | undefined {\n try {\n return fn()\n } catch {\n return undefined\n }\n}\n\nexport const safewrap = function any = (...args: any[]) => any>(f: F): F {\n return function (...args) {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return f.apply(this, args)\n } catch (e) {\n logger.critical(\n 'Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A.'\n )\n logger.critical(e)\n }\n } as F\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport const safewrapClass = function (klass: Function, functions: string[]): void {\n for (let i = 0; i < functions.length; i++) {\n klass.prototype[functions[i]] = safewrap(klass.prototype[functions[i]])\n }\n}\n\nexport const stripEmptyProperties = function (p: Properties): Properties {\n const ret: Properties = {}\n each(p, function (v, k) {\n if ((isString(v) && v.length > 0) || isNumber(v)) {\n ret[k] = v\n }\n })\n return ret\n}\n\n/**\n * Deep copies an object.\n * It handles cycles by replacing all references to them with `undefined`\n * Also supports customizing native values\n *\n * @param value\n * @param customizer\n * @returns {{}|undefined|*}\n */\nfunction deepCircularCopy = Record>(\n value: T,\n customizer?: (value: T[K], key?: K) => T[K]\n): T | undefined {\n const COPY_IN_PROGRESS_SET = new Set()\n\n function internalDeepCircularCopy(value: T, key?: string): T | undefined {\n if (value !== Object(value)) return customizer ? customizer(value as any, key) : value // primitive value\n\n if (COPY_IN_PROGRESS_SET.has(value)) return undefined\n COPY_IN_PROGRESS_SET.add(value)\n let result: T\n\n if (isArray(value)) {\n result = [] as any as T\n eachArray(value, (it) => {\n result.push(internalDeepCircularCopy(it))\n })\n } else {\n result = {} as T\n each(value, (val, key) => {\n if (!COPY_IN_PROGRESS_SET.has(val)) {\n ;(result as any)[key] = internalDeepCircularCopy(val, key)\n }\n })\n }\n return result\n }\n return internalDeepCircularCopy(value)\n}\n\nexport function _copyAndTruncateStrings = Record>(\n object: T,\n maxStringLength: number\n): T {\n return deepCircularCopy(object, (value: any) => {\n if (isString(value)) {\n return (value as string).slice(0, maxStringLength)\n }\n return value\n }) as T\n}\n\n// NOTE: Update PostHogConfig docs if you change this list\n// We will not try to catch all bullets here, but we should make an effort to catch the most common ones\n// You should be highly against adding more to this list, because ultimately customers can configure\n// their `cross_subdomain_cookie` setting to anything they want.\nconst EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE = ['herokuapp.com', 'vercel.app', 'netlify.app']\nexport function isCrossDomainCookie(documentLocation: Location | undefined) {\n const hostname = documentLocation?.hostname\n\n if (!isString(hostname)) {\n return false\n }\n // split and slice isn't a great way to match arbitrary domains,\n // but it's good enough for ensuring we only match herokuapp.com when it is the TLD\n // for the hostname\n const lastTwoParts = hostname.split('.').slice(-2).join('.')\n\n for (const excluded of EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE) {\n if (lastTwoParts === excluded) {\n return false\n }\n }\n\n return true\n}\n\n// Use this instead of element.addEventListener to avoid eslint errors\n// this properly implements the default options for passive event listeners\nexport function addEventListener(\n element: Window | Document | Element | undefined,\n event: string,\n callback: EventListener,\n options?: AddEventListenerOptions\n): void {\n const { capture = false, passive = true } = options ?? {}\n\n // This is the only place where we are allowed to call this function\n // because the whole idea is that we should be calling this instead of the built-in one\n // eslint-disable-next-line posthog-js/no-add-event-listener\n element?.addEventListener(event, callback, { capture, passive })\n}\n\n/**\n * Helper to migrate deprecated config fields to new field names with appropriate warnings\n * @param config - The config object to check\n * @param newField - The new field name to use\n * @param oldField - The deprecated field name to check for\n * @param defaultValue - The default value if neither field is set\n * @param loggerInstance - Optional logger instance for deprecation warnings\n * @returns The value to use (new field takes precedence over old field)\n */\nexport function migrateConfigField(\n config: Record,\n newField: string,\n oldField: string,\n defaultValue: T,\n loggerInstance?: { warn: (message: string) => void }\n): T {\n const hasNewField = newField in config && !isNullish(config[newField])\n const hasOldField = oldField in config && !isNullish(config[oldField])\n\n if (hasNewField) {\n return config[newField]\n }\n\n if (hasOldField) {\n if (loggerInstance) {\n loggerInstance.warn(\n `Config field '${oldField}' is deprecated. Please use '${newField}' instead. ` +\n `The old field will be removed in a future major version.`\n )\n }\n return config[oldField]\n }\n\n return defaultValue\n}\n\nconst TOOLBAR_INTERNAL_INSTANCE_NAME = 'ph_toolbar_internal'\n\nexport function isToolbarInstance(config: Pick): boolean {\n return config.name === TOOLBAR_INTERNAL_INSTANCE_NAME\n}\n", "/**\n * uuidv7: An experimental implementation of the proposed UUID Version 7\n *\n * @license Apache-2.0\n * @copyright 2021-2023 LiosK\n * @packageDocumentation\n *\n * from https://github.com/LiosK/uuidv7/blob/e501462ea3d23241de13192ceae726956f9b3b7d/src/index.ts\n */\n\n// polyfill for IE11\nimport { window } from './utils/globals'\n\nimport { isNumber, isUndefined } from '@posthog/core'\n\nif (!Math.trunc) {\n Math.trunc = function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v)\n }\n}\n\n// polyfill for IE11\nif (!Number.isInteger) {\n Number.isInteger = function (value) {\n return isNumber(value) && isFinite(value) && Math.floor(value) === value\n }\n}\n\n/** Represents a UUID as a 16-byte byte array. */\nexport class UUID {\n /** @param bytes - The 16-byte byte array representation. */\n constructor(readonly bytes: Readonly) {\n if (bytes.length !== 16) {\n throw new TypeError('not 128-bit length')\n }\n }\n\n /**\n * Builds a byte array from UUIDv7 field values.\n *\n * @param unixTsMs - A 48-bit `unix_ts_ms` field value.\n * @param randA - A 12-bit `rand_a` field value.\n * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.\n * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.\n */\n static fromFieldsV7(unixTsMs: number, randA: number, randBHi: number, randBLo: number): UUID {\n if (\n !Number.isInteger(unixTsMs) ||\n !Number.isInteger(randA) ||\n !Number.isInteger(randBHi) ||\n !Number.isInteger(randBLo) ||\n unixTsMs < 0 ||\n randA < 0 ||\n randBHi < 0 ||\n randBLo < 0 ||\n unixTsMs > 0xffff_ffff_ffff ||\n randA > 0xfff ||\n randBHi > 0x3fff_ffff ||\n randBLo > 0xffff_ffff\n ) {\n throw new RangeError('invalid field value')\n }\n\n const bytes = new Uint8Array(16)\n bytes[0] = unixTsMs / 2 ** 40\n bytes[1] = unixTsMs / 2 ** 32\n bytes[2] = unixTsMs / 2 ** 24\n bytes[3] = unixTsMs / 2 ** 16\n bytes[4] = unixTsMs / 2 ** 8\n bytes[5] = unixTsMs\n bytes[6] = 0x70 | (randA >>> 8)\n bytes[7] = randA\n bytes[8] = 0x80 | (randBHi >>> 24)\n bytes[9] = randBHi >>> 16\n bytes[10] = randBHi >>> 8\n bytes[11] = randBHi\n bytes[12] = randBLo >>> 24\n bytes[13] = randBLo >>> 16\n bytes[14] = randBLo >>> 8\n bytes[15] = randBLo\n return new UUID(bytes)\n }\n\n /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */\n toString(): string {\n let text = ''\n for (let i = 0; i < this.bytes.length; i++) {\n text = text + (this.bytes[i] >>> 4).toString(16) + (this.bytes[i] & 0xf).toString(16)\n if (i === 3 || i === 5 || i === 7 || i === 9) {\n text += '-'\n }\n }\n\n if (text.length !== 36) {\n // We saw one customer whose bundling code was mangling the UUID generation\n // rather than accept a bad UUID, we throw an error here.\n throw new Error('Invalid UUIDv7 was generated')\n }\n return text\n }\n\n /** Creates an object from `this`. */\n clone(): UUID {\n return new UUID(this.bytes.slice(0))\n }\n\n /** Returns true if `this` is equivalent to `other`. */\n equals(other: UUID): boolean {\n return this.compareTo(other) === 0\n }\n\n /**\n * Returns a negative integer, zero, or positive integer if `this` is less\n * than, equal to, or greater than `other`, respectively.\n */\n compareTo(other: UUID): number {\n for (let i = 0; i < 16; i++) {\n const diff = this.bytes[i] - other.bytes[i]\n if (diff !== 0) {\n return Math.sign(diff)\n }\n }\n return 0\n }\n}\n\n/** Encapsulates the monotonic counter state. */\nclass V7Generator {\n private _timestamp = 0\n private _counter = 0\n private readonly _random = new DefaultRandom()\n\n /**\n * Generates a new UUIDv7 object from the current timestamp, or resets the\n * generator upon significant timestamp rollback.\n *\n * This method returns monotonically increasing UUIDs unless the up-to-date\n * timestamp is significantly (by ten seconds or more) smaller than the one\n * embedded in the immediately preceding UUID. If such a significant clock\n * rollback is detected, this method resets the generator and returns a new\n * UUID based on the current timestamp.\n */\n generate(): UUID {\n const value = this.generateOrAbort()\n if (!isUndefined(value)) {\n return value\n } else {\n // reset state and resume\n this._timestamp = 0\n const valueAfterReset = this.generateOrAbort()\n if (isUndefined(valueAfterReset)) {\n throw new Error('Could not generate UUID after timestamp reset')\n }\n return valueAfterReset\n }\n }\n\n /**\n * Generates a new UUIDv7 object from the current timestamp, or returns\n * `undefined` upon significant timestamp rollback.\n *\n * This method returns monotonically increasing UUIDs unless the up-to-date\n * timestamp is significantly (by ten seconds or more) smaller than the one\n * embedded in the immediately preceding UUID. If such a significant clock\n * rollback is detected, this method aborts and returns `undefined`.\n */\n generateOrAbort(): UUID | undefined {\n const MAX_COUNTER = 0x3ff_ffff_ffff\n const ROLLBACK_ALLOWANCE = 10_000 // 10 seconds\n\n const ts = Date.now()\n if (ts > this._timestamp) {\n this._timestamp = ts\n this._resetCounter()\n } else if (ts + ROLLBACK_ALLOWANCE > this._timestamp) {\n // go on with previous timestamp if new one is not much smaller\n this._counter++\n if (this._counter > MAX_COUNTER) {\n // increment timestamp at counter overflow\n this._timestamp++\n this._resetCounter()\n }\n } else {\n // abort if clock went backwards to unbearable extent\n return undefined\n }\n\n return UUID.fromFieldsV7(\n this._timestamp,\n Math.trunc(this._counter / 2 ** 30),\n this._counter & (2 ** 30 - 1),\n this._random.nextUint32()\n )\n }\n\n /** Initializes the counter at a 42-bit random integer. */\n private _resetCounter(): void {\n this._counter = this._random.nextUint32() * 0x400 + (this._random.nextUint32() & 0x3ff)\n }\n}\n\n/** A global flag to force use of cryptographically strong RNG. */\ndeclare const UUIDV7_DENY_WEAK_RNG: boolean\n\n/** Stores `crypto.getRandomValues()` available in the environment. */\nlet getRandomValues: (buffer: T) => T = (buffer) => {\n // fall back on Math.random() unless the flag is set to true\n // TRICKY: don't use the isUndefined method here as can't pass the reference\n if (typeof UUIDV7_DENY_WEAK_RNG !== 'undefined' && UUIDV7_DENY_WEAK_RNG) {\n throw new Error('no cryptographically strong RNG available')\n }\n\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] = Math.trunc(Math.random() * 0x1_0000) * 0x1_0000 + Math.trunc(Math.random() * 0x1_0000)\n }\n return buffer\n}\n\n// detect Web Crypto API\nif (window && !isUndefined(window.crypto) && crypto.getRandomValues) {\n getRandomValues = (buffer) => crypto.getRandomValues(buffer)\n}\n\n/**\n * Wraps `crypto.getRandomValues()` and compatibles to enable buffering; this\n * uses a small buffer by default to avoid unbearable throughput decline in some\n * environments as well as the waste of time and space for unused values.\n */\nclass DefaultRandom {\n private readonly _buffer = new Uint32Array(8)\n private _cursor = Infinity\n nextUint32(): number {\n if (this._cursor >= this._buffer.length) {\n getRandomValues(this._buffer)\n this._cursor = 0\n }\n return this._buffer[this._cursor++]\n }\n}\n\nlet defaultGenerator: V7Generator | undefined\n\n/**\n * Generates a UUIDv7 string.\n *\n * @returns The 8-4-4-4-12 canonical hexadecimal string representation\n * (\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\").\n */\nexport const uuidv7 = (): string => uuidv7obj().toString()\n\n/** Generates a UUIDv7 object. */\nconst uuidv7obj = (): UUID => (defaultGenerator || (defaultGenerator = new V7Generator())).generate()\n\nexport const uuid7ToTimestampMs = (uuid: string): number => {\n // remove hyphens\n const hex = uuid.replace(/-/g, '')\n // ensure that it's a version 7 UUID\n if (hex.length !== 32) {\n throw new Error('Not a valid UUID')\n }\n if (hex[12] !== '7') {\n throw new Error('Not a UUIDv7')\n }\n // the first 6 bytes are the timestamp, which means that we can read only the first 12 hex characters\n return parseInt(hex.substring(0, 12), 16)\n}\n", "import { extend } from './utils'\nimport { PersistentStore, Properties } from './types'\nimport {\n DEVICE_ID,\n DISTINCT_ID,\n ENABLE_PERSON_PROCESSING,\n INITIAL_PERSON_INFO,\n SESSION_ID,\n SESSION_RECORDING_IS_SAMPLED,\n USER_STATE,\n} from './constants'\n\nimport { isNull, isUndefined } from '@posthog/core'\nimport { logger } from './utils/logger'\nimport { window, document } from './utils/globals'\nimport { uuidv7 } from './uuidv7'\n\n// we store the discovered subdomain in memory because it might be read multiple times\nlet firstNonPublicSubDomain = ''\n\n// helper to allow tests to clear this \"cache\"\nexport const resetSubDomainCache = () => {\n firstNonPublicSubDomain = ''\n}\n\n/**\n * Browsers don't offer a way to check if something is a public suffix\n * e.g. `.com.au`, `.io`, `.org.uk`\n *\n * But they do reject cookies set on public suffixes\n * Setting a cookie on `.co.uk` would mean it was sent for every `.co.uk` site visited\n *\n * So, we can use this to check if a domain is a public suffix\n * by trying to set a cookie on a subdomain of the provided hostname\n * until the browser accepts it\n *\n * inspired by https://github.com/AngusFu/browser-root-domain\n */\nexport function seekFirstNonPublicSubDomain(hostname: string, cookieJar = document): string {\n if (firstNonPublicSubDomain) {\n return firstNonPublicSubDomain\n }\n\n if (!cookieJar) {\n return ''\n }\n if (['localhost', '127.0.0.1'].includes(hostname)) return ''\n\n const list = hostname.split('.')\n let len = Math.min(list.length, 8) // paranoia - we know this number should be small\n const key = 'dmn_chk_' + uuidv7()\n\n while (!firstNonPublicSubDomain && len--) {\n const candidate = list.slice(len).join('.')\n const candidateCookieValue = key + '=1;domain=.' + candidate + ';path=/'\n\n // try to set cookie, include a short expiry in seconds since we'll check immediately\n cookieJar.cookie = candidateCookieValue + ';max-age=3'\n\n if (cookieJar.cookie.includes(key)) {\n // the cookie was accepted by the browser, remove the test cookie\n cookieJar.cookie = candidateCookieValue + ';max-age=0'\n firstNonPublicSubDomain = candidate\n }\n }\n\n return firstNonPublicSubDomain\n}\n\nconst DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\\.[a-z]{2,}$/i\nconst originalCookieDomainFn = (hostname: string): string => {\n const matches = hostname.match(DOMAIN_MATCH_REGEX)\n return matches ? matches[0] : ''\n}\n\nexport function chooseCookieDomain(hostname: string, cross_subdomain: boolean | undefined): string {\n if (cross_subdomain) {\n // NOTE: Could we use this for cross domain tracking?\n let matchedSubDomain = seekFirstNonPublicSubDomain(hostname)\n\n if (!matchedSubDomain) {\n const originalMatch = originalCookieDomainFn(hostname)\n if (originalMatch !== matchedSubDomain) {\n logger.info('Warning: cookie subdomain discovery mismatch', originalMatch, matchedSubDomain)\n }\n matchedSubDomain = originalMatch\n }\n\n return matchedSubDomain ? '; domain=.' + matchedSubDomain : ''\n }\n return ''\n}\n\n// Methods partially borrowed from quirksmode.org/js/cookies.html\nexport const cookieStore: PersistentStore = {\n _is_supported: () => !!document,\n\n _error: function (msg) {\n logger.error('cookieStore error: ' + msg)\n },\n\n _get: function (name) {\n if (!document) {\n return\n }\n\n try {\n const nameEQ = name + '='\n const ca = document.cookie.split(';').filter((x) => x.length)\n for (let i = 0; i < ca.length; i++) {\n let c = ca[i]\n while (c.charAt(0) == ' ') {\n c = c.substring(1, c.length)\n }\n if (c.indexOf(nameEQ) === 0) {\n return decodeURIComponent(c.substring(nameEQ.length, c.length))\n }\n }\n } catch {}\n return null\n },\n\n _parse: function (name) {\n let cookie\n try {\n cookie = JSON.parse(cookieStore._get(name)) || {}\n } catch {\n // noop\n }\n return cookie\n },\n\n _set: function (name, value, days, cross_subdomain, is_secure) {\n if (!document) {\n return\n }\n try {\n let expires = '',\n secure = ''\n\n const cdomain = chooseCookieDomain(document.location.hostname, cross_subdomain)\n\n if (days) {\n const date = new Date()\n date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)\n expires = '; expires=' + date.toUTCString()\n }\n\n if (is_secure) {\n secure = '; secure'\n }\n\n const new_cookie_val =\n name +\n '=' +\n encodeURIComponent(JSON.stringify(value)) +\n expires +\n '; SameSite=Lax; path=/' +\n cdomain +\n secure\n\n // 4096 bytes is the size at which some browsers (e.g. firefox) will not store a cookie, warn slightly before that\n if (new_cookie_val.length > 4096 * 0.9) {\n logger.warn('cookieStore warning: large cookie, len=' + new_cookie_val.length)\n }\n\n document.cookie = new_cookie_val\n return new_cookie_val\n } catch {\n return\n }\n },\n\n _remove: function (name, cross_subdomain) {\n if (!document?.cookie) {\n return\n }\n try {\n cookieStore._set(name, '', -1, cross_subdomain)\n } catch {\n return\n }\n },\n}\n\nlet _localStorage_supported: boolean | null = null\nexport const resetLocalStorageSupported = () => {\n _localStorage_supported = null\n}\n\nexport const localStore: PersistentStore = {\n _is_supported: function () {\n if (!isNull(_localStorage_supported)) {\n return _localStorage_supported\n }\n\n let supported = true\n if (!isUndefined(window)) {\n try {\n const key = '__mplssupport__',\n val = 'xyz'\n localStore._set(key, val)\n if (localStore._get(key) !== '\"xyz\"') {\n supported = false\n }\n localStore._remove(key)\n } catch {\n supported = false\n }\n } else {\n supported = false\n }\n if (!supported) {\n logger.error('localStorage unsupported; falling back to cookie store')\n }\n\n _localStorage_supported = supported\n return supported\n },\n\n _error: function (msg) {\n logger.error('localStorage error: ' + msg)\n },\n\n _get: function (name) {\n try {\n return window?.localStorage.getItem(name)\n } catch (err) {\n localStore._error(err)\n }\n return null\n },\n\n _parse: function (name) {\n try {\n return JSON.parse(localStore._get(name)) || {}\n } catch {\n // noop\n }\n return null\n },\n\n _set: function (name, value) {\n try {\n window?.localStorage.setItem(name, JSON.stringify(value))\n } catch (err) {\n localStore._error(err)\n }\n },\n\n _remove: function (name) {\n try {\n window?.localStorage.removeItem(name)\n } catch (err) {\n localStore._error(err)\n }\n },\n}\n\n// Use localstorage for most data but still use cookie for COOKIE_PERSISTED_PROPERTIES\n// This solves issues with cookies having too much data in them causing headers too large\n// Also makes sure we don't have to send a ton of data to the server\nconst COOKIE_PERSISTED_PROPERTIES = [\n DEVICE_ID,\n DISTINCT_ID,\n SESSION_ID,\n SESSION_RECORDING_IS_SAMPLED,\n ENABLE_PERSON_PROCESSING,\n INITIAL_PERSON_INFO,\n USER_STATE,\n]\n\n/**\n * Creates a localPlusCookieStore instance with custom cookie-persisted properties\n */\nexport const createLocalPlusCookieStore = (customCookieProperties: readonly string[] = []): PersistentStore => {\n const cookiePropertiesToPersist = [...COOKIE_PERSISTED_PROPERTIES, ...customCookieProperties]\n\n return {\n ...localStore,\n _parse: function (name) {\n try {\n let cookieProperties: Properties = {}\n try {\n // See if there's a cookie stored with data.\n cookieProperties = cookieStore._parse(name) || {}\n } catch {}\n const value = extend(cookieProperties, JSON.parse(localStore._get(name) || '{}'))\n localStore._set(name, value)\n return value\n } catch {\n // noop\n }\n return null\n },\n\n _set: function (name, value, days, cross_subdomain, is_secure, debug) {\n try {\n localStore._set(name, value, undefined, undefined, debug)\n const cookiePersistedProperties: Record = {}\n cookiePropertiesToPersist.forEach((key) => {\n if (value[key]) {\n cookiePersistedProperties[key] = value[key]\n }\n })\n\n if (Object.keys(cookiePersistedProperties).length) {\n cookieStore._set(name, cookiePersistedProperties, days, cross_subdomain, is_secure, debug)\n }\n } catch (err) {\n localStore._error(err)\n }\n },\n\n _remove: function (name, cross_subdomain) {\n try {\n window?.localStorage.removeItem(name)\n cookieStore._remove(name, cross_subdomain)\n } catch (err) {\n localStore._error(err)\n }\n },\n }\n}\n\nconst memoryStorage: Properties = {}\n\n// Storage that only lasts the length of the pageview if we don't want to use cookies\nexport const memoryStore: PersistentStore = {\n _is_supported: function () {\n return true\n },\n\n _error: function (msg) {\n logger.error('memoryStorage error: ' + msg)\n },\n\n _get: function (name) {\n return memoryStorage[name] || null\n },\n\n _parse: function (name) {\n return memoryStorage[name] || null\n },\n\n _set: function (name, value) {\n memoryStorage[name] = value\n },\n\n _remove: function (name) {\n delete memoryStorage[name]\n },\n}\n\nlet sessionStorageSupported: boolean | null = null\nexport const resetSessionStorageSupported = () => {\n sessionStorageSupported = null\n}\n// Storage that only lasts the length of a tab/window. Survives page refreshes\nexport const sessionStore: PersistentStore = {\n _is_supported: function () {\n if (!isNull(sessionStorageSupported)) {\n return sessionStorageSupported\n }\n sessionStorageSupported = true\n if (!isUndefined(window)) {\n try {\n const key = '__support__',\n val = 'xyz'\n sessionStore._set(key, val)\n if (sessionStore._get(key) !== '\"xyz\"') {\n sessionStorageSupported = false\n }\n sessionStore._remove(key)\n } catch {\n sessionStorageSupported = false\n }\n } else {\n sessionStorageSupported = false\n }\n return sessionStorageSupported\n },\n\n _error: function (msg) {\n logger.error('sessionStorage error: ', msg)\n },\n\n _get: function (name) {\n try {\n return window?.sessionStorage.getItem(name)\n } catch (err) {\n sessionStore._error(err)\n }\n return null\n },\n\n _parse: function (name) {\n try {\n return JSON.parse(sessionStore._get(name)) || null\n } catch {\n // noop\n }\n return null\n },\n\n _set: function (name, value) {\n try {\n window?.sessionStorage.setItem(name, JSON.stringify(value))\n } catch (err) {\n sessionStore._error(err)\n }\n },\n\n _remove: function (name) {\n try {\n window?.sessionStorage.removeItem(name)\n } catch (err) {\n sessionStore._error(err)\n }\n },\n}\n", "import { PostHog } from './posthog-core'\nimport { COOKIELESS_ALWAYS, COOKIELESS_ON_REJECT } from './constants'\nimport { assignableWindow, navigator } from './utils/globals'\nimport { cookieStore, localStore } from './storage'\nimport { PersistentStore } from './types'\nimport { isNoLike, isYesLike } from '@posthog/core'\n\nconst OPT_OUT_PREFIX = '__ph_opt_in_out_'\n\nexport const ConsentStatus = {\n PENDING: -1,\n DENIED: 0,\n GRANTED: 1,\n} as const\nexport type ConsentStatus = (typeof ConsentStatus)[keyof typeof ConsentStatus]\n\n/**\n * ConsentManager provides tools for managing user consent as configured by the application.\n */\nexport class ConsentManager {\n private _persistentStore?: PersistentStore\n\n constructor(private _instance: PostHog) {}\n\n private get _config() {\n return this._instance.config\n }\n\n public get consent(): ConsentStatus {\n if (this._getDnt()) {\n return ConsentStatus.DENIED\n }\n\n return this._storedConsent\n }\n\n public isOptedOut() {\n if (this._config.cookieless_mode === COOKIELESS_ALWAYS) {\n return true\n }\n // we are opted out if:\n // * consent is explicitly denied\n // * consent is pending, and we are configured to opt out by default\n // * consent is pending, and we are in cookieless mode \"on_reject\"\n return (\n this.consent === ConsentStatus.DENIED ||\n (this.consent === ConsentStatus.PENDING &&\n (this._config.opt_out_capturing_by_default || this._config.cookieless_mode === COOKIELESS_ON_REJECT))\n )\n }\n\n public isOptedIn() {\n return !this.isOptedOut()\n }\n\n public isExplicitlyOptedOut() {\n return this.consent === ConsentStatus.DENIED\n }\n\n public optInOut(isOptedIn: boolean) {\n this._storage._set(\n this._storageKey,\n isOptedIn ? 1 : 0,\n this._config.cookie_expiration,\n this._config.cross_subdomain_cookie,\n this._config.secure_cookie\n )\n }\n\n public reset() {\n this._storage._remove(this._storageKey, this._config.cross_subdomain_cookie)\n }\n\n private get _storageKey() {\n const { token, opt_out_capturing_cookie_prefix, consent_persistence_name } = this._instance.config\n if (consent_persistence_name) {\n return consent_persistence_name\n } else if (opt_out_capturing_cookie_prefix) {\n // Deprecated, but we still support it for backwards compatibility.\n // This was deprecated because it differed in behaviour from storage.ts, and appends the token.\n // This meant it was not possible to share the same consent state across multiple PostHog instances,\n // and made it harder for people to migrate from other systems.\n return opt_out_capturing_cookie_prefix + token\n } else {\n return OPT_OUT_PREFIX + token\n }\n }\n\n private get _storedConsent(): ConsentStatus {\n const value = this._storage._get(this._storageKey)\n // be somewhat permissive in what we accept as yes/opt-in, to make it easier for people to migrate from other systems\n return isYesLike(value) ? ConsentStatus.GRANTED : isNoLike(value) ? ConsentStatus.DENIED : ConsentStatus.PENDING\n }\n\n private get _storage() {\n // Re-evaluate the store on every access so that a config change after the first\n // access (e.g. init() called after _dom_loaded() fires in bundled apps) is picked\n // up and any value already stored under the old backend is migrated across.\n const persistenceType = this._config.opt_out_capturing_persistence_type\n const expectedStore = persistenceType === 'localStorage' ? localStore : cookieStore\n\n if (!this._persistentStore || this._persistentStore !== expectedStore) {\n this._persistentStore = expectedStore\n const otherStorage = persistenceType === 'localStorage' ? cookieStore : localStore\n\n if (otherStorage._get(this._storageKey)) {\n if (!this._persistentStore._get(this._storageKey)) {\n // This indicates we have moved to a new storage format so we migrate the value over\n this.optInOut(isYesLike(otherStorage._get(this._storageKey)))\n }\n\n otherStorage._remove(this._storageKey, this._config.cross_subdomain_cookie)\n }\n }\n\n return this._persistentStore\n }\n\n private _getDnt(): boolean {\n if (!this._config.respect_dnt) {\n return false\n }\n return [\n navigator?.doNotTrack, // standard\n (navigator as any)?.['msDoNotTrack'],\n assignableWindow['doNotTrack'],\n ].some((dntValue) => isYesLike(dntValue))\n }\n}\n", "import { PostHog } from '../posthog-core'\nimport { DEAD_CLICKS_ENABLED_SERVER_SIDE } from '../constants'\nimport { isBoolean, isObject } from '@posthog/core'\nimport { assignableWindow, document, LazyLoadedDeadClicksAutocaptureInterface } from '../utils/globals'\nimport { createLogger } from '../utils/logger'\nimport { DeadClicksAutoCaptureConfig, RemoteConfig } from '../types'\nimport type { Extension } from './types'\n\nconst logger = createLogger('[Dead Clicks]')\n\nexport const isDeadClicksEnabledForHeatmaps = () => {\n return true\n}\nexport const isDeadClicksEnabledForAutocapture = (instance: DeadClicksAutocapture) => {\n const isRemoteEnabled = !!instance.instance.persistence?.get_property(DEAD_CLICKS_ENABLED_SERVER_SIDE)\n const clientConfig = instance.instance.config.capture_dead_clicks\n if (isBoolean(clientConfig)) {\n return clientConfig\n }\n if (isObject(clientConfig)) {\n return true\n }\n return isRemoteEnabled\n}\n\nexport class DeadClicksAutocapture implements Extension {\n get lazyLoadedDeadClicksAutocapture(): LazyLoadedDeadClicksAutocaptureInterface | undefined {\n return this._lazyLoadedDeadClicksAutocapture\n }\n\n private _lazyLoadedDeadClicksAutocapture: LazyLoadedDeadClicksAutocaptureInterface | undefined\n\n constructor(\n readonly instance: PostHog,\n readonly isEnabled: (dca: DeadClicksAutocapture) => boolean,\n readonly onCapture?: DeadClicksAutoCaptureConfig['__onCapture']\n ) {\n this.startIfEnabledOrStop()\n }\n\n public onRemoteConfig(response: RemoteConfig) {\n if (!('captureDeadClicks' in response)) {\n return\n }\n\n if (this.instance.persistence) {\n this.instance.persistence.register({\n [DEAD_CLICKS_ENABLED_SERVER_SIDE]: response.captureDeadClicks,\n })\n }\n this.startIfEnabledOrStop()\n }\n\n public startIfEnabledOrStop() {\n if (this.isEnabled(this)) {\n this._loadScript(() => {\n this._start()\n })\n } else {\n this.stop()\n }\n }\n\n private _loadScript(cb: () => void): void {\n if (assignableWindow.__PosthogExtensions__?.initDeadClicksAutocapture) {\n // already loaded\n cb()\n }\n assignableWindow.__PosthogExtensions__?.loadExternalDependency?.(\n this.instance,\n 'dead-clicks-autocapture',\n (err) => {\n if (err) {\n logger.error('failed to load script', err)\n return\n }\n cb()\n }\n )\n }\n\n private _start() {\n if (!document) {\n logger.error('`document` not found. Cannot start.')\n return\n }\n\n if (\n !this._lazyLoadedDeadClicksAutocapture &&\n assignableWindow.__PosthogExtensions__?.initDeadClicksAutocapture\n ) {\n const config = isObject(this.instance.config.capture_dead_clicks)\n ? this.instance.config.capture_dead_clicks\n : {}\n config.__onCapture = this.onCapture\n\n this._lazyLoadedDeadClicksAutocapture = assignableWindow.__PosthogExtensions__.initDeadClicksAutocapture(\n this.instance,\n config\n )\n this._lazyLoadedDeadClicksAutocapture.start(document)\n logger.info(`starting...`)\n }\n }\n\n stop() {\n if (this._lazyLoadedDeadClicksAutocapture) {\n this._lazyLoadedDeadClicksAutocapture.stop()\n this._lazyLoadedDeadClicksAutocapture = undefined\n logger.info(`stopping...`)\n }\n }\n}\n", "/**\n * Extend Segment with extra PostHog JS functionality. Required for things like Recordings and feature flags to work correctly.\n *\n * ### Usage\n *\n * ```js\n * // After your standard segment anyalytics install\n * analytics.load(\"GOEDfA21zZTtR7clsBuDvmBKAtAdZ6Np\");\n *\n * analytics.ready(() => {\n * posthog.init('', {\n * capture_pageview: false,\n * segment: window.analytics, // NOTE: Be sure to use window.analytics here!\n * });\n * window.analytics.page();\n * })\n * ```\n */\nimport { PostHog } from '../posthog-core'\nimport { createLogger } from '../utils/logger'\n\nimport { EVENT_IDENTIFY, EVENT_PAGEVIEW, USER_STATE, USER_STATE_IDENTIFIED } from '../constants'\nimport { isFunction } from '@posthog/core'\nimport { uuidv7 } from '../uuidv7'\n\nimport type { SegmentUser, SegmentAnalytics, SegmentContext, SegmentPlugin } from '@posthog/types'\n\n// Re-export for backwards compatibility\nexport type { SegmentUser, SegmentAnalytics, SegmentContext, SegmentPlugin }\n\nconst logger = createLogger('[SegmentIntegration]')\n\nconst createSegmentIntegration = (posthog: PostHog): SegmentPlugin => {\n if (!Promise || !Promise.resolve) {\n logger.warn('This browser does not have Promise support, and can not use the segment integration')\n }\n\n const enrichEvent = (ctx: SegmentContext, eventName: string | undefined) => {\n if (!eventName) {\n return ctx\n }\n if (!ctx.event.userId && ctx.event.anonymousId !== posthog.get_distinct_id()) {\n // This is our only way of detecting that segment's analytics.reset() has been called so we also call it\n logger.info('No userId set, resetting PostHog')\n posthog.reset()\n }\n if (ctx.event.userId && ctx.event.userId !== posthog.get_distinct_id()) {\n logger.info('UserId set, identifying with PostHog')\n posthog.identify(ctx.event.userId)\n }\n\n const additionalProperties = posthog.calculateEventProperties(eventName, ctx.event.properties)\n ctx.event.properties = Object.assign({}, additionalProperties, ctx.event.properties)\n return ctx\n }\n\n return {\n name: 'PostHog JS',\n type: 'enrichment',\n version: '1.0.0',\n isLoaded: () => true,\n // check and early return above\n // eslint-disable-next-line compat/compat\n load: () => Promise.resolve(),\n track: (ctx) => enrichEvent(ctx, ctx.event.event),\n page: (ctx) => enrichEvent(ctx, EVENT_PAGEVIEW),\n identify: (ctx) => enrichEvent(ctx, EVENT_IDENTIFY),\n screen: (ctx) => enrichEvent(ctx, '$screen'),\n }\n}\n\nfunction setupPostHogFromSegment(posthog: PostHog, done: () => void) {\n const segment = posthog.config.segment\n if (!segment) {\n return done()\n }\n\n const bootstrapUser = (user: SegmentUser) => {\n // Use segments anonymousId instead\n const getSegmentAnonymousId = () => user.anonymousId() || uuidv7()\n posthog.config.get_device_id = getSegmentAnonymousId\n\n // If a segment user ID exists, set it as the distinct_id\n if (user.id()) {\n posthog.register({\n distinct_id: user.id(),\n $device_id: getSegmentAnonymousId(),\n })\n posthog.persistence!.set_property(USER_STATE, USER_STATE_IDENTIFIED)\n }\n\n done()\n }\n\n const segmentUser = segment.user()\n if ('then' in segmentUser && isFunction(segmentUser.then)) {\n segmentUser.then(bootstrapUser)\n } else {\n bootstrapUser(segmentUser as SegmentUser)\n }\n}\n\nexport function setupSegmentIntegration(posthog: PostHog, done: () => void) {\n const segment = posthog.config.segment\n if (!segment) {\n return done()\n }\n\n setupPostHogFromSegment(posthog, () => {\n segment.register(createSegmentIntegration(posthog)).then(() => {\n done()\n })\n })\n}\n", "/**\n * Integrate Sentry with PostHog. This will add a direct link to the person in Sentry, and an $exception event in PostHog\n *\n * ### Usage\n *\n * Sentry.init({\n * dsn: 'https://example',\n * integrations: [\n * new posthog.SentryIntegration(posthog)\n * ]\n * })\n *\n * @param {Object} [posthog] The posthog object\n * @param {string} [organization] Optional: The Sentry organization, used to send a direct link from PostHog to Sentry\n * @param {Number} [projectId] Optional: The Sentry project id, used to send a direct link from PostHog to Sentry\n * @param {string} [prefix] Optional: Url of a self-hosted sentry instance (default: https://sentry.io/organizations/)\n * @param {SeverityLevel[] | '*'} [severityAllowList] Optional: send events matching the provided levels. Use '*' to send all events (default: ['error'])\n * @param {boolean} [sendExceptionsToPostHog] Optional: capture exceptions as events in PostHog (default: true)\n */\n\nimport { PostHog } from '../posthog-core'\nimport { SeverityLevel } from '../types'\n\n// NOTE - we can't import from @sentry/types because it changes frequently and causes clashes\n// We only use a small subset of the types, so we can just define the integration overall and use any for the rest\n\n// import {\n// Event as _SentryEvent,\n// EventProcessor as _SentryEventProcessor,\n// Hub as _SentryHub,\n// Integration as _SentryIntegration,\n// SeverityLevel as _SeverityLevel,\n// IntegrationClass as _SentryIntegrationClass,\n// } from '@sentry/types'\n\n// Uncomment the above and comment the below to get type checking for development\n\ntype _SentryEvent = any\ntype _SentryException = any\ntype _SentryEventProcessor = any\ntype _SentryHub = any\n\ninterface _SentryIntegration {\n name: string\n processEvent(event: _SentryEvent): _SentryEvent\n}\n\ninterface _SentryIntegrationClass {\n name: string\n setupOnce(addGlobalEventProcessor: (callback: _SentryEventProcessor) => void, getCurrentHub: () => _SentryHub): void\n}\n\ninterface SentryExceptionProperties {\n $sentry_event_id: any\n $sentry_exception: any\n $sentry_exception_message: any\n $sentry_exception_type: any\n $sentry_tags: any\n $sentry_url?: string\n}\n\nexport type SentryIntegrationOptions = {\n organization?: string\n projectId?: number\n prefix?: string\n severityAllowList?: SeverityLevel[] | '*'\n sendExceptionsToPostHog?: boolean\n}\n\nconst NAME = 'posthog-js'\n\nexport function createEventProcessor(\n _posthog: PostHog,\n {\n organization,\n projectId,\n prefix,\n severityAllowList = ['error'],\n sendExceptionsToPostHog = true,\n }: SentryIntegrationOptions = {}\n): (event: _SentryEvent) => _SentryEvent {\n return (event) => {\n const shouldProcessLevel = severityAllowList === '*' || severityAllowList.includes(event.level as SeverityLevel)\n if (!shouldProcessLevel || !_posthog.__loaded) return event\n if (!event.tags) event.tags = {}\n\n const personUrl = _posthog.requestRouter.endpointFor(\n 'ui',\n `/project/${_posthog.config.token}/person/${_posthog.get_distinct_id()}`\n )\n event.tags['PostHog Person URL'] = personUrl\n if (_posthog.sessionRecordingStarted()) {\n event.tags['PostHog Recording URL'] = _posthog.get_session_replay_url({ withTimestamp: true })\n }\n\n const exceptions: _SentryException[] = event.exception?.values || []\n\n const exceptionList = exceptions.map((exception) => {\n return {\n ...exception,\n stacktrace: exception.stacktrace\n ? {\n ...exception.stacktrace,\n type: 'raw',\n frames: (exception.stacktrace.frames || []).map((frame: any) => {\n return { ...frame, platform: 'web:javascript' }\n }),\n }\n : undefined,\n }\n })\n\n const data: SentryExceptionProperties & {\n // two properties added to match any exception auto-capture\n // added manually to avoid any dependency on the lazily loaded content\n $exception_message: any\n $exception_type: any\n $exception_list: any\n $exception_level: SeverityLevel\n } = {\n // PostHog Exception Properties,\n $exception_message: exceptions[0]?.value || event.message,\n $exception_type: exceptions[0]?.type,\n $exception_level: event.level,\n $exception_list: exceptionList,\n // Sentry Exception Properties\n $sentry_event_id: event.event_id,\n $sentry_exception: event.exception,\n $sentry_exception_message: exceptions[0]?.value || event.message,\n $sentry_exception_type: exceptions[0]?.type,\n $sentry_tags: event.tags,\n }\n\n if (organization && projectId) {\n data['$sentry_url'] =\n (prefix || 'https://sentry.io/organizations/') +\n organization +\n '/issues/?project=' +\n projectId +\n '&query=' +\n event.event_id\n }\n\n if (sendExceptionsToPostHog) {\n _posthog.exceptions?.sendExceptionEvent(data)\n }\n\n return event\n }\n}\n\n// V8 integration - function based\nexport function sentryIntegration(_posthog: PostHog, options?: SentryIntegrationOptions): _SentryIntegration {\n const processor = createEventProcessor(_posthog, options)\n return {\n name: NAME,\n processEvent(event) {\n return processor(event)\n },\n }\n}\n// V7 integration - class based\nexport class SentryIntegration implements _SentryIntegrationClass {\n name: string\n\n setupOnce: (\n addGlobalEventProcessor: (callback: _SentryEventProcessor) => void,\n getCurrentHub: () => _SentryHub\n ) => void\n\n constructor(\n _posthog: PostHog,\n organization?: string,\n projectId?: number,\n prefix?: string,\n severityAllowList?: SeverityLevel[] | '*',\n sendExceptionsToPostHog?: boolean\n ) {\n // setupOnce gets called by Sentry when it intializes the plugin\n this.name = NAME\n this.setupOnce = function (addGlobalEventProcessor: (callback: _SentryEventProcessor) => void) {\n addGlobalEventProcessor(\n createEventProcessor(_posthog, {\n organization,\n projectId,\n prefix,\n severityAllowList,\n sendExceptionsToPostHog: sendExceptionsToPostHog ?? true,\n })\n )\n }\n }\n}\n", "import { window } from './utils/globals'\nimport { PostHog } from './posthog-core'\nimport { clampToRange, isUndefined } from '@posthog/core'\nimport { extend } from './utils'\nimport { logger } from './utils/logger'\nimport { SessionIdChangedCallback } from './types'\n\ninterface PageViewEventProperties {\n $pageview_id?: string\n $prev_pageview_id?: string\n $prev_pageview_pathname?: string\n $prev_pageview_duration?: number // seconds\n $prev_pageview_last_scroll?: number\n $prev_pageview_last_scroll_percentage?: number\n $prev_pageview_max_scroll?: number\n $prev_pageview_max_scroll_percentage?: number\n $prev_pageview_last_content?: number\n $prev_pageview_last_content_percentage?: number\n $prev_pageview_max_content?: number\n $prev_pageview_max_content_percentage?: number\n}\n\n// This keeps track of the PageView state (such as the previous PageView's path, timestamp, id, and scroll properties).\n// We store the state in memory, which means that for non-SPA sites, the state will be lost on page reload. This means\n// that non-SPA sites should always send a $pageleave event on any navigation, before the page unloads. For SPA sites,\n// they only need to send a $pageleave event when the user navigates away from the site, as the information is not lost\n// on an internal navigation, and is included as the $prev_pageview_ properties in the next $pageview event.\n\n// Practically, this means that to find the scroll properties for a given pageview, you need to find the event where\n// event name is $pageview or $pageleave and where $prev_pageview_id matches the original pageview event's id.\n\nexport class PageViewManager {\n _currentPageview?: { timestamp: Date; pageViewId: string | undefined; pathname: string | undefined }\n _instance: PostHog\n private _unsubscribeSessionId?: () => void\n\n constructor(instance: PostHog) {\n this._instance = instance\n this._setupSessionRotationHandler()\n }\n\n private _setupSessionRotationHandler(): void {\n this._unsubscribeSessionId = this._instance.sessionManager?.onSessionId(this._onSessionIdChange)\n }\n\n private _onSessionIdChange: SessionIdChangedCallback = (sessionId, _windowId, changeReason) => {\n // Only act on actual session rotations, not initial session creation\n if (!changeReason) {\n return\n }\n\n // Clear state when session changes for any of these reasons:\n // - noSessionId: after posthog.reset() or forced idle reset\n // - activityTimeout: 30 min idle (default, configurable up to 10 hours)\n // - sessionPastMaximumLength: 24 hour max session\n if (changeReason.noSessionId || changeReason.activityTimeout || changeReason.sessionPastMaximumLength) {\n logger.info('[PageViewManager] Session rotated, clearing pageview state', {\n sessionId,\n changeReason,\n })\n this._currentPageview = undefined\n this._instance.scrollManager.resetContext()\n }\n }\n\n destroy(): void {\n this._unsubscribeSessionId?.()\n this._unsubscribeSessionId = undefined\n }\n\n doPageView(timestamp: Date, pageViewId?: string): PageViewEventProperties {\n const response = this._previousPageViewProperties(timestamp, pageViewId)\n\n // On a pageview we reset the contexts\n this._currentPageview = { pathname: window?.location.pathname ?? '', pageViewId, timestamp }\n this._instance.scrollManager.resetContext()\n\n return response\n }\n\n doPageLeave(timestamp: Date): PageViewEventProperties {\n return this._previousPageViewProperties(timestamp, this._currentPageview?.pageViewId)\n }\n\n doEvent(): PageViewEventProperties {\n return { $pageview_id: this._currentPageview?.pageViewId }\n }\n\n private _previousPageViewProperties(timestamp: Date, pageviewId: string | undefined): PageViewEventProperties {\n const previousPageView = this._currentPageview\n\n if (!previousPageView) {\n return { $pageview_id: pageviewId }\n }\n\n let properties: PageViewEventProperties = {\n $pageview_id: pageviewId,\n $prev_pageview_id: previousPageView.pageViewId,\n }\n\n const scrollContext = this._instance.scrollManager.getContext()\n\n if (scrollContext && !this._instance.config.disable_scroll_properties) {\n let { maxScrollHeight, lastScrollY, maxScrollY, maxContentHeight, lastContentY, maxContentY } =\n scrollContext\n\n if (\n !isUndefined(maxScrollHeight) &&\n !isUndefined(lastScrollY) &&\n !isUndefined(maxScrollY) &&\n !isUndefined(maxContentHeight) &&\n !isUndefined(lastContentY) &&\n !isUndefined(maxContentY)\n ) {\n // Use ceil, so that e.g. scrolling 999.5px of a 1000px page is considered 100% scrolled\n maxScrollHeight = Math.ceil(maxScrollHeight)\n lastScrollY = Math.ceil(lastScrollY)\n maxScrollY = Math.ceil(maxScrollY)\n maxContentHeight = Math.ceil(maxContentHeight)\n lastContentY = Math.ceil(lastContentY)\n maxContentY = Math.ceil(maxContentY)\n\n // if the maximum scroll height is near 0, then the percentage is 1\n const lastScrollPercentage =\n maxScrollHeight <= 1 ? 1 : clampToRange(lastScrollY / maxScrollHeight, 0, 1, logger)\n const maxScrollPercentage =\n maxScrollHeight <= 1 ? 1 : clampToRange(maxScrollY / maxScrollHeight, 0, 1, logger)\n const lastContentPercentage =\n maxContentHeight <= 1 ? 1 : clampToRange(lastContentY / maxContentHeight, 0, 1, logger)\n const maxContentPercentage =\n maxContentHeight <= 1 ? 1 : clampToRange(maxContentY / maxContentHeight, 0, 1, logger)\n\n properties = extend(properties, {\n $prev_pageview_last_scroll: lastScrollY,\n $prev_pageview_last_scroll_percentage: lastScrollPercentage,\n $prev_pageview_max_scroll: maxScrollY,\n $prev_pageview_max_scroll_percentage: maxScrollPercentage,\n $prev_pageview_last_content: lastContentY,\n $prev_pageview_last_content_percentage: lastContentPercentage,\n $prev_pageview_max_content: maxContentY,\n $prev_pageview_max_content_percentage: maxContentPercentage,\n })\n }\n }\n\n if (previousPageView.pathname) {\n properties.$prev_pageview_pathname = previousPageView.pathname\n }\n if (previousPageView.timestamp) {\n // Use seconds, for consistency with our other duration-related properties like $duration\n properties.$prev_pageview_duration = (timestamp.getTime() - previousPageView.timestamp.getTime()) / 1000\n }\n\n return properties\n }\n}\n", "import { each } from './'\n\nimport { isArray, isFile, isUndefined } from '@posthog/core'\nimport { logger } from './logger'\nimport { document } from './globals'\n\nconst localDomains = ['localhost', '127.0.0.1']\n\n/**\n * IE11 doesn't support `new URL`\n * so we can create an anchor element and use that to parse the URL\n * there's a lot of overlap between HTMLHyperlinkElementUtils and URL\n * meaning useful properties like `pathname` are available on both\n */\nexport const convertToURL = (url: string): HTMLAnchorElement | null => {\n const location = document?.createElement('a')\n if (isUndefined(location)) {\n return null\n }\n\n location.href = url\n return location\n}\n\nexport const formDataToQuery = function (formdata: Record | FormData, arg_separator = '&'): string {\n let use_val: string\n let use_key: string\n const tph_arr: string[] = []\n\n each(formdata, function (val: File | string | undefined, key: string | undefined) {\n // the key might be literally the string undefined for e.g. if {undefined: 'something'}\n if (isUndefined(val) || isUndefined(key) || key === 'undefined') {\n return\n }\n\n use_val = encodeURIComponent(isFile(val) ? val.name : val.toString())\n use_key = encodeURIComponent(key)\n tph_arr[tph_arr.length] = use_key + '=' + use_val\n })\n\n return tph_arr.join(arg_separator)\n}\n\nexport const getQueryParam = function (url: string, param: string): string {\n const withoutHash: string = url.split('#')[0] || ''\n\n // Split only on the first ? to sort problem out for those with multiple ?s\n // and then remove them\n const queryParams: string = withoutHash.split(/\\?(.*)/)[1] || ''\n const cleanedQueryParams = queryParams.replace(/^\\?+/g, '')\n\n const queryParts = cleanedQueryParams.split('&')\n let keyValuePair\n\n for (let i = 0; i < queryParts.length; i++) {\n const parts = queryParts[i].split('=')\n if (parts[0] === param) {\n keyValuePair = parts\n break\n }\n }\n\n if (!isArray(keyValuePair) || keyValuePair.length < 2) {\n return ''\n } else {\n let result = keyValuePair[1]\n try {\n result = decodeURIComponent(result)\n } catch {\n logger.error('Skipping decoding for malformed query param: ' + result)\n }\n return result.replace(/\\+/g, ' ')\n }\n}\n\n// replace any query params in the url with the provided mask value. Tries to keep the URL as instant as possible,\n// including preserving malformed text in most cases\nexport const maskQueryParams = function (\n url: T,\n maskedParams: string[] | undefined,\n mask: string\n): T extends string ? string : undefined {\n if (!url || !maskedParams || !maskedParams.length) {\n return url as any\n }\n\n const splitHash = url.split('#')\n const withoutHash: string = splitHash[0] || ''\n const hash = splitHash[1]\n\n const splitQuery: string[] = withoutHash.split('?')\n const queryString: string = splitQuery[1]\n const urlWithoutQueryAndHash: string = splitQuery[0]\n const queryParts = (queryString || '').split('&')\n\n // use an array of strings rather than an object to preserve ordering and duplicates\n const paramStrings: string[] = []\n\n for (let i = 0; i < queryParts.length; i++) {\n const keyValuePair = queryParts[i].split('=')\n if (!isArray(keyValuePair)) {\n continue\n } else if (maskedParams.includes(keyValuePair[0])) {\n paramStrings.push(keyValuePair[0] + '=' + mask)\n } else {\n paramStrings.push(queryParts[i])\n }\n }\n\n let result = urlWithoutQueryAndHash\n if (queryString != null) {\n result += '?' + paramStrings.join('&')\n }\n if (hash != null) {\n result += '#' + hash\n }\n\n return result as any\n}\n\nexport const _getHashParam = function (hash: string, param: string): string | null {\n const matches = hash.match(new RegExp(param + '=([^&]*)'))\n return matches ? matches[1] : null\n}\n\nexport const isLocalhost = (): boolean => {\n return localDomains.includes(location.hostname)\n}\n", "import { convertToURL, getQueryParam, maskQueryParams } from './request-utils'\nimport { isNull, stripLeadingDollar } from '@posthog/core'\nimport { Properties } from '../types'\nimport Config from '../config'\nimport { each, extend, stripEmptyProperties } from './index'\nimport { document, location, userAgent, window } from './globals'\nimport { detectBrowser, detectBrowserVersion, detectDevice, detectDeviceType, detectOS } from '@posthog/core'\nimport { cookieStore } from '../storage'\n\nconst URL_REGEX_PREFIX = 'https?://(.*)'\n\n// CAMPAIGN_PARAMS and EVENT_TO_PERSON_PROPERTIES should be kept in sync with\n// https://github.com/PostHog/posthog/blob/master/plugin-server/src/utils/db/utils.ts#L60\n\n// The list of campaign parameters that could be considered personal data under e.g. GDPR.\n// These can be masked in URLs and properties before being sent to posthog.\nexport const PERSONAL_DATA_CAMPAIGN_PARAMS = [\n 'gclid', // google ads\n 'gclsrc', // google ads 360\n 'dclid', // google display ads\n 'gbraid', // google ads, web to app\n 'wbraid', // google ads, app to web\n 'fbclid', // facebook\n 'msclkid', // microsoft\n 'twclid', // twitter\n 'li_fat_id', // linkedin\n 'igshid', // instagram\n 'ttclid', // tiktok\n 'rdt_cid', // reddit\n 'epik', // pinterest\n 'qclid', // quora\n 'sccid', // snapchat\n 'irclid', // impact\n '_kx', // klaviyo\n]\n\nexport const CAMPAIGN_PARAMS = [\n 'utm_source',\n 'utm_medium',\n 'utm_campaign',\n 'utm_content',\n 'utm_term',\n 'gad_source', // google ads source\n 'mc_cid', // mailchimp campaign id\n ...PERSONAL_DATA_CAMPAIGN_PARAMS,\n]\n\nexport const EVENT_TO_PERSON_PROPERTIES = [\n // mobile params\n '$app_build',\n '$app_name',\n '$app_namespace',\n '$app_version',\n // web params\n '$browser',\n '$browser_version',\n '$device_type',\n '$current_url',\n '$pathname',\n '$os',\n '$os_name', // $os_name is a special case, it's treated as an alias of $os!\n '$os_version',\n '$referring_domain',\n '$referrer',\n '$screen_height',\n '$screen_width',\n '$viewport_height',\n '$viewport_width',\n '$raw_user_agent',\n]\n\nexport const MASKED = ''\n\n// Campaign params that can be read from the cookie store\nexport const COOKIE_CAMPAIGN_PARAMS = [\n 'li_fat_id', // linkedin\n]\n\nexport function getCampaignParams(\n customTrackedParams?: string[],\n maskPersonalDataProperties?: boolean,\n customPersonalDataProperties?: string[] | undefined\n): Record {\n if (!document) {\n return {}\n }\n\n const paramsToMask = maskPersonalDataProperties\n ? [...PERSONAL_DATA_CAMPAIGN_PARAMS, ...(customPersonalDataProperties || [])]\n : []\n\n // Initially get campaign params from the URL\n const urlCampaignParams = _getCampaignParamsFromUrl(\n maskQueryParams(document.URL, paramsToMask, MASKED),\n customTrackedParams\n )\n\n // But we can also get some of them from the cookie store\n // For example: https://learn.microsoft.com/en-us/linkedin/marketing/conversions/enabling-first-party-cookies?view=li-lms-2025-05#reading-li_fat_id-from-cookies\n const cookieCampaignParams = _getCampaignParamsFromCookie()\n\n // Prefer the values found in the urlCampaignParams if possible\n // `extend` will override the values if found in the second argument\n return extend(cookieCampaignParams, urlCampaignParams)\n}\n\nfunction _getCampaignParamsFromUrl(url: string, customParams?: string[]): Record {\n const campaign_keywords = CAMPAIGN_PARAMS.concat(customParams || [])\n\n const params: Record = {}\n each(campaign_keywords, function (kwkey) {\n const kw = getQueryParam(url, kwkey)\n params[kwkey] = kw ? kw : null\n })\n\n return params\n}\n\nfunction _getCampaignParamsFromCookie(): Record {\n const params: Record = {}\n each(COOKIE_CAMPAIGN_PARAMS, function (kwkey) {\n const kw = cookieStore._get(kwkey)\n params[kwkey] = kw ? kw : null\n })\n\n return params\n}\n\nfunction _getSearchEngine(referrer: string): string | null {\n if (!referrer) {\n return null\n } else {\n if (referrer.search(URL_REGEX_PREFIX + 'google.([^/?]*)') === 0) {\n return 'google'\n } else if (referrer.search(URL_REGEX_PREFIX + 'bing.com') === 0) {\n return 'bing'\n } else if (referrer.search(URL_REGEX_PREFIX + 'yahoo.com') === 0) {\n return 'yahoo'\n } else if (referrer.search(URL_REGEX_PREFIX + 'duckduckgo.com') === 0) {\n return 'duckduckgo'\n } else {\n return null\n }\n }\n}\n\nfunction _getSearchInfoFromReferrer(referrer: string): Record {\n const search = _getSearchEngine(referrer)\n const param = search != 'yahoo' ? 'q' : 'p'\n const ret: Record = {}\n\n if (!isNull(search)) {\n ret['$search_engine'] = search\n\n const keyword = document ? getQueryParam(document.referrer, param) : ''\n if (keyword.length) {\n ret['ph_keyword'] = keyword\n }\n }\n\n return ret\n}\n\nexport function getSearchInfo(): Record {\n const referrer = document?.referrer\n if (!referrer) {\n return {}\n }\n return _getSearchInfoFromReferrer(referrer)\n}\n\nexport function getBrowserLanguage(): string | undefined {\n return (\n navigator.language || // Any modern browser\n (navigator as Record).userLanguage // IE11\n )\n}\n\nexport function getBrowserLanguagePrefix(): string | undefined {\n const lang = getBrowserLanguage()\n return typeof lang === 'string' ? lang.split('-')[0] : undefined\n}\n\nconst DIRECT = '$direct'\n\nexport function getReferrer(): string {\n return document?.referrer || DIRECT\n}\n\nexport function getReferringDomain(): string {\n if (!document?.referrer) {\n return DIRECT\n }\n return convertToURL(document.referrer)?.host || DIRECT\n}\n\nexport function getReferrerInfo(): Record {\n return {\n $referrer: getReferrer(),\n $referring_domain: getReferringDomain(),\n }\n}\n\nexport function getPersonInfo(maskPersonalDataProperties?: boolean, customPersonalDataProperties?: string[]) {\n const paramsToMask = maskPersonalDataProperties\n ? [...PERSONAL_DATA_CAMPAIGN_PARAMS, ...(customPersonalDataProperties || [])]\n : []\n const url = location?.href.substring(0, 1000)\n // we're being a bit more economical with bytes here because this is stored in the cookie\n return {\n r: getReferrer().substring(0, 1000),\n u: url ? maskQueryParams(url, paramsToMask, MASKED) : undefined,\n }\n}\n\nexport function getPersonPropsFromInfo(info: Record): Record {\n const { r: referrer, u: url } = info\n const referring_domain = referrer == null ? undefined : referrer == DIRECT ? DIRECT : convertToURL(referrer)?.host\n\n const props: Record = {\n $referrer: referrer,\n $referring_domain: referring_domain,\n }\n if (url) {\n props['$current_url'] = url\n const location = convertToURL(url)\n props['$host'] = location?.host\n props['$pathname'] = location?.pathname\n const campaignParams = _getCampaignParamsFromUrl(url)\n extend(props, campaignParams)\n }\n if (referrer) {\n const searchInfo = _getSearchInfoFromReferrer(referrer)\n extend(props, searchInfo)\n }\n return props\n}\n\nexport function getInitialPersonPropsFromInfo(info: Record): Record {\n const personProps = getPersonPropsFromInfo(info)\n const props: Record = {}\n each(personProps, function (val: any, key: string) {\n props[`$initial_${stripLeadingDollar(key)}`] = val\n })\n return props\n}\n\nexport function getTimezone(): string | undefined {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone\n } catch {\n return undefined\n }\n}\n\nexport function getTimezoneOffset(): number | undefined {\n try {\n return new Date().getTimezoneOffset()\n } catch {\n return undefined\n }\n}\n\nexport function getEventProperties(\n maskPersonalDataProperties?: boolean,\n customPersonalDataProperties?: string[]\n): Properties {\n if (!userAgent) {\n return {}\n }\n const paramsToMask = maskPersonalDataProperties\n ? [...PERSONAL_DATA_CAMPAIGN_PARAMS, ...(customPersonalDataProperties || [])]\n : []\n const [os_name, os_version] = detectOS(userAgent)\n\n return extend(\n stripEmptyProperties({\n $os: os_name,\n $os_version: os_version,\n $browser: detectBrowser(userAgent, navigator.vendor),\n $device: detectDevice(userAgent),\n $device_type: detectDeviceType(userAgent, {\n // eslint-disable-next-line compat/compat\n userAgentDataPlatform: navigator?.userAgentData?.platform,\n maxTouchPoints: navigator?.maxTouchPoints,\n screenWidth: window?.screen?.width,\n screenHeight: window?.screen?.height,\n devicePixelRatio: window?.devicePixelRatio,\n }),\n $timezone: getTimezone(),\n $timezone_offset: getTimezoneOffset(),\n }),\n {\n $current_url: maskQueryParams(location?.href, paramsToMask, MASKED),\n $host: location?.host,\n $pathname: location?.pathname,\n $raw_user_agent: userAgent.length > 1000 ? userAgent.substring(0, 997) + '...' : userAgent,\n $browser_version: detectBrowserVersion(userAgent, navigator.vendor),\n $browser_language: getBrowserLanguage(),\n $browser_language_prefix: getBrowserLanguagePrefix(),\n $screen_height: window?.screen.height,\n $screen_width: window?.screen.width,\n $viewport_height: window?.innerHeight,\n $viewport_width: window?.innerWidth,\n $lib: Config.LIB_NAME,\n $lib_version: Config.LIB_VERSION,\n $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10),\n $time: Date.now() / 1000, // epoch time in seconds\n }\n )\n}\n", "/* eslint camelcase: \"off\" */\n\nimport { each, extend, stripEmptyProperties } from './utils'\nimport { cookieStore, createLocalPlusCookieStore, localStore, memoryStore, sessionStore } from './storage'\nimport { PersistentStore, PostHogConfig, Properties } from './types'\nimport {\n ENABLED_FEATURE_FLAGS,\n EVENT_TIMERS_KEY,\n INITIAL_CAMPAIGN_PARAMS,\n INITIAL_PERSON_INFO,\n INITIAL_REFERRER_INFO,\n PERSISTENCE_RESERVED_PROPERTIES,\n PERSISTENCE_FEATURE_FLAG_EVALUATED_AT,\n} from './constants'\n\nimport { isUndefined } from '@posthog/core'\nimport {\n getCampaignParams,\n getInitialPersonPropsFromInfo,\n getPersonInfo,\n getReferrerInfo,\n getSearchInfo,\n} from './utils/event-utils'\nimport { logger } from './utils/logger'\nimport { stripLeadingDollar, isEmptyObject, isObject } from '@posthog/core'\n\nconst CASE_INSENSITIVE_PERSISTENCE_TYPES: readonly Lowercase[] = [\n 'cookie',\n 'localstorage',\n 'localstorage+cookie',\n 'sessionstorage',\n 'memory',\n]\n\nconst parseName = (config: PostHogConfig): string => {\n let token = ''\n if (config['token']) {\n token = config['token'].replace(/\\+/g, 'PL').replace(/\\//g, 'SL').replace(/=/g, 'EQ')\n }\n\n if (config['persistence_name']) {\n return 'ph_' + config['persistence_name']\n } else {\n return 'ph_' + token + '_posthog'\n }\n}\n\nconst isArrayContentsEqual = (arr1: readonly string[], arr2: readonly string[]): boolean => {\n if (arr1.length !== arr2.length) {\n return false\n }\n\n const sortedArr1 = [...arr1].sort()\n const sortedArr2 = [...arr2].sort()\n return sortedArr1.every((item, index) => item === sortedArr2[index])\n}\n\n/**\n * PostHog Persistence Object\n * @constructor\n */\nexport class PostHogPersistence {\n private _config: PostHogConfig\n props: Properties\n private _storage: PersistentStore\n private _campaign_params_saved: boolean\n private readonly _name: string\n _disabled: boolean | undefined\n private _secure: boolean | undefined\n private _expire_days: number | undefined\n private _default_expiry: number | undefined\n private _cross_subdomain: boolean | undefined\n\n /**\n * @param {PostHogConfig} config initial PostHog configuration\n * @param {boolean=} isDisabled should persistence be disabled (e.g. because of consent management)\n */\n constructor(config: PostHogConfig, isDisabled?: boolean) {\n this._config = config\n this.props = {}\n this._campaign_params_saved = false\n this._name = parseName(config)\n this._storage = this._buildStorage(config)\n this.load()\n if (config.debug) {\n logger.info('Persistence loaded', config['persistence'], { ...this.props })\n }\n this.update_config(config, config, isDisabled)\n this.save()\n }\n\n /**\n * Returns whether persistence is disabled. Only available in SDKs > 1.257.1. Do not use on extensions, otherwise\n * it'll break backwards compatibility for any version before 1.257.1.\n */\n public isDisabled?(): boolean {\n return !!this._disabled\n }\n\n private _buildStorage(config: PostHogConfig) {\n if (\n CASE_INSENSITIVE_PERSISTENCE_TYPES.indexOf(\n config['persistence'].toLowerCase() as Lowercase\n ) === -1\n ) {\n logger.critical(\n 'Unknown persistence type ' + config['persistence'] + '; falling back to localStorage+cookie'\n )\n config['persistence'] = 'localStorage+cookie'\n }\n\n // Create this before hand to avoid creating it multiple times\n // Creating it inside each individual condition below is too complicated and will break backwards compatibility\n // so create it once for this specific config and use it if necessary\n const localPlusCookieStore = createLocalPlusCookieStore(config['cookie_persisted_properties'] || [])\n\n let store: PersistentStore\n\n // We handle storage type in a case-insensitive way for backwards compatibility\n const storage_type = config['persistence'].toLowerCase() as Lowercase\n if (storage_type === 'localstorage' && localStore._is_supported()) {\n store = localStore\n } else if (storage_type === 'localstorage+cookie' && localPlusCookieStore._is_supported()) {\n store = localPlusCookieStore\n } else if (storage_type === 'sessionstorage' && sessionStore._is_supported()) {\n store = sessionStore\n } else if (storage_type === 'memory') {\n store = memoryStore\n } else if (storage_type === 'cookie') {\n store = cookieStore\n } else if (localPlusCookieStore._is_supported()) {\n // selected storage type wasn't supported, fallback to 'localstorage+cookie' if possible\n store = localPlusCookieStore\n } else {\n store = cookieStore\n }\n\n return store\n }\n\n /**\n * Check if the feature flag cache is stale based on the configured TTL.\n * @param ttl Optional TTL override (uses config value if not provided)\n * @internal\n */\n _isFeatureFlagCacheStale(ttl?: number): boolean {\n const effectiveTtl = ttl ?? this._config.feature_flag_cache_ttl_ms\n if (!effectiveTtl || effectiveTtl <= 0) {\n return false\n }\n const evaluatedAt = this.props[PERSISTENCE_FEATURE_FLAG_EVALUATED_AT]\n // If evaluatedAt is missing or not a numeric timestamp, consider cache stale.\n // This handles SDK upgrades where old cached flags lack evaluatedAt.\n if (!evaluatedAt || typeof evaluatedAt !== 'number') {\n return true\n }\n return Date.now() - evaluatedAt > effectiveTtl\n }\n\n properties(): Properties {\n const p: Properties = {}\n\n // Filter out reserved properties\n each(this.props, (v, k) => {\n if (k === ENABLED_FEATURE_FLAGS && isObject(v)) {\n // Skip $feature/ properties if cache is stale\n if (!this._isFeatureFlagCacheStale()) {\n const keys = Object.keys(v)\n for (let i = 0; i < keys.length; i++) {\n p[`$feature/${keys[i]}`] = v[keys[i]]\n }\n }\n } else if (PERSISTENCE_RESERVED_PROPERTIES.indexOf(k) === -1) {\n p[k] = v\n }\n })\n return p\n }\n\n load(): void {\n if (this._disabled) {\n return\n }\n\n const entry = this._storage._parse(this._name)\n\n if (entry) {\n this.props = extend({}, entry)\n }\n }\n\n /**\n * NOTE: Saving frequently causes issues with Recordings and Consent Management Platform (CMP) tools which\n * observe cookie changes, and modify their UI, often causing infinite loops.\n * As such callers of this should ideally check that the data has changed beforehand\n */\n save(): void {\n if (this._disabled) {\n return\n }\n this._storage._set(\n this._name,\n this.props,\n this._expire_days,\n this._cross_subdomain,\n this._secure,\n this._config.debug\n )\n }\n\n remove(): void {\n // remove both domain and subdomain cookies\n this._storage._remove(this._name, false)\n this._storage._remove(this._name, true)\n }\n\n // removes the storage entry and deletes all loaded data\n // forced name for tests\n\n clear(): void {\n this.remove()\n this.props = {}\n }\n\n /**\n * @param {Object} props\n * @param {*=} default_value\n * @param {number=} days\n */\n\n register_once(props: Properties, default_value: any, days?: number): boolean {\n if (isObject(props)) {\n if (isUndefined(default_value)) {\n default_value = 'None'\n }\n this._expire_days = isUndefined(days) ? this._default_expiry : days\n\n let hasChanges = false\n\n each(props, (val, prop) => {\n if (!this.props.hasOwnProperty(prop) || this.props[prop] === default_value) {\n this.props[prop] = val\n hasChanges = true\n }\n })\n\n if (hasChanges) {\n this.save()\n return true\n }\n }\n return false\n }\n\n /**\n * @param {Object} props\n * @param {number=} days\n */\n\n register(props: Properties, days?: number): boolean {\n if (isObject(props)) {\n this._expire_days = isUndefined(days) ? this._default_expiry : days\n\n let hasChanges = false\n\n each(props, (val, prop) => {\n if (props.hasOwnProperty(prop) && this.props[prop] !== val) {\n this.props[prop] = val\n hasChanges = true\n }\n })\n\n if (hasChanges) {\n this.save()\n return true\n }\n }\n return false\n }\n\n unregister(prop: string): void {\n if (prop in this.props) {\n delete this.props[prop]\n this.save()\n }\n }\n\n update_campaign_params(): void {\n if (!this._campaign_params_saved) {\n const campaignParams = getCampaignParams(\n this._config.custom_campaign_params,\n this._config.mask_personal_data_properties,\n this._config.custom_personal_data_properties\n )\n // only save campaign params if there were any\n if (!isEmptyObject(stripEmptyProperties(campaignParams))) {\n this.register(campaignParams)\n }\n this._campaign_params_saved = true\n }\n }\n update_search_keyword(): void {\n this.register(getSearchInfo())\n }\n\n update_referrer_info(): void {\n this.register_once(getReferrerInfo(), undefined)\n }\n\n set_initial_person_info(): void {\n if (this.props[INITIAL_CAMPAIGN_PARAMS] || this.props[INITIAL_REFERRER_INFO]) {\n // the user has initial properties stored the previous way, don't save them again\n return\n }\n\n this.register_once(\n {\n [INITIAL_PERSON_INFO]: getPersonInfo(\n this._config.mask_personal_data_properties,\n this._config.custom_personal_data_properties\n ),\n },\n undefined\n )\n }\n\n get_initial_props(): Properties {\n const p: Properties = {}\n\n // this section isn't written to anymore, but we should keep reading from it for backwards compatibility\n // for a while\n each([INITIAL_REFERRER_INFO, INITIAL_CAMPAIGN_PARAMS], (key) => {\n const initialReferrerInfo = this.props[key]\n if (initialReferrerInfo) {\n each(initialReferrerInfo, function (v, k) {\n p['$initial_' + stripLeadingDollar(k)] = v\n })\n }\n })\n const initialPersonInfo = this.props[INITIAL_PERSON_INFO]\n if (initialPersonInfo) {\n const initialPersonProps = getInitialPersonPropsFromInfo(initialPersonInfo)\n extend(p, initialPersonProps)\n }\n\n return p\n }\n\n // safely fills the passed in object with stored properties,\n // does not override any properties defined in both\n // returns the passed in object\n\n safe_merge(props: Properties): Properties {\n each(this.props, function (val, prop) {\n if (!(prop in props)) {\n props[prop] = val\n }\n })\n\n return props\n }\n\n update_config(config: PostHogConfig, oldConfig: PostHogConfig, isDisabled?: boolean): void {\n this._default_expiry = this._expire_days = config['cookie_expiration']\n this.set_disabled(config['disable_persistence'] || !!isDisabled)\n this.set_cross_subdomain(config['cross_subdomain_cookie'])\n this.set_secure(config['secure_cookie'])\n\n // If the persistence type has changed, we need to migrate the data.\n if (\n config.persistence !== oldConfig.persistence ||\n !isArrayContentsEqual(config.cookie_persisted_properties || [], oldConfig.cookie_persisted_properties || [])\n ) {\n const newStore = this._buildStorage(config)\n const props = this.props\n\n // Clear the old store\n this.clear()\n\n // Set up the new store data\n this._storage = newStore\n this.props = props\n this.save()\n }\n }\n\n set_disabled(disabled: boolean): void {\n this._disabled = disabled\n if (this._disabled) {\n this.remove()\n } else {\n this.save()\n }\n }\n\n set_cross_subdomain(cross_subdomain: boolean): void {\n if (cross_subdomain !== this._cross_subdomain) {\n this._cross_subdomain = cross_subdomain\n this.remove()\n this.save()\n }\n }\n\n set_secure(secure: boolean): void {\n if (secure !== this._secure) {\n this._secure = secure\n this.remove()\n this.save()\n }\n }\n\n set_event_timer(event_name: string, timestamp: number): void {\n const timers = this.props[EVENT_TIMERS_KEY] || {}\n timers[event_name] = timestamp\n this.props[EVENT_TIMERS_KEY] = timers\n this.save()\n }\n\n remove_event_timer(event_name: string): number {\n const timers = this.props[EVENT_TIMERS_KEY] || {}\n const timestamp = timers[event_name]\n if (!isUndefined(timestamp)) {\n delete this.props[EVENT_TIMERS_KEY][event_name]\n this.save()\n }\n return timestamp\n }\n\n get_property(prop: string): any {\n return this.props[prop]\n }\n\n set_property(prop: string, to: any): void {\n this.props[prop] = to\n this.save()\n }\n}\n", "/**\n * Having Survey types in types.ts was confusing tsc\n * and generating an invalid module.d.ts\n * See https://github.com/PostHog/posthog-js/issues/698\n */\n\nimport type { Properties, PropertyMatchType } from './types'\nimport type { SurveyAppearance as CoreSurveyAppearance, SurveyValidationRule } from '@posthog/core'\n\n// Extended operator type to include numeric operators not in PropertyMatchType\nexport type PropertyOperator = PropertyMatchType | 'gt' | 'lt'\n\nexport type PropertyFilters = {\n [propertyName: string]: {\n values: string[]\n operator: PropertyOperator\n }\n}\n\nexport interface SurveyEventWithFilters {\n name: string\n propertyFilters?: PropertyFilters\n}\n\n// Extends core SurveyAppearance with browser-specific fields\n// Omit 'position' from core because browser's SurveyPosition has additional values (e.g., NextToTrigger)\nexport interface SurveyAppearance extends Omit {\n // Browser-specific fields not in core\n /** @deprecated - not currently used */\n descriptionTextColor?: string\n ratingButtonHoverColor?: string\n whiteLabel?: boolean\n tabPosition?: SurveyTabPosition\n fontFamily?: string\n maxWidth?: string\n zIndex?: string\n disabledButtonOpacity?: string\n boxPadding?: string\n /** @deprecated Use inputBackground instead (inherited from core) */\n inputBackgroundColor?: string\n // Hide the X (cancel) button - defaults to false (show the button)\n hideCancelButton?: boolean\n // Browser's SurveyPosition has more options than core (e.g., NextToTrigger)\n position?: SurveyPosition\n widgetType?: SurveyWidgetType\n}\n\nexport type SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion\n\nexport type SurveyQuestionDescriptionContentType = 'html' | 'text'\n\ninterface SurveyQuestionBase {\n question: string\n id?: string\n description?: string | null\n descriptionContentType?: SurveyQuestionDescriptionContentType\n optional?: boolean\n buttonText?: string\n branching?: NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching\n validation?: SurveyValidationRule[]\n}\n\nexport interface BasicSurveyQuestion extends SurveyQuestionBase {\n type: typeof SurveyQuestionType.Open\n}\n\nexport interface LinkSurveyQuestion extends SurveyQuestionBase {\n type: typeof SurveyQuestionType.Link\n link?: string | null\n}\n\nexport interface RatingSurveyQuestion extends SurveyQuestionBase {\n type: typeof SurveyQuestionType.Rating\n display: 'number' | 'emoji'\n scale: 2 | 3 | 5 | 7 | 10\n lowerBoundLabel: string\n upperBoundLabel: string\n skipSubmitButton?: boolean\n}\n\nexport interface MultipleSurveyQuestion extends SurveyQuestionBase {\n type: typeof SurveyQuestionType.SingleChoice | typeof SurveyQuestionType.MultipleChoice\n choices: string[]\n hasOpenChoice?: boolean\n shuffleOptions?: boolean\n skipSubmitButton?: boolean\n}\n\ninterface NextQuestionBranching {\n type: typeof SurveyQuestionBranchingType.NextQuestion\n}\n\ninterface EndBranching {\n type: typeof SurveyQuestionBranchingType.End\n}\n\ninterface ResponseBasedBranching {\n type: typeof SurveyQuestionBranchingType.ResponseBased\n responseValues: Record\n}\n\ninterface SpecificQuestionBranching {\n type: typeof SurveyQuestionBranchingType.SpecificQuestion\n index: number\n}\n\nexport type SurveyCallback = (surveys: Survey[], context?: { isLoaded: boolean; error?: string }) => void\n\nexport interface SurveyElement {\n text?: string\n $el_text?: string\n tag_name?: string\n href?: string\n attr_id?: string\n attr_class?: string[]\n nth_child?: number\n nth_of_type?: number\n attributes?: Record\n event_id?: number\n order?: number\n group_id?: number\n}\n\n// Re-export from @posthog/types to avoid duplication\nexport type { SurveyRenderReason } from '@posthog/types'\n\nexport interface Survey {\n // Sync this with the backend's SurveyAPISerializer!\n id: string\n name: string\n description: string\n type: SurveyType\n feature_flag_keys:\n | {\n key: string\n value?: string\n }[]\n | null\n // the linked flag key is the flag key that is used to link the survey to a flag\n linked_flag_key: string | null\n targeting_flag_key: string | null\n // the internal targeting flag key is the flag key that is used to target users who have seen the survey\n // eg survey-targeting-\n internal_targeting_flag_key: string | null\n questions: SurveyQuestion[]\n appearance: SurveyAppearance | null\n conditions: {\n url?: string\n selector?: string\n seenSurveyWaitPeriodInDays?: number\n urlMatchType?: PropertyMatchType\n /** events that trigger surveys */\n events: {\n repeatedActivation?: boolean\n values: SurveyEventWithFilters[]\n } | null\n /** events that cancel \"pending\" (time-delayed) surveys */\n cancelEvents: {\n values: SurveyEventWithFilters[]\n } | null\n actions: {\n values: SurveyActionType[]\n } | null\n deviceTypes?: string[]\n deviceTypesMatchType?: PropertyMatchType\n linkedFlagVariant?: string\n } | null\n start_date: string | null\n end_date: string | null\n current_iteration: number | null\n current_iteration_start_date: string | null\n schedule?: SurveySchedule | null\n enable_partial_responses?: boolean | null\n}\n\nexport type SurveyWithTypeAndAppearance = Pick\n\nexport interface SurveyActionType {\n id: number\n name: string | null\n steps?: ActionStepType[]\n}\n\n/** Sync with plugin-server/src/types.ts */\nexport type ActionStepStringMatching = 'contains' | 'exact' | 'regex'\n\nexport interface ActionStepType {\n event?: string | null\n selector?: string | null\n /** pre-compiled regex pattern for matching selector against $elements_chain */\n selector_regex?: string | null\n /** @deprecated Only `selector` should be used now. */\n tag_name?: string\n text?: string | null\n /** @default StringMatching.Exact */\n text_matching?: ActionStepStringMatching | null\n href?: string | null\n /** @default ActionStepStringMatching.Exact */\n href_matching?: ActionStepStringMatching | null\n url?: string | null\n /** @default StringMatching.Contains */\n url_matching?: ActionStepStringMatching | null\n /** Property filters for action step matching */\n properties?: {\n key: string\n value?: string | number | boolean | (string | number | boolean)[] | null\n operator?: PropertyMatchType\n type?: string\n }[]\n}\n\ninterface DisplaySurveyOptionsBase {\n ignoreConditions: boolean\n ignoreDelay: boolean\n displayType: DisplaySurveyType\n /** Additional properties to include in all survey events (shown, sent, dismissed) */\n properties?: Properties\n /** Pre-filled responses by question index (0-based) */\n initialResponses?: Record\n}\n\nexport interface DisplaySurveyPopoverOptions extends DisplaySurveyOptionsBase {\n displayType: typeof DisplaySurveyType.Popover\n /** Override the survey's configured position */\n position?: SurveyPosition\n /** CSS selector for the element to position the survey next to (when position is NextToTrigger) */\n selector?: string\n /** When true, `survey shown` events will not be emitted automatically */\n skipShownEvent?: boolean\n}\n\ninterface DisplaySurveyInlineOptions extends DisplaySurveyOptionsBase {\n displayType: typeof DisplaySurveyType.Inline\n selector: string\n}\n\nexport type DisplaySurveyOptions = DisplaySurveyPopoverOptions | DisplaySurveyInlineOptions\n\nexport interface SurveyConfig {\n prefillFromUrl?: boolean\n /**\n * @deprecated No longer used. Surveys will automatically advance past\n * prefilled questions with skipSubmitButton enabled. If partial response\n * collection is enabled, partial responses for pre-filled questions will\n * be submitted automatically on page load.\n */\n autoSubmitIfComplete?: boolean\n /**\n * @deprecated No longer used. Pre-filled responses are now sent\n * immediately when partial responses are enabled, or all required\n * quesions have been pre-filled.\n */\n autoSubmitDelay?: number\n}\n\nexport type SurveyResponseValue = string | number | string[] | null\n\n/**\n * Surveys related enums and constants.\n * We use const objects instead of TypeScript enums to allow for easier tree-shaking and to avoid issues with enum imports in JavaScript.\n */\n\nexport const SurveyEventType = {\n Activation: 'events',\n Cancellation: 'cancelEvents',\n} as const\nexport type SurveyEventType = (typeof SurveyEventType)[keyof typeof SurveyEventType]\n\nexport const SurveyWidgetType = {\n Button: 'button',\n Tab: 'tab',\n Selector: 'selector',\n} as const\nexport type SurveyWidgetType = (typeof SurveyWidgetType)[keyof typeof SurveyWidgetType]\n\nexport const SurveyPosition = {\n TopLeft: 'top_left',\n TopRight: 'top_right',\n TopCenter: 'top_center',\n MiddleLeft: 'middle_left',\n MiddleRight: 'middle_right',\n MiddleCenter: 'middle_center',\n Left: 'left',\n Center: 'center',\n Right: 'right',\n NextToTrigger: 'next_to_trigger',\n} as const\nexport type SurveyPosition = (typeof SurveyPosition)[keyof typeof SurveyPosition]\n\nexport const SurveyTabPosition = {\n Top: 'top',\n Left: 'left',\n Right: 'right',\n Bottom: 'bottom',\n} as const\nexport type SurveyTabPosition = (typeof SurveyTabPosition)[keyof typeof SurveyTabPosition]\n\nexport const SurveyType = {\n Popover: 'popover',\n API: 'api',\n Widget: 'widget',\n ExternalSurvey: 'external_survey',\n} as const\nexport type SurveyType = (typeof SurveyType)[keyof typeof SurveyType]\n\nexport const SurveyQuestionType = {\n Open: 'open',\n MultipleChoice: 'multiple_choice',\n SingleChoice: 'single_choice',\n Rating: 'rating',\n Link: 'link',\n} as const\nexport type SurveyQuestionType = (typeof SurveyQuestionType)[keyof typeof SurveyQuestionType]\n\nexport const SurveyQuestionBranchingType = {\n NextQuestion: 'next_question',\n End: 'end',\n ResponseBased: 'response_based',\n SpecificQuestion: 'specific_question',\n} as const\nexport type SurveyQuestionBranchingType = (typeof SurveyQuestionBranchingType)[keyof typeof SurveyQuestionBranchingType]\n\nexport const SurveySchedule = {\n Once: 'once',\n Recurring: 'recurring',\n Always: 'always',\n} as const\nexport type SurveySchedule = (typeof SurveySchedule)[keyof typeof SurveySchedule]\n\nexport const SurveyEventName = {\n SHOWN: 'survey shown',\n DISMISSED: 'survey dismissed',\n SENT: 'survey sent',\n ABANDONED: 'survey abandoned',\n} as const\nexport type SurveyEventName = (typeof SurveyEventName)[keyof typeof SurveyEventName]\n\nexport const SurveyEventProperties = {\n SURVEY_ID: '$survey_id',\n SURVEY_NAME: '$survey_name',\n SURVEY_RESPONSE: '$survey_response',\n SURVEY_ITERATION: '$survey_iteration',\n SURVEY_ITERATION_START_DATE: '$survey_iteration_start_date',\n SURVEY_PARTIALLY_COMPLETED: '$survey_partially_completed',\n SURVEY_SUBMISSION_ID: '$survey_submission_id',\n SURVEY_QUESTIONS: '$survey_questions',\n SURVEY_COMPLETED: '$survey_completed',\n PRODUCT_TOUR_ID: '$product_tour_id',\n SURVEY_LAST_SEEN_DATE: '$survey_last_seen_date',\n} as const\nexport type SurveyEventProperties = (typeof SurveyEventProperties)[keyof typeof SurveyEventProperties]\n\nexport const DisplaySurveyType = {\n Popover: 'popover',\n Inline: 'inline',\n} as const\nexport type DisplaySurveyType = (typeof DisplaySurveyType)[keyof typeof DisplaySurveyType]\n", "import { PropertyMatchType } from './types'\nimport { SurveyActionType, SurveyEventWithFilters } from './posthog-surveys-types'\nimport type { InferredSelector } from './extensions/product-tours/element-inference'\nimport { SurveyPosition } from '@posthog/core'\nimport { Z_INDEX_TOURS } from './constants'\n\nexport interface JSONContent {\n type?: string\n attrs?: Record\n content?: JSONContent[]\n marks?: { type: string; attrs?: Record }[]\n text?: string\n}\n\nexport type ProductTourStepType = 'element' | 'modal' | 'survey' | 'banner'\n\nexport interface ProductTourBannerConfig {\n behavior: 'sticky' | 'static' | 'custom'\n selector?: string\n action?: {\n type: 'none' | 'link' | 'trigger_tour'\n link?: string\n tourId?: string\n }\n animation?: {\n duration?: number\n }\n}\n\n/** Button actions available on modal steps */\nexport type ProductTourButtonAction = 'dismiss' | 'link' | 'next_step' | 'previous_step' | 'trigger_tour'\n\nexport interface ProductTourStepButton {\n text: string\n action: ProductTourButtonAction\n /** URL to open when action is 'link' */\n link?: string\n /** Tour ID to trigger when action is 'trigger_tour' */\n tourId?: string\n}\n\nexport interface ProductTourStepButtons {\n primary?: ProductTourStepButton\n secondary?: ProductTourStepButton\n}\n\nexport type ProductTourSurveyQuestionType = 'open' | 'rating'\n\nexport interface ProductTourSurveyQuestion {\n type: ProductTourSurveyQuestionType\n questionText: string\n /** Rating display type - emoji or number */\n display?: 'emoji' | 'number'\n /** Rating scale - 3 or 5 for emoji, 5 or 10 for number */\n scale?: 3 | 5 | 10\n /** Label for low end of rating scale (e.g., \"Not likely\") */\n lowerBoundLabel?: string\n /** Label for high end of rating scale (e.g., \"Very likely\") */\n upperBoundLabel?: string\n submitButtonText?: string\n backButtonText?: string\n}\n\nexport interface ProductTourStep {\n id: string\n type: ProductTourStepType\n selector?: string\n progressionTrigger: 'button' | 'click'\n content: JSONContent | null\n /** Pre-rendered HTML content from the editor. If present, SDK should use this instead of rendering from JSONContent. */\n contentHtml?: string\n /** Inline survey question config - if present, this is a survey step */\n survey?: ProductTourSurveyQuestion\n /** ID of the auto-created survey for this step (set by backend) */\n linkedSurveyId?: string\n /** ID of the survey question (set by backend, used for event tracking) */\n linkedSurveyQuestionId?: string\n /** Enhanced element data for more reliable lookup at runtime */\n inferenceData?: InferredSelector\n /** Use CSS selector instead of inference. Defaults to false (use inference). */\n useManualSelector?: boolean\n /** Maximum tooltip width in pixels (defaults to 320px) */\n maxWidth?: number\n /** Position for modal/survey steps (defaults to middle_center) */\n modalPosition?: SurveyPosition\n /** Button configuration for modal steps */\n buttons?: ProductTourStepButtons\n /** Banner configuration (only for banner steps) */\n bannerConfig?: ProductTourBannerConfig\n /** translation data for this tour step */\n translations?: Record\n}\n\n/** all translatable content for a given tour step */\nexport interface ProductTourStepTranslation {\n content?: ProductTourStep['content']\n contentHtml?: ProductTourStep['contentHtml']\n buttons?: {\n primary?: Pick\n secondary?: Pick\n }\n survey?: Pick<\n ProductTourSurveyQuestion,\n 'questionText' | 'lowerBoundLabel' | 'upperBoundLabel' | 'submitButtonText' | 'backButtonText'\n >\n}\n\n/** maps to main repo EffectiveProductTourType */\nexport type ProductTourType = 'tour' | 'announcement' | 'banner'\n\nexport interface ProductTourWaitPeriod {\n days: number\n types: ProductTourType[]\n}\n\nexport interface ProductTourConditions {\n url?: string\n urlMatchType?: PropertyMatchType\n selector?: string\n autoShowDelaySeconds?: number\n events?: {\n values: SurveyEventWithFilters[]\n } | null\n cancelEvents?: {\n values: SurveyEventWithFilters[]\n } | null\n actions?: {\n values: SurveyActionType[]\n } | null\n linkedFlagVariant?: string\n deviceTypes?: string[]\n seenTourWaitPeriod?: ProductTourWaitPeriod\n}\n\nexport interface ProductTourAppearance {\n backgroundColor?: string\n textColor?: string\n buttonColor?: string\n borderRadius?: number\n buttonBorderRadius?: number\n borderColor?: string\n fontFamily?: string\n boxShadow?: string\n showOverlay?: boolean\n whiteLabel?: boolean\n /** defaults to true, auto-set to false for announcements/banners */\n dismissOnClickOutside?: boolean\n zIndex?: number\n}\n\nexport type ProductTourDisplayFrequency = 'show_once' | 'until_interacted' | 'always'\n\nexport interface ProductTour {\n id: string\n name: string\n description?: string\n tour_type: ProductTourType // inferred in API based on tour content\n auto_launch?: boolean\n start_date: string | null\n end_date: string | null\n current_iteration?: number\n conditions?: ProductTourConditions\n appearance?: ProductTourAppearance\n steps: ProductTourStep[]\n internal_targeting_flag_key?: string\n linked_flag_key?: string\n display_frequency?: ProductTourDisplayFrequency\n disable_image_preload?: boolean\n}\n\nexport type ProductTourCallback = (tours: ProductTour[], context?: { isLoaded: boolean; error?: string }) => void\n\nexport type ProductTourSelectorError = 'not_found' | 'multiple_matches' | 'not_visible'\n\nexport type ProductTourDismissReason =\n | 'user_clicked_skip'\n | 'user_clicked_outside'\n | 'escape_key'\n | 'element_unavailable'\n | 'container_unavailable'\n\nexport type ProductTourRenderReason = 'auto' | 'api' | 'trigger' | 'event'\n\nexport const DEFAULT_PRODUCT_TOUR_APPEARANCE: Required = {\n backgroundColor: '#ffffff',\n textColor: '#1d1f27',\n buttonColor: '#1d1f27',\n borderRadius: 8,\n buttonBorderRadius: 6,\n borderColor: '#e5e7eb',\n fontFamily: 'system-ui',\n boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',\n showOverlay: true,\n whiteLabel: false,\n dismissOnClickOutside: true,\n zIndex: Z_INDEX_TOURS,\n}\n\nexport interface ShowTourOptions {\n reason?: ProductTourRenderReason\n enableStrictValidation?: boolean\n}\n\nexport const ProductTourEventName = {\n SHOWN: 'product tour shown',\n DISMISSED: 'product tour dismissed',\n COMPLETED: 'product tour completed',\n STEP_SHOWN: 'product tour step shown',\n STEP_COMPLETED: 'product tour step completed',\n BUTTON_CLICKED: 'product tour button clicked',\n STEP_SELECTOR_FAILED: 'product tour step selector failed',\n BANNER_CONTAINER_SELECTOR_FAILED: 'product tour banner container selector failed',\n BANNER_ACTION_CLICKED: 'product tour banner action clicked',\n} as const\nexport type ProductTourEventName = (typeof ProductTourEventName)[keyof typeof ProductTourEventName]\n\nexport const ProductTourEventProperties = {\n TOUR_ID: '$product_tour_id',\n TOUR_NAME: '$product_tour_name',\n TOUR_ITERATION: '$product_tour_iteration',\n TOUR_RENDER_REASON: '$product_tour_render_reason',\n TOUR_STEP_ID: '$product_tour_step_id',\n TOUR_STEP_ORDER: '$product_tour_step_order',\n TOUR_STEP_TYPE: '$product_tour_step_type',\n TOUR_DISMISS_REASON: '$product_tour_dismiss_reason',\n TOUR_BUTTON_TEXT: '$product_tour_button_text',\n TOUR_BUTTON_ACTION: '$product_tour_button_action',\n TOUR_BUTTON_LINK: '$product_tour_button_link',\n TOUR_BUTTON_TOUR_ID: '$product_tour_button_tour_id',\n TOUR_STEPS_COUNT: '$product_tour_steps_count',\n TOUR_STEP_SELECTOR: '$product_tour_step_selector',\n TOUR_STEP_SELECTOR_FOUND: '$product_tour_step_selector_found',\n TOUR_STEP_ELEMENT_TAG: '$product_tour_step_element_tag',\n TOUR_STEP_ELEMENT_ID: '$product_tour_step_element_id',\n TOUR_STEP_ELEMENT_CLASSES: '$product_tour_step_element_classes',\n TOUR_STEP_ELEMENT_TEXT: '$product_tour_step_element_text',\n TOUR_ERROR: '$product_tour_error',\n TOUR_MATCHES_COUNT: '$product_tour_matches_count',\n TOUR_FAILURE_PHASE: '$product_tour_failure_phase',\n TOUR_WAITED_FOR_ELEMENT: '$product_tour_waited_for_element',\n TOUR_WAIT_DURATION_MS: '$product_tour_wait_duration_ms',\n TOUR_BANNER_SELECTOR: '$product_tour_banner_selector',\n TOUR_LINKED_SURVEY_ID: '$product_tour_linked_survey_id',\n USE_MANUAL_SELECTOR: '$use_manual_selector',\n INFERENCE_DATA_PRESENT: '$inference_data_present',\n TOUR_LAST_SEEN_DATE: '$product_tour_last_seen_date',\n TOUR_TYPE: '$product_tour_type',\n} as const\nexport type ProductTourEventProperties = (typeof ProductTourEventProperties)[keyof typeof ProductTourEventProperties]\n", "import { CAPTURE_RATE_LIMIT } from './constants'\nimport type { PostHog } from './posthog-core'\nimport { RequestResponse } from './types'\nimport { createLogger } from './utils/logger'\n\nconst logger = createLogger('[RateLimiter]')\n\nconst ONE_MINUTE_IN_MILLISECONDS = 60 * 1000\nconst RATE_LIMIT_EVENT = '$$client_ingestion_warning'\nconst DEFAULT_EVENTS_PER_SECOND = 10\nconst BURST_LIMIT_MULTIPLIER = 10\n\ninterface CaptureResponse {\n quota_limited?: string[]\n}\n\nexport class RateLimiter {\n instance: PostHog\n serverLimits: Record = {}\n lastEventRateLimited = false\n\n constructor(instance: PostHog) {\n this.instance = instance\n this.lastEventRateLimited = this.clientRateLimitContext(true).isRateLimited\n }\n\n get captureEventsPerSecond(): number {\n return this.instance.config.rate_limiting?.events_per_second || DEFAULT_EVENTS_PER_SECOND\n }\n\n get captureEventsBurstLimit(): number {\n return Math.max(\n this.instance.config.rate_limiting?.events_burst_limit ||\n this.captureEventsPerSecond * BURST_LIMIT_MULTIPLIER,\n this.captureEventsPerSecond\n )\n }\n\n public clientRateLimitContext(checkOnly = false): {\n isRateLimited: boolean\n remainingTokens: number\n } {\n // This is primarily to prevent runaway loops from flooding capture with millions of events for a single user.\n // It's as much for our protection as theirs.\n const { captureEventsBurstLimit, captureEventsPerSecond } = this\n const now = new Date().getTime()\n const bucket = this.instance.persistence?.get_property(CAPTURE_RATE_LIMIT) ?? {\n tokens: captureEventsBurstLimit,\n last: now,\n }\n\n bucket.tokens += ((now - bucket.last) / 1000) * captureEventsPerSecond\n bucket.last = now\n\n if (bucket.tokens > captureEventsBurstLimit) {\n bucket.tokens = captureEventsBurstLimit\n }\n\n const isRateLimited = bucket.tokens < 1\n\n if (!isRateLimited && !checkOnly) {\n bucket.tokens = Math.max(0, bucket.tokens - 1)\n }\n\n if (isRateLimited && !this.lastEventRateLimited && !checkOnly) {\n this.instance.capture(\n RATE_LIMIT_EVENT,\n {\n $$client_ingestion_warning_message: `posthog-js client rate limited. Config is set to ${captureEventsPerSecond} events per second and ${captureEventsBurstLimit} events burst limit.`,\n },\n {\n skip_client_rate_limiting: true,\n }\n )\n }\n\n this.lastEventRateLimited = isRateLimited\n this.instance.persistence?.set_property(CAPTURE_RATE_LIMIT, bucket)\n\n return {\n isRateLimited,\n remainingTokens: bucket.tokens,\n }\n }\n\n public isServerRateLimited(batchKey: string | undefined): boolean {\n const retryAfter = this.serverLimits[batchKey || 'events'] || false\n\n if (retryAfter === false) {\n return false\n }\n return new Date().getTime() < retryAfter\n }\n\n public checkForLimiting = (httpResponse: RequestResponse): void => {\n const text = httpResponse.text\n\n if (!text || !text.length) {\n return\n }\n\n try {\n const response: CaptureResponse = JSON.parse(text)\n const quotaLimitedProducts = response.quota_limited || []\n quotaLimitedProducts.forEach((batchKey) => {\n logger.info(`${batchKey || 'events'} is quota limited.`)\n this.serverLimits[batchKey] = new Date().getTime() + ONE_MINUTE_IN_MILLISECONDS\n })\n } catch (e: any) {\n logger.warn(`could not rate limit - continuing. Error: \"${e?.message}\"`, { text })\n return\n }\n }\n}\n", "import { PostHog } from './posthog-core'\nimport { RemoteConfig } from './types'\n\nimport { createLogger } from './utils/logger'\nimport { assignableWindow, document } from './utils/globals'\n\nconst logger = createLogger('[RemoteConfig]')\n\n// Default refresh interval for feature flags in long-running sessions.\n// 5 minutes balances freshness with server load - flags typically don't change\n// frequently, and most sessions are shorter than this anyway.\nconst DEFAULT_REFRESH_INTERVAL = 5 * 60 * 1000\n\nexport class RemoteConfigLoader {\n private _refreshInterval: ReturnType | undefined\n\n constructor(private readonly _instance: PostHog) {}\n\n get remoteConfig(): RemoteConfig | undefined {\n return assignableWindow._POSTHOG_REMOTE_CONFIG?.[this._instance.config.token]?.config\n }\n\n private _loadRemoteConfigJs(cb: (config?: RemoteConfig) => void): void {\n if (assignableWindow.__PosthogExtensions__?.loadExternalDependency) {\n assignableWindow.__PosthogExtensions__?.loadExternalDependency?.(this._instance, 'remote-config', () => {\n return cb(this.remoteConfig)\n })\n } else {\n cb()\n }\n }\n\n private _loadRemoteConfigJSON(cb: (config?: RemoteConfig) => void): void {\n this._instance._send_request({\n method: 'GET',\n url: this._instance.requestRouter.endpointFor('assets', `/array/${this._instance.config.token}/config`),\n callback: (response) => {\n cb(response.json as RemoteConfig | undefined)\n },\n })\n }\n\n load(): void {\n try {\n // Attempt 1 - use the pre-loaded config if it came as part of the token-specific array.js\n if (this.remoteConfig) {\n logger.info('Using preloaded remote config', this.remoteConfig)\n this._onRemoteConfig(this.remoteConfig)\n this._startRefreshInterval()\n return\n }\n\n if (this._instance._shouldDisableFlags()) {\n // This setting is essentially saying \"dont call external APIs\" hence we respect it here\n logger.warn('Remote config is disabled. Falling back to local config.')\n return\n }\n\n // Attempt 2 - if we have the external deps loader then lets load the script version of the config that includes site apps\n this._loadRemoteConfigJs((config) => {\n if (!config) {\n logger.info('No config found after loading remote JS config. Falling back to JSON.')\n // Attempt 3 Load the config json instead of the script - we won't get site apps etc. but we will get the config\n this._loadRemoteConfigJSON((config) => {\n this._onRemoteConfig(config)\n this._startRefreshInterval()\n })\n return\n }\n\n this._onRemoteConfig(config)\n this._startRefreshInterval()\n })\n } catch (error) {\n logger.error('Error loading remote config', error)\n }\n }\n\n stop(): void {\n if (this._refreshInterval) {\n clearInterval(this._refreshInterval)\n this._refreshInterval = undefined\n }\n }\n\n /**\n * Refresh feature flags for long-running sessions.\n * Calls reloadFeatureFlags() directly rather than re-fetching config — the initial\n * config load already determined whether flags are enabled, and reloadFeatureFlags()\n * is a no-op when flags are disabled. This avoids an unnecessary network round-trip.\n */\n refresh(): void {\n if (this._instance._shouldDisableFlags() || document?.visibilityState === 'hidden') {\n return\n }\n\n this._instance.reloadFeatureFlags()\n }\n\n private _startRefreshInterval(): void {\n if (this._refreshInterval) {\n return\n }\n\n const intervalMs = this._instance.config.remote_config_refresh_interval_ms ?? DEFAULT_REFRESH_INTERVAL\n\n // Allow users to disable periodic refresh by setting interval to 0\n if (intervalMs === 0) {\n return\n }\n\n this._refreshInterval = setInterval(() => {\n this.refresh()\n }, intervalMs)\n }\n\n private _onRemoteConfig(config?: RemoteConfig): void {\n if (!config) {\n logger.error('Failed to fetch remote config from PostHog.')\n }\n\n // Config and flags are loaded separately: config from /array/{token}/config,\n // flags from /flags/?v=2. Features like surveys, session recording, and product\n // tours reference flags in their config (e.g. survey.linked_flag_key), but this\n // is safe because those flag checks happen lazily at runtime (e.g. when deciding\n // whether to show a survey), not during config processing. By the time a linked\n // flag is evaluated, flags have already loaded.\n //\n // Even when config fails, we pass an empty object so extensions (autocapture,\n // session recording, etc.) still initialize with their defaults.\n this._instance._onRemoteConfig(config ?? ({} as RemoteConfig))\n\n if (config?.hasFeatureFlags !== false) {\n if (!this._instance.config.advanced_disable_feature_flags_on_first_load) {\n this._instance.featureFlags?.ensureFlagsLoaded()\n }\n }\n }\n}\n", "import { PostHog } from './posthog-core'\nimport { Survey } from './posthog-surveys-types'\nimport { ConversationsRemoteConfig } from './posthog-conversations-types'\n\n// only importing types here, so won't affect the bundle\n// eslint-disable-next-line posthog-js/no-external-replay-imports\nimport type { SAMPLED } from './extensions/replay/external/triggerMatching'\n\n// Extension class types for __extensionClasses (type-only, no bundle impact)\nimport type { ExtensionConstructor } from './extensions/types'\nimport type { Autocapture } from './autocapture'\nimport type { DeadClicksAutocapture } from './extensions/dead-clicks-autocapture'\nimport type { ExceptionObserver } from './extensions/exception-autocapture'\nimport type { HistoryAutocapture } from './extensions/history-autocapture'\nimport type { TracingHeaders } from './extensions/tracing-headers'\nimport type { WebVitalsAutocapture } from './extensions/web-vitals'\nimport type { SessionRecording } from './extensions/replay/session-recording'\nimport type { Heatmaps } from './heatmaps'\nimport type { PostHogProductTours } from './posthog-product-tours'\nimport type { SiteApps } from './site-apps'\nimport type { PostHogSurveys } from './posthog-surveys'\nimport type { Toolbar } from './extensions/toolbar'\nimport type { PostHogExceptions } from './posthog-exceptions'\nimport type { WebExperiments } from './web-experiments'\nimport type { PostHogConversations } from './extensions/conversations/posthog-conversations'\nimport type { PostHogFeatureFlags } from './posthog-featureflags'\nimport type { PostHogLogs } from './posthog-logs'\n\n// ============================================================================\n// Re-export public types from @posthog/types\n// ============================================================================\n\n// Common types\nexport type { Property, Properties, JsonType, JsonRecord } from '@posthog/types'\n\n// Capture types\nexport type { KnownEventName, EventName, CaptureResult, CaptureOptions, BeforeSendFn } from '@posthog/types'\n\n// Feature flag types\nexport type {\n FeatureFlagsCallback,\n FeatureFlagDetail,\n FeatureFlagMetadata,\n EvaluationReason,\n FeatureFlagResult,\n FeatureFlagOptions,\n RemoteConfigFeatureFlagCallback,\n EarlyAccessFeature,\n EarlyAccessFeatureStage,\n EarlyAccessFeatureCallback,\n EarlyAccessFeatureResponse,\n FeatureFlagOverrides,\n FeatureFlagPayloadOverrides,\n FeatureFlagOverrideOptions,\n OverrideFeatureFlagsOptions,\n} from '@posthog/types'\n\n// Request types\nexport type { Headers, RequestResponse, RequestCallback } from '@posthog/types'\n\n// Session recording types\nexport type {\n SessionRecordingCanvasOptions,\n InitiatorType,\n NetworkRequest,\n CapturedNetworkRequest,\n SessionIdChangedCallback,\n SeverityLevel,\n} from '@posthog/types'\n\n// Config types\nexport type {\n AutocaptureCompatibleElement,\n DomAutocaptureEvents,\n AutocaptureConfig,\n RageclickConfig,\n BootstrapConfig,\n SupportedWebVitalsMetrics,\n PerformanceCaptureConfig,\n DeadClickCandidate,\n ExceptionAutoCaptureConfig,\n DeadClicksAutoCaptureConfig,\n HeatmapConfig,\n ConfigDefaults,\n ExternalIntegrationKind,\n ErrorTrackingOptions,\n MaskInputOptions,\n SlimDOMOptions,\n SessionRecordingOptions,\n RequestQueueConfig,\n} from '@posthog/types'\n\n// Toolbar types\nexport type { ToolbarUserIntent, ToolbarSource, ToolbarVersion, ToolbarParams } from '@posthog/types'\n\n// Log capture types\nexport type {\n LogSeverityLevel,\n OtlpSeverityText,\n OtlpSeverityEntry,\n LogAttributeValue,\n LogAttributes,\n CaptureLogOptions,\n Logger,\n OtlpAnyValue,\n OtlpKeyValue,\n OtlpLogRecord,\n OtlpLogsPayload,\n LogSdkContext,\n} from '@posthog/types'\n\n// Re-export KnownUnsafeEditableEvent from @posthog/core for backwards compatibility\nexport type { KnownUnsafeEditableEvent } from '@posthog/core'\n\n// ============================================================================\n// Browser-specific types that depend on local imports\n// These cannot be moved to @posthog/types as they reference browser-specific code\n// ============================================================================\n\n// Import types for internal use in this file\nimport type {\n SessionRecordingCanvasOptions,\n PerformanceCaptureConfig,\n InitiatorType,\n JsonType,\n Properties,\n EventName,\n CapturedNetworkRequest,\n SessionRecordingOptions,\n FeatureFlagDetail,\n ToolbarParams,\n PostHogConfig as BasePostHogConfig,\n PostHog as BasePostHogInterface,\n RequestResponse,\n} from '@posthog/types'\n\n/* Small override from the base class to make it more specific to the browser/src/posthog-core.ts file\n * This guarantees we'll be able to use `PostHogConfig` as implemented in the browser/src/posthog-core.ts file\n * using the proper `loaded` function signature.\n */\nexport type PostHogInterface = Omit\n\n/*\n * Specify that `loaded` should be using the PostHog instance type\n * as implemented by the browser/src/posthog-core.ts file rather than the @posthog/types type\n */\nexport type PostHogConfig = Omit & {\n loaded: (posthog: PostHogInterface) => void\n\n /**\n * Internal: Extension class overrides for tree-shaking support.\n * When provided, these classes are used instead of the default imports.\n * This enables entrypoints to control which extensions are bundled.\n * @internal\n */\n __extensionClasses?: {\n exceptions?: ExtensionConstructor\n historyAutocapture?: ExtensionConstructor\n tracingHeaders?: ExtensionConstructor\n siteApps?: ExtensionConstructor\n sessionRecording?: ExtensionConstructor\n autocapture?: ExtensionConstructor\n productTours?: ExtensionConstructor\n heatmaps?: ExtensionConstructor\n webVitalsAutocapture?: ExtensionConstructor\n exceptionObserver?: ExtensionConstructor\n deadClicksAutocapture?: ExtensionConstructor\n surveys?: ExtensionConstructor\n toolbar?: ExtensionConstructor\n experiments?: ExtensionConstructor\n conversations?: ExtensionConstructor\n featureFlags?: ExtensionConstructor\n logs?: ExtensionConstructor\n }\n}\n\n// See https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options\ntype NextOptions = { revalidate: false | 0 | number; tags: string[] }\n\nexport interface RequestWithOptions {\n url: string\n // Data can be a single object or an array of objects when batched\n data?: Record | Record[]\n headers?: Record\n transport?: 'XHR' | 'fetch' | 'sendBeacon'\n method?: 'POST' | 'GET'\n urlQueryArgs?: { compression: Compression }\n callback?: (response: RequestResponse) => void\n timeout?: number\n noRetries?: boolean\n disableTransport?: ('XHR' | 'fetch' | 'sendBeacon')[]\n disableXHRCredentials?: boolean\n compression?: Compression | 'best-available'\n fetchOptions?: {\n cache?: RequestInit['cache']\n next?: NextOptions\n }\n}\n\n// Queued request types - the same as a request but with additional queueing information\nexport interface QueuedRequestWithOptions extends RequestWithOptions {\n /** key of queue, e.g. 'sessionRecording' vs 'event' */\n batchKey?: string\n}\n\n// Used explicitly for retriable requests\nexport interface RetriableRequestWithOptions extends QueuedRequestWithOptions {\n retriesPerformedSoFar?: number\n}\n\nexport type FlagVariant = { flag: string; variant: string }\n\n/** the config stored in persistence when session recording remote config is received */\nexport type SessionRecordingPersistedConfig = Omit<\n SessionRecordingRemoteConfig,\n | 'recordCanvas'\n | 'canvasFps'\n | 'canvasQuality'\n | 'networkPayloadCapture'\n | 'sampleRate'\n | 'minimumDurationMilliseconds'\n> & {\n /**\n * Used to determine if the persisted config is still valid or we need to wait for a new one\n * only accepts undefined since older versions of the library didn't set this.\n */\n cache_timestamp?: number\n enabled: boolean\n networkPayloadCapture: SessionRecordingRemoteConfig['networkPayloadCapture'] & {\n capturePerformance: RemoteConfig['capturePerformance']\n }\n canvasRecording: {\n enabled: SessionRecordingRemoteConfig['recordCanvas']\n fps: SessionRecordingRemoteConfig['canvasFps']\n quality: SessionRecordingRemoteConfig['canvasQuality']\n }\n // we don't allow string config here\n sampleRate: number | null\n minimumDurationMilliseconds: number | null | undefined\n}\n\nexport type SessionRecordingRemoteConfig = SessionRecordingCanvasOptions & {\n endpoint?: string\n consoleLogRecordingEnabled?: boolean\n // the API returns a decimal between 0 and 1 as a string\n sampleRate?: string | null\n minimumDurationMilliseconds?: number\n linkedFlag?: string | FlagVariant | null\n networkPayloadCapture?: Pick\n masking?: Pick\n urlTriggers?: SessionRecordingUrlTrigger[]\n scriptConfig?: { script?: string | undefined }\n urlBlocklist?: SessionRecordingUrlTrigger[]\n eventTriggers?: string[]\n /**\n * Controls how event, url, sampling, and linked flag triggers are combined\n *\n * `any` means that if any of the triggers match, the session will be recorded\n * `all` means that all the triggers must match for the session to be recorded\n *\n * originally it was (event || url) && (sampling || linked flag)\n * which nobody wanted, now the default is all\n */\n triggerMatchType?: 'any' | 'all'\n /**\n * Config version - defaults to 1 (legacy)\n * When version is 2, triggerGroups is used instead of individual trigger fields\n */\n version?: 1 | 2\n /**\n * V2 Trigger Groups - multiple named trigger groups with their own conditions and sample rates\n * Only used when version === 2\n */\n triggerGroups?: SessionRecordingTriggerGroup[]\n}\n\n/**\n * Remote configuration for the PostHog instance\n *\n * All of these settings can be configured directly in your PostHog instance\n * Any configuration set in the client overrides the information from the server\n */\nexport interface RemoteConfig {\n /**\n * Supported compression algorithms\n */\n supportedCompression: Compression[]\n\n /**\n * If set, disables autocapture\n */\n autocapture_opt_out?: boolean\n\n /**\n * originally capturePerformance was replay only and so boolean true\n * is equivalent to { network_timing: true }\n * now capture performance can be separately enabled within replay\n * and as a standalone web vitals tracker\n * people can have them enabled separately\n * they work standalone but enhance each other\n * TODO: deprecate this so we make a new config that doesn't need this explanation\n */\n capturePerformance?: boolean | PerformanceCaptureConfig\n\n /**\n * Whether we should use a custom endpoint for analytics\n *\n * @default { endpoint: \"/e\" }\n */\n analytics?: {\n endpoint?: string\n }\n\n /**\n * Whether the `$elements_chain` property should be sent as a string or as an array\n *\n * @default false\n */\n elementsChainAsString?: boolean\n\n /**\n * Error tracking configuration options\n */\n errorTracking?: {\n autocaptureExceptions?: boolean\n captureExtensionExceptions?: boolean\n suppressionRules?: ErrorTrackingSuppressionRule[]\n }\n\n /**\n * Whether capturing logs to the logs product is enabled\n */\n logs?: {\n captureConsoleLogs?: boolean\n }\n\n /**\n * This is currently in development and may have breaking changes without a major version bump\n */\n autocaptureExceptions?: boolean | { endpoint?: string }\n\n /**\n * Session recording configuration options\n */\n sessionRecording?: SessionRecordingRemoteConfig | false\n\n /**\n * Whether surveys are enabled\n */\n surveys?: boolean | Survey[]\n\n /**\n * Whether product tours are enabled\n */\n productTours?: boolean\n\n /**\n * Parameters for the toolbar\n */\n toolbarParams: ToolbarParams\n\n /**\n * @deprecated renamed to toolbarParams, still present on older API responses\n */\n editorParams?: ToolbarParams\n\n /**\n * @deprecated, moved to toolbarParams\n */\n toolbarVersion: 'toolbar'\n\n /**\n * Whether the user is authenticated\n */\n isAuthenticated: boolean\n\n /**\n * List of site apps with their IDs and URLs\n */\n siteApps: { id: string; url: string }[]\n\n /**\n * Whether heatmaps are enabled\n */\n heatmaps?: boolean\n\n /**\n * Whether to only capture identified users by default\n */\n defaultIdentifiedOnly?: boolean\n\n /**\n * Whether to capture dead clicks\n */\n captureDeadClicks?: boolean\n\n /**\n * Indicates if the team has any flags enabled (if not we don't need to load them)\n */\n hasFeatureFlags?: boolean\n\n /**\n * Conversations widget configuration\n */\n conversations?: boolean | ConversationsRemoteConfig\n}\n\n/**\n * Flags returns feature flags and their payloads\n */\nexport interface FlagsResponse extends RemoteConfig {\n featureFlags: Record\n featureFlagPayloads: Record\n errorsWhileComputingFlags: boolean\n requestId?: string\n flags: Record\n evaluatedAt?: number\n}\n\nexport type SiteAppGlobals = {\n event: {\n uuid: string\n event: EventName\n properties: Properties\n timestamp?: Date\n elements_chain?: string\n distinct_id?: string\n }\n person: {\n properties: Properties\n }\n groups: Record\n}\n\nexport type SiteAppLoader = {\n id: string\n init: (config: { posthog: PostHog; callback: (success: boolean) => void }) => {\n processEvent?: (globals: SiteAppGlobals) => void\n }\n}\n\nexport type SiteApp = {\n id: string\n loaded: boolean\n errored: boolean\n processedBuffer: boolean\n processEvent?: (globals: SiteAppGlobals) => void\n}\n\nexport interface PersistentStore {\n _is_supported: () => boolean\n _error: (error: any) => void\n _parse: (name: string) => any\n _get: (name: string) => any\n _set: (\n name: string,\n value: any,\n expire_days?: number | null,\n cross_subdomain?: boolean,\n secure?: boolean,\n debug?: boolean\n ) => void\n _remove: (name: string, cross_subdomain?: boolean) => void\n}\n\nexport type EventHandler = (event: Event) => boolean | void\n\nexport type SnippetArrayItem = [method: string, ...args: any[]]\n\nexport type NetworkRecordOptions = {\n initiatorTypes?: InitiatorType[]\n maskRequestFn?: (data: CapturedNetworkRequest) => CapturedNetworkRequest | undefined\n recordHeaders?: boolean | { request: boolean; response: boolean }\n recordBody?: boolean | string[] | { request: boolean | string[]; response: boolean | string[] }\n recordInitialRequests?: boolean\n /**\n * whether to record PerformanceEntry events for network requests\n */\n recordPerformance?: boolean\n /**\n * the PerformanceObserver will only observe these entry types\n */\n performanceEntryTypeToObserve: string[]\n /**\n * the maximum size of the request/response body to record\n * NB this will be at most 1MB even if set larger\n */\n payloadSizeLimitBytes: number\n /**\n * some domains we should never record the payload\n * for example other companies session replay ingestion payloads aren't super useful but are gigantic\n * if this isn't provided we use a default list\n * if this is provided - we add the provided list to the default list\n * i.e. we never record the payloads on the default deny list\n */\n payloadHostDenyList?: string[]\n}\n\nexport type ErrorEventArgs = [\n event: string | Event,\n source?: string | undefined,\n lineno?: number | undefined,\n colno?: number | undefined,\n error?: Error | undefined,\n]\n\n// levels originally copied from Sentry to work with the sentry integration\n// and to avoid relying on a frequently changing @sentry/types dependency\n// but provided as an array of literal types, so we can constrain the level below\nexport const severityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'] as const\n\nexport interface SessionRecordingUrlTrigger {\n url: string\n matching: 'regex'\n}\n\n/**\n * V2 event trigger - always an object with name, optionally with property filters.\n * The server normalizes bare event name strings to this shape before sending.\n */\nexport interface SessionRecordingEventTrigger {\n name: string\n properties?: SessionRecordingTriggerPropertyFilter[]\n}\n\nexport interface SessionRecordingTriggerPropertyFilter {\n key: string\n type: 'event' | 'person'\n operator?: 'exact' | 'is_not' | 'icontains' | 'not_icontains' | 'regex' | 'not_regex' | 'gt' | 'lt'\n value?: string | number | boolean | string[]\n}\n\n/**\n * V2 Trigger Group - represents a single trigger group with its own conditions and sample rate\n */\nexport interface SessionRecordingTriggerGroup {\n id: string\n name: string\n sampleRate: number\n minDurationMs?: number\n conditions: {\n matchType: 'any' | 'all'\n events?: SessionRecordingEventTrigger[]\n urls?: SessionRecordingUrlTrigger[]\n flag?: string | FlagVariant\n properties?: SessionRecordingTriggerPropertyFilter[]\n }\n}\n\nexport type PropertyMatchType = 'regex' | 'not_regex' | 'exact' | 'is_not' | 'icontains' | 'not_icontains'\n\nexport interface ErrorTrackingSuppressionRule {\n type: 'AND' | 'OR'\n values: ErrorTrackingSuppressionRuleValue[]\n}\n\nexport interface ErrorTrackingSuppressionRuleValue {\n key: '$exception_types' | '$exception_values'\n operator: PropertyMatchType\n value: string | string[]\n type: string\n}\n\nexport type SessionStartReason =\n | 'sampling_overridden'\n | 'recording_initialized'\n | 'linked_flag_matched'\n | 'linked_flag_overridden'\n | typeof SAMPLED\n | 'session_id_changed'\n | 'url_trigger_matched'\n | 'event_trigger_matched'\n\nexport type OverrideConfig = {\n sampling: boolean\n linked_flag: boolean\n url_trigger: boolean\n event_trigger: boolean\n}\n\nexport const Compression = {\n GZipJS: 'gzip-js',\n Base64: 'base64',\n} as const\nexport type Compression = (typeof Compression)[keyof typeof Compression]\n", "// DEFLATE is a complex format; to read this code, you should probably check the RFC first:\n// https://tools.ietf.org/html/rfc1951\n// You may also wish to take a look at the guide I made about this program:\n// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad\n// Much of the following code is similar to that of UZIP.js:\n// https://github.com/photopea/UZIP.js\n// Many optimizations have been made, so the bundle size is ultimately smaller but performance is similar.\n// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint\n// is better for memory in most engines (I *think*).\nvar ch2 = {};\nvar wk = (function (c, id, msg, transfer, cb) {\n var u = ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([c], { type: 'text/javascript' })));\n var w = new Worker(u);\n w.onerror = function (e) { return cb(e.error, null); };\n w.onmessage = function (e) { return cb(null, e.data); };\n w.postMessage(msg, transfer);\n return w;\n});\n\n// aliases for shorter compressed code (most minifers don't do this)\nvar u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;\n// fixed length extra bits\nvar fleb = new u8([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, /* unused */ 0, 0, /* impossible */ 0]);\n// fixed distance extra bits\n// see fleb note\nvar fdeb = new u8([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, /* unused */ 0, 0]);\n// code length index map\nvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n// get base, reverse index map from extra bits\nvar freb = function (eb, start) {\n var b = new u16(31);\n for (var i = 0; i < 31; ++i) {\n b[i] = start += 1 << eb[i - 1];\n }\n // numbers here are at max 18 bits\n var r = new u32(b[30]);\n for (var i = 1; i < 30; ++i) {\n for (var j = b[i]; j < b[i + 1]; ++j) {\n r[j] = ((j - b[i]) << 5) | i;\n }\n }\n return [b, r];\n};\nvar _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];\n// we can ignore the fact that the other numbers are wrong; they never happen anyway\nfl[28] = 258, revfl[258] = 28;\nvar _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1];\n// map of value to reverse (assuming 16 bits)\nvar rev = new u16(32768);\nfor (var i = 0; i < 32768; ++i) {\n // reverse table algorithm from SO\n var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);\n x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);\n x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);\n rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;\n}\n// create huffman tree from u8 \"map\": index -> code length for code index\n// mb (max bits) must be at most 15\n// TODO: optimize/split up?\nvar hMap = (function (cd, mb, r) {\n var s = cd.length;\n // index\n var i = 0;\n // u16 \"map\": index -> # of codes with bit length = index\n var l = new u16(mb);\n // length of cd must be 288 (total # of codes)\n for (; i < s; ++i)\n ++l[cd[i] - 1];\n // u16 \"map\": index -> minimum code for bit length = index\n var le = new u16(mb);\n for (i = 0; i < mb; ++i) {\n le[i] = (le[i - 1] + l[i - 1]) << 1;\n }\n var co;\n if (r) {\n // u16 \"map\": index -> number of actual bits, symbol for code\n co = new u16(1 << mb);\n // bits to remove for reverser\n var rvb = 15 - mb;\n for (i = 0; i < s; ++i) {\n // ignore 0 lengths\n if (cd[i]) {\n // num encoding both symbol and bits read\n var sv = (i << 4) | cd[i];\n // free bits\n var r_1 = mb - cd[i];\n // start value\n var v = le[cd[i] - 1]++ << r_1;\n // m is end value\n for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {\n // every 16 bit value starting with the code yields the same result\n co[rev[v] >>> rvb] = sv;\n }\n }\n }\n }\n else {\n co = new u16(s);\n for (i = 0; i < s; ++i)\n co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]);\n }\n return co;\n});\n// fixed length tree\nvar flt = new u8(288);\nfor (var i = 0; i < 144; ++i)\n flt[i] = 8;\nfor (var i = 144; i < 256; ++i)\n flt[i] = 9;\nfor (var i = 256; i < 280; ++i)\n flt[i] = 7;\nfor (var i = 280; i < 288; ++i)\n flt[i] = 8;\n// fixed distance tree\nvar fdt = new u8(32);\nfor (var i = 0; i < 32; ++i)\n fdt[i] = 5;\n// fixed length map\nvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);\n// fixed distance map\nvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);\n// find max of array\nvar max = function (a) {\n var m = a[0];\n for (var i = 1; i < a.length; ++i) {\n if (a[i] > m)\n m = a[i];\n }\n return m;\n};\n// read d, starting at bit p and mask with m\nvar bits = function (d, p, m) {\n var o = (p / 8) >> 0;\n return ((d[o] | (d[o + 1] << 8)) >>> (p & 7)) & m;\n};\n// read d, starting at bit p continuing for at least 16 bits\nvar bits16 = function (d, p) {\n var o = (p / 8) >> 0;\n return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >>> (p & 7));\n};\n// get end of byte\nvar shft = function (p) { return ((p / 8) >> 0) + (p & 7 && 1); };\n// typed array slice - allows garbage collector to free original reference,\n// while being more compatible than .slice\nvar slc = function (v, s, e) {\n if (s == null || s < 0)\n s = 0;\n if (e == null || e > v.length)\n e = v.length;\n // can't use .constructor in case user-supplied\n var n = new (v instanceof u16 ? u16 : v instanceof u32 ? u32 : u8)(e - s);\n n.set(v.subarray(s, e));\n return n;\n};\n// expands raw DEFLATE data\nvar inflt = function (dat, buf, st) {\n // source length\n var sl = dat.length;\n // have to estimate size\n var noBuf = !buf || st;\n // no state\n var noSt = !st || st.i;\n if (!st)\n st = {};\n // Assumes roughly 33% compression ratio average\n if (!buf)\n buf = new u8(sl * 3);\n // ensure buffer can fit at least l elements\n var cbuf = function (l) {\n var bl = buf.length;\n // need to increase size to fit\n if (l > bl) {\n // Double or set to necessary, whichever is greater\n var nbuf = new u8(Math.max(bl * 2, l));\n nbuf.set(buf);\n buf = nbuf;\n }\n };\n // last chunk bitpos bytes\n var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;\n // total bits\n var tbts = sl * 8;\n do {\n if (!lm) {\n // BFINAL - this is only 1 when last chunk is next\n st.f = final = bits(dat, pos, 1);\n // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman\n var type = bits(dat, pos + 1, 3);\n pos += 3;\n if (!type) {\n // go to end of byte boundary\n var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;\n if (t > sl) {\n if (noSt)\n throw 'unexpected EOF';\n break;\n }\n // ensure size\n if (noBuf)\n cbuf(bt + l);\n // Copy over uncompressed data\n buf.set(dat.subarray(s, t), bt);\n // Get new bitpos, update byte count\n st.b = bt += l, st.p = pos = t * 8;\n continue;\n }\n else if (type == 1)\n lm = flrm, dm = fdrm, lbt = 9, dbt = 5;\n else if (type == 2) {\n // literal lengths\n var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;\n var tl = hLit + bits(dat, pos + 5, 31) + 1;\n pos += 14;\n // length+distance tree\n var ldt = new u8(tl);\n // code length tree\n var clt = new u8(19);\n for (var i = 0; i < hcLen; ++i) {\n // use index map to get real code\n clt[clim[i]] = bits(dat, pos + i * 3, 7);\n }\n pos += hcLen * 3;\n // code lengths bits\n var clb = max(clt), clbmsk = (1 << clb) - 1;\n if (!noSt && pos + tl * (clb + 7) > tbts)\n break;\n // code lengths map\n var clm = hMap(clt, clb, 1);\n for (var i = 0; i < tl;) {\n var r = clm[bits(dat, pos, clbmsk)];\n // bits read\n pos += r & 15;\n // symbol\n var s = r >>> 4;\n // code length to copy\n if (s < 16) {\n ldt[i++] = s;\n }\n else {\n // copy count\n var c = 0, n = 0;\n if (s == 16)\n n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];\n else if (s == 17)\n n = 3 + bits(dat, pos, 7), pos += 3;\n else if (s == 18)\n n = 11 + bits(dat, pos, 127), pos += 7;\n while (n--)\n ldt[i++] = c;\n }\n }\n // length tree distance tree\n var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);\n // max length bits\n lbt = max(lt);\n // max dist bits\n dbt = max(dt);\n lm = hMap(lt, lbt, 1);\n dm = hMap(dt, dbt, 1);\n }\n else\n throw 'invalid block type';\n if (pos > tbts)\n throw 'unexpected EOF';\n }\n // Make sure the buffer can hold this + the largest possible addition\n // Maximum chunk size (practically, theoretically infinite) is 2^17;\n if (noBuf)\n cbuf(bt + 131072);\n var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;\n var mxa = lbt + dbt + 18;\n while (noSt || pos + mxa < tbts) {\n // bits read, code\n var c = lm[bits16(dat, pos) & lms], sym = c >>> 4;\n pos += c & 15;\n if (pos > tbts)\n throw 'unexpected EOF';\n if (!c)\n throw 'invalid length/literal';\n if (sym < 256)\n buf[bt++] = sym;\n else if (sym == 256) {\n lm = null;\n break;\n }\n else {\n var add = sym - 254;\n // no extra bits needed if less\n if (sym > 264) {\n // index\n var i = sym - 257, b = fleb[i];\n add = bits(dat, pos, (1 << b) - 1) + fl[i];\n pos += b;\n }\n // dist\n var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;\n if (!d)\n throw 'invalid distance';\n pos += d & 15;\n var dt = fd[dsym];\n if (dsym > 3) {\n var b = fdeb[dsym];\n dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;\n }\n if (pos > tbts)\n throw 'unexpected EOF';\n if (noBuf)\n cbuf(bt + 131072);\n var end = bt + add;\n for (; bt < end; bt += 4) {\n buf[bt] = buf[bt - dt];\n buf[bt + 1] = buf[bt + 1 - dt];\n buf[bt + 2] = buf[bt + 2 - dt];\n buf[bt + 3] = buf[bt + 3 - dt];\n }\n bt = end;\n }\n }\n st.l = lm, st.p = pos, st.b = bt;\n if (lm)\n final = 1, st.m = lbt, st.d = dm, st.n = dbt;\n } while (!final);\n return bt == buf.length ? buf : slc(buf, 0, bt);\n};\n// starting at p, write the minimum number of bits that can hold v to d\nvar wbits = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) >> 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n};\n// starting at p, write the minimum number of bits (>8) that can hold v to d\nvar wbits16 = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) >> 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n d[o + 2] |= v >>> 16;\n};\n// creates code lengths from a frequency table\nvar hTree = function (d, mb) {\n // Need extra info to make a tree\n var t = [];\n for (var i = 0; i < d.length; ++i) {\n if (d[i])\n t.push({ s: i, f: d[i] });\n }\n var s = t.length;\n var t2 = t.slice();\n if (!s)\n return [new u8(0), 0];\n if (s == 1) {\n var v = new u8(t[0].s + 1);\n v[t[0].s] = 1;\n return [v, 1];\n }\n t.sort(function (a, b) { return a.f - b.f; });\n // after i2 reaches last ind, will be stopped\n // freq must be greater than largest possible number of symbols\n t.push({ s: -1, f: 25001 });\n var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;\n t[0] = { s: -1, f: l.f + r.f, l: l, r: r };\n // efficient algorithm from UZIP.js\n // i0 is lookbehind, i2 is lookahead - after processing two low-freq\n // symbols that combined have high freq, will start processing i2 (high-freq,\n // non-composite) symbols instead\n // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/\n while (i1 != s - 1) {\n l = t[t[i0].f < t[i2].f ? i0++ : i2++];\n r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];\n t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };\n }\n var maxSym = t2[0].s;\n for (var i = 1; i < s; ++i) {\n if (t2[i].s > maxSym)\n maxSym = t2[i].s;\n }\n // code lengths\n var tr = new u16(maxSym + 1);\n // max bits in tree\n var mbt = ln(t[i1 - 1], tr, 0);\n if (mbt > mb) {\n // more algorithms from UZIP.js\n // TODO: find out how this code works (debt)\n // ind debt\n var i = 0, dt = 0;\n // left cost\n var lft = mbt - mb, cst = 1 << lft;\n t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });\n for (; i < s; ++i) {\n var i2_1 = t2[i].s;\n if (tr[i2_1] > mb) {\n dt += cst - (1 << (mbt - tr[i2_1]));\n tr[i2_1] = mb;\n }\n else\n break;\n }\n dt >>>= lft;\n while (dt > 0) {\n var i2_2 = t2[i].s;\n if (tr[i2_2] < mb)\n dt -= 1 << (mb - tr[i2_2]++ - 1);\n else\n ++i;\n }\n for (; i >= 0 && dt; --i) {\n var i2_3 = t2[i].s;\n if (tr[i2_3] == mb) {\n --tr[i2_3];\n ++dt;\n }\n }\n mbt = mb;\n }\n return [new u8(tr), mbt];\n};\n// get the max length and assign length codes\nvar ln = function (n, l, d) {\n return n.s == -1\n ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))\n : (l[n.s] = d);\n};\n// length codes generation\nvar lc = function (c) {\n var s = c.length;\n // Note that the semicolon was intentional\n while (s && !c[--s])\n ;\n var cl = new u16(++s);\n // ind num streak\n var cli = 0, cln = c[0], cls = 1;\n var w = function (v) { cl[cli++] = v; };\n for (var i = 1; i <= s; ++i) {\n if (c[i] == cln && i != s)\n ++cls;\n else {\n if (!cln && cls > 2) {\n for (; cls > 138; cls -= 138)\n w(32754);\n if (cls > 2) {\n w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);\n cls = 0;\n }\n }\n else if (cls > 3) {\n w(cln), --cls;\n for (; cls > 6; cls -= 6)\n w(8304);\n if (cls > 2)\n w(((cls - 3) << 5) | 8208), cls = 0;\n }\n while (cls--)\n w(cln);\n cls = 1;\n cln = c[i];\n }\n }\n return [cl.subarray(0, cli), s];\n};\n// calculate the length of output from tree, code lengths\nvar clen = function (cf, cl) {\n var l = 0;\n for (var i = 0; i < cl.length; ++i)\n l += cf[i] * cl[i];\n return l;\n};\n// writes a fixed block\n// returns the new bit pos\nvar wfblk = function (out, pos, dat) {\n // no need to write 00 as type: TypedArray defaults to 0\n var s = dat.length;\n var o = shft(pos + 2);\n out[o] = s & 255;\n out[o + 1] = s >>> 8;\n out[o + 2] = out[o] ^ 255;\n out[o + 3] = out[o + 1] ^ 255;\n for (var i = 0; i < s; ++i)\n out[o + i + 4] = dat[i];\n return (o + 4 + s) * 8;\n};\n// writes a block\nvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {\n wbits(out, p++, final);\n ++lf[256];\n var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1];\n var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1];\n var _c = lc(dlt), lclt = _c[0], nlc = _c[1];\n var _d = lc(ddt), lcdt = _d[0], ndc = _d[1];\n var lcfreq = new u16(19);\n for (var i = 0; i < lclt.length; ++i)\n lcfreq[lclt[i] & 31]++;\n for (var i = 0; i < lcdt.length; ++i)\n lcfreq[lcdt[i] & 31]++;\n var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1];\n var nlcc = 19;\n for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)\n ;\n var flen = (bl + 5) << 3;\n var ftlen = clen(lf, flt) + clen(df, fdt) + eb;\n var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]);\n if (flen <= ftlen && flen <= dtlen)\n return wfblk(out, p, dat.subarray(bs, bs + bl));\n var lm, ll, dm, dl;\n wbits(out, p, 1 + (dtlen < ftlen)), p += 2;\n if (dtlen < ftlen) {\n lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;\n var llm = hMap(lct, mlcb, 0);\n wbits(out, p, nlc - 257);\n wbits(out, p + 5, ndc - 1);\n wbits(out, p + 10, nlcc - 4);\n p += 14;\n for (var i = 0; i < nlcc; ++i)\n wbits(out, p + 3 * i, lct[clim[i]]);\n p += 3 * nlcc;\n var lcts = [lclt, lcdt];\n for (var it = 0; it < 2; ++it) {\n var clct = lcts[it];\n for (var i = 0; i < clct.length; ++i) {\n var len = clct[i] & 31;\n wbits(out, p, llm[len]), p += lct[len];\n if (len > 15)\n wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12;\n }\n }\n }\n else {\n lm = flm, ll = flt, dm = fdm, dl = fdt;\n }\n for (var i = 0; i < li; ++i) {\n if (syms[i] > 255) {\n var len = (syms[i] >>> 18) & 31;\n wbits16(out, p, lm[len + 257]), p += ll[len + 257];\n if (len > 7)\n wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len];\n var dst = syms[i] & 31;\n wbits16(out, p, dm[dst]), p += dl[dst];\n if (dst > 3)\n wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst];\n }\n else {\n wbits16(out, p, lm[syms[i]]), p += ll[syms[i]];\n }\n }\n wbits16(out, p, lm[256]);\n return p + ll[256];\n};\n// deflate options (nice << 13) | chain\nvar deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);\n// empty\nvar et = /*#__PURE__*/ new u8(0);\n// compresses data into a raw DEFLATE buffer\nvar dflt = function (dat, lvl, plvl, pre, post, lst) {\n var s = dat.length;\n var o = new u8(pre + s + 5 * (1 + Math.floor(s / 7000)) + post);\n // writing to this writes to the output buffer\n var w = o.subarray(pre, o.length - post);\n var pos = 0;\n if (!lvl || s < 8) {\n for (var i = 0; i <= s; i += 65535) {\n // end\n var e = i + 65535;\n if (e < s) {\n // write full block\n pos = wfblk(w, pos, dat.subarray(i, e));\n }\n else {\n // write final block\n w[i] = lst;\n pos = wfblk(w, pos, dat.subarray(i, s));\n }\n }\n }\n else {\n var opt = deo[lvl - 1];\n var n = opt >>> 13, c = opt & 8191;\n var msk_1 = (1 << plvl) - 1;\n // prev 2-byte val map curr 2-byte val map\n var prev = new u16(32768), head = new u16(msk_1 + 1);\n var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;\n var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };\n // 24576 is an arbitrary number of maximum symbols per block\n // 424 buffer for last block\n var syms = new u32(25000);\n // length/literal freq distance freq\n var lf = new u16(288), df = new u16(32);\n // l/lcnt exbits index l/lind waitdx bitpos\n var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0;\n for (; i < s; ++i) {\n // hash value\n var hv = hsh(i);\n // index mod 32768\n var imod = i & 32767;\n // previous index with this value\n var pimod = head[hv];\n prev[imod] = pimod;\n head[hv] = imod;\n // We always should modify head and prev, but only add symbols if\n // this data is not yet processed (\"wait\" for wait index)\n if (wi <= i) {\n // bytes remaining\n var rem = s - i;\n if ((lc_1 > 7000 || li > 24576) && rem > 423) {\n pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);\n li = lc_1 = eb = 0, bs = i;\n for (var j = 0; j < 286; ++j)\n lf[j] = 0;\n for (var j = 0; j < 30; ++j)\n df[j] = 0;\n }\n // len dist chain\n var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767;\n if (rem > 2 && hv == hsh(i - dif)) {\n var maxn = Math.min(n, rem) - 1;\n var maxd = Math.min(32767, i);\n // max possible length\n // not capped at dif because decompressors implement \"rolling\" index population\n var ml = Math.min(258, rem);\n while (dif <= maxd && --ch_1 && imod != pimod) {\n if (dat[i + l] == dat[i + l - dif]) {\n var nl = 0;\n for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)\n ;\n if (nl > l) {\n l = nl, d = dif;\n // break out early when we reach \"nice\" (we are satisfied enough)\n if (nl > maxn)\n break;\n // now, find the rarest 2-byte sequence within this\n // length of literals and search for that instead.\n // Much faster than just using the start\n var mmd = Math.min(dif, nl - 2);\n var md = 0;\n for (var j = 0; j < mmd; ++j) {\n var ti = (i - dif + j + 32768) & 32767;\n var pti = prev[ti];\n var cd = (ti - pti + 32768) & 32767;\n if (cd > md)\n md = cd, pimod = ti;\n }\n }\n }\n // check the previous match\n imod = pimod, pimod = prev[imod];\n dif += (imod - pimod + 32768) & 32767;\n }\n }\n // d will be nonzero only when a match was found\n if (d) {\n // store both dist and len data in one Uint32\n // Make sure this is recognized as a len/dist with 28th bit (2^28)\n syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];\n var lin = revfl[l] & 31, din = revfd[d] & 31;\n eb += fleb[lin] + fdeb[din];\n ++lf[257 + lin];\n ++df[din];\n wi = i + l;\n ++lc_1;\n }\n else {\n syms[li++] = dat[i];\n ++lf[dat[i]];\n }\n }\n }\n pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);\n // this is the easiest way to avoid needing to maintain state\n if (!lst)\n pos = wfblk(w, pos, et);\n }\n return slc(o, 0, pre + shft(pos) + post);\n};\n// CRC32 table\nvar crct = /*#__PURE__*/ (function () {\n var t = new u32(256);\n for (var i = 0; i < 256; ++i) {\n var c = i, k = 9;\n while (--k)\n c = ((c & 1) && 0xEDB88320) ^ (c >>> 1);\n t[i] = c;\n }\n return t;\n})();\n// CRC32\nvar crc = function () {\n var c = 0xFFFFFFFF;\n return {\n p: function (d) {\n // closures have awful performance\n var cr = c;\n for (var i = 0; i < d.length; ++i)\n cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);\n c = cr;\n },\n d: function () { return c ^ 0xFFFFFFFF; }\n };\n};\n// Alder32\nvar adler = function () {\n var a = 1, b = 0;\n return {\n p: function (d) {\n // closures have awful performance\n var n = a, m = b;\n var l = d.length;\n for (var i = 0; i != l;) {\n var e = Math.min(i + 5552, l);\n for (; i < e; ++i)\n n += d[i], m += n;\n n %= 65521, m %= 65521;\n }\n a = n, b = m;\n },\n d: function () { return ((a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8)) + ((a & 255) << 23) * 2; }\n };\n};\n;\n// deflate with opts\nvar dopt = function (dat, opt, pre, post, st) {\n return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st);\n};\n// Walmart object spread\nvar mrg = function (a, b) {\n var o = {};\n for (var k in a)\n o[k] = a[k];\n for (var k in b)\n o[k] = b[k];\n return o;\n};\n// worker clone\n// This is possibly the craziest part of the entire codebase, despite how simple it may seem.\n// The only parameter to this function is a closure that returns an array of variables outside of the function scope.\n// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.\n// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).\n// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.\n// This took me three weeks to figure out how to do.\nvar wcln = function (fn, fnStr, td) {\n var dt = fn();\n var st = fn.toString();\n var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/ /g, '').split(',');\n for (var i = 0; i < dt.length; ++i) {\n var v = dt[i], k = ks[i];\n if (typeof v == 'function') {\n fnStr += ';' + k + '=';\n var st_1 = v.toString();\n if (v.prototype) {\n // for global objects\n if (st_1.indexOf('[native code]') != -1) {\n var spInd = st_1.indexOf(' ', 8) + 1;\n fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));\n }\n else {\n fnStr += st_1;\n for (var t in v.prototype)\n fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();\n }\n }\n else\n fnStr += st_1;\n }\n else\n td[k] = v;\n }\n return [fnStr, td];\n};\nvar ch = [];\n// clone bufs\nvar cbfs = function (v) {\n var tl = [];\n for (var k in v) {\n if (v[k] instanceof u8 || v[k] instanceof u16 || v[k] instanceof u32)\n tl.push((v[k] = new v[k].constructor(v[k])).buffer);\n }\n return tl;\n};\n// use a worker to execute code\nvar wrkr = function (fns, init, id, cb) {\n var _a;\n if (!ch[id]) {\n var fnStr = '', td_1 = {}, m = fns.length - 1;\n for (var i = 0; i < m; ++i)\n _a = wcln(fns[i], fnStr, td_1), fnStr = _a[0], td_1 = _a[1];\n ch[id] = wcln(fns[m], fnStr, td_1);\n }\n var td = mrg({}, ch[id][1]);\n return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);\n};\n// base async inflate fn\nvar bInflt = function () { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, hMap, max, bits, bits16, shft, slc, inflt, inflateSync, pbf, gu8]; };\nvar bDflt = function () { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };\n// gzip extra\nvar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };\n// gunzip extra\nvar guze = function () { return [gzs, gzl]; };\n// zlib extra\nvar zle = function () { return [zlh, wbytes, adler]; };\n// unzlib extra\nvar zule = function () { return [zlv]; };\n// post buf\nvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };\n// get u8\nvar gu8 = function (o) { return o && o.size && new u8(o.size); };\n// async helper\nvar cbify = function (dat, opts, fns, init, id, cb) {\n var w = wrkr(fns, init, id, function (err, dat) {\n w.terminate();\n cb(err, dat);\n });\n if (!opts.consume)\n dat = new u8(dat);\n w.postMessage([dat, opts], [dat.buffer]);\n return function () { w.terminate(); };\n};\n// auto stream\nvar astrm = function (strm) {\n strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };\n return function (ev) { return strm.push(ev.data[0], ev.data[1]); };\n};\n// async stream attach\nvar astrmify = function (fns, strm, opts, init, id) {\n var t;\n var w = wrkr(fns, init, id, function (err, dat) {\n if (err)\n w.terminate(), strm.ondata.call(strm, err);\n else {\n if (dat[1])\n w.terminate();\n strm.ondata.call(strm, err, dat[0], dat[1]);\n }\n });\n w.postMessage(opts);\n strm.push = function (d, f) {\n if (t)\n throw 'stream finished';\n if (!strm.ondata)\n throw 'no stream handler';\n w.postMessage([d, t = f], [d.buffer]);\n };\n strm.terminate = function () { w.terminate(); };\n};\n// read 2 bytes\nvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };\n// read 4 bytes\nvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16)) + (d[b + 3] << 23) * 2; };\n// write bytes\nvar wbytes = function (d, b, v) {\n for (; v; ++b)\n d[b] = v, v >>>= 8;\n};\n// gzip header\nvar gzh = function (c, o) {\n var fn = o.filename;\n c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix\n if (o.mtime != 0)\n wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));\n if (fn) {\n c[3] = 8;\n for (var i = 0; i <= fn.length; ++i)\n c[i + 10] = fn.charCodeAt(i);\n }\n};\n// gzip footer: -8 to -4 = CRC, -4 to -0 is length\n// gzip start\nvar gzs = function (d) {\n if (d[0] != 31 || d[1] != 139 || d[2] != 8)\n throw 'invalid gzip data';\n var flg = d[3];\n var st = 10;\n if (flg & 4)\n st += d[10] | (d[11] << 8) + 2;\n for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])\n ;\n return st + (flg & 2);\n};\n// gzip length\nvar gzl = function (d) {\n var l = d.length;\n return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) + (2 * (d[l - 1] << 23));\n};\n// gzip header length\nvar gzhl = function (o) { return 10 + ((o.filename && (o.filename.length + 1)) || 0); };\n// zlib header\nvar zlh = function (c, o) {\n var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;\n c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1);\n};\n// zlib valid\nvar zlv = function (d) {\n if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31))\n throw 'invalid zlib data';\n if (d[1] & 32)\n throw 'invalid zlib data: preset dictionaries not supported';\n};\nfunction AsyncCmpStrm(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n return opts;\n}\n// zlib footer: -4 to -0 is Adler32\n/**\n * Streaming DEFLATE compression\n */\nvar Deflate = /*#__PURE__*/ (function () {\n function Deflate(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n this.o = opts || {};\n }\n Deflate.prototype.p = function (c, f) {\n this.ondata(dopt(c, this.o, 0, 0, !f), f);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Deflate.prototype.push = function (chunk, final) {\n if (this.d)\n throw 'stream finished';\n if (!this.ondata)\n throw 'no stream handler';\n this.d = final;\n this.p(chunk, final || false);\n };\n return Deflate;\n}());\nexport { Deflate };\n/**\n * Asynchronous streaming DEFLATE compression\n */\nvar AsyncDeflate = /*#__PURE__*/ (function () {\n function AsyncDeflate(opts, cb) {\n astrmify([\n bDflt,\n function () { return [astrm, Deflate]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Deflate(ev.data);\n onmessage = astrm(strm);\n }, 6);\n }\n return AsyncDeflate;\n}());\nexport { AsyncDeflate };\nexport function deflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return cbify(data, opts, [\n bDflt,\n ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);\n}\n/**\n * Compresses data with DEFLATE without any wrapper\n * @param data The data to compress\n * @param opts The compression options\n * @returns The deflated version of the data\n */\nexport function deflateSync(data, opts) {\n if (opts === void 0) { opts = {}; }\n return dopt(data, opts, 0, 0);\n}\n/**\n * Streaming DEFLATE decompression\n */\nvar Inflate = /*#__PURE__*/ (function () {\n /**\n * Creates an inflation stream\n * @param cb The callback to call whenever data is inflated\n */\n function Inflate(cb) {\n this.s = {};\n this.p = new u8(0);\n this.ondata = cb;\n }\n Inflate.prototype.e = function (c) {\n if (this.d)\n throw 'stream finished';\n if (!this.ondata)\n throw 'no stream handler';\n var l = this.p.length;\n var n = new u8(l + c.length);\n n.set(this.p), n.set(c, l), this.p = n;\n };\n Inflate.prototype.c = function (final) {\n this.d = this.s.i = final || false;\n var bts = this.s.b;\n var dt = inflt(this.p, this.o, this.s);\n this.ondata(slc(dt, bts, this.s.b), this.d);\n this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;\n this.p = slc(this.p, (this.s.p / 8) >> 0), this.s.p &= 7;\n };\n /**\n * Pushes a chunk to be inflated\n * @param chunk The chunk to push\n * @param final Whether this is the final chunk\n */\n Inflate.prototype.push = function (chunk, final) {\n this.e(chunk), this.c(final);\n };\n return Inflate;\n}());\nexport { Inflate };\n/**\n * Asynchronous streaming DEFLATE decompression\n */\nvar AsyncInflate = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous inflation stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncInflate(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n function () { return [astrm, Inflate]; }\n ], this, 0, function () {\n var strm = new Inflate();\n onmessage = astrm(strm);\n }, 7);\n }\n return AsyncInflate;\n}());\nexport { AsyncInflate };\nexport function inflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return cbify(data, opts, [\n bInflt\n ], function (ev) { return pbf(inflateSync(ev.data[0], gu8(ev.data[1]))); }, 1, cb);\n}\n/**\n * Expands DEFLATE data with no wrapper\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function inflateSync(data, out) {\n return inflt(data, out);\n}\n// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.\n/**\n * Streaming GZIP compression\n */\nvar Gzip = /*#__PURE__*/ (function () {\n function Gzip(opts, cb) {\n this.c = crc();\n this.l = 0;\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be GZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gzip.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Gzip.prototype.p = function (c, f) {\n this.c.p(c);\n this.l += c.length;\n var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f);\n if (this.v)\n gzh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);\n this.ondata(raw, f);\n };\n return Gzip;\n}());\nexport { Gzip };\n/**\n * Asynchronous streaming GZIP compression\n */\nvar AsyncGzip = /*#__PURE__*/ (function () {\n function AsyncGzip(opts, cb) {\n astrmify([\n bDflt,\n gze,\n function () { return [astrm, Deflate, Gzip]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Gzip(ev.data);\n onmessage = astrm(strm);\n }, 8);\n }\n return AsyncGzip;\n}());\nexport { AsyncGzip };\nexport function gzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return cbify(data, opts, [\n bDflt,\n gze,\n function () { return [gzipSync]; }\n ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);\n}\n/**\n * Compresses data with GZIP\n * @param data The data to compress\n * @param opts The compression options\n * @returns The gzipped version of the data\n */\nexport function gzipSync(data, opts) {\n if (opts === void 0) { opts = {}; }\n var c = crc(), l = data.length;\n c.p(data);\n var d = dopt(data, opts, gzhl(opts), 8), s = d.length;\n return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;\n}\n/**\n * Streaming GZIP decompression\n */\nvar Gunzip = /*#__PURE__*/ (function () {\n /**\n * Creates a GUNZIP stream\n * @param cb The callback to call whenever data is inflated\n */\n function Gunzip(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be GUNZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gunzip.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n var s = gzs(this.p);\n if (s >= this.p.length && !final)\n return;\n this.p = this.p.subarray(s), this.v = 0;\n }\n if (final) {\n if (this.p.length < 8)\n throw 'invalid gzip stream';\n this.p = this.p.subarray(0, -8);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Gunzip;\n}());\nexport { Gunzip };\n/**\n * Asynchronous streaming GZIP decompression\n */\nvar AsyncGunzip = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous GUNZIP stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncGunzip(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n guze,\n function () { return [astrm, Inflate, Gunzip]; }\n ], this, 0, function () {\n var strm = new Gunzip();\n onmessage = astrm(strm);\n }, 9);\n }\n return AsyncGunzip;\n}());\nexport { AsyncGunzip };\nexport function gunzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return cbify(data, opts, [\n bInflt,\n guze,\n function () { return [gunzipSync]; }\n ], function (ev) { return pbf(gunzipSync(ev.data[0])); }, 3, cb);\n}\n/**\n * Expands GZIP data\n * @param data The data to decompress\n * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory.\n * @returns The decompressed version of the data\n */\nexport function gunzipSync(data, out) {\n return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data)));\n}\n/**\n * Streaming Zlib compression\n */\nvar Zlib = /*#__PURE__*/ (function () {\n function Zlib(opts, cb) {\n this.c = adler();\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be zlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Zlib.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Zlib.prototype.p = function (c, f) {\n this.c.p(c);\n var raw = dopt(c, this.o, this.v && 2, f && 4, !f);\n if (this.v)\n zlh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 4, this.c.d());\n this.ondata(raw, f);\n };\n return Zlib;\n}());\nexport { Zlib };\n/**\n * Asynchronous streaming Zlib compression\n */\nvar AsyncZlib = /*#__PURE__*/ (function () {\n function AsyncZlib(opts, cb) {\n astrmify([\n bDflt,\n zle,\n function () { return [astrm, Deflate, Zlib]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Zlib(ev.data);\n onmessage = astrm(strm);\n }, 10);\n }\n return AsyncZlib;\n}());\nexport { AsyncZlib };\nexport function zlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return cbify(data, opts, [\n bDflt,\n zle,\n function () { return [zlibSync]; }\n ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);\n}\n/**\n * Compress data with Zlib\n * @param data The data to compress\n * @param opts The compression options\n * @returns The zlib-compressed version of the data\n */\nexport function zlibSync(data, opts) {\n if (opts === void 0) { opts = {}; }\n var a = adler();\n a.p(data);\n var d = dopt(data, opts, 2, 4);\n return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;\n}\n/**\n * Streaming Zlib decompression\n */\nvar Unzlib = /*#__PURE__*/ (function () {\n /**\n * Creates a Zlib decompression stream\n * @param cb The callback to call whenever data is inflated\n */\n function Unzlib(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be unzlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzlib.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n if (this.p.length < 2 && !final)\n return;\n this.p = this.p.subarray(2), this.v = 0;\n }\n if (final) {\n if (this.p.length < 4)\n throw 'invalid zlib stream';\n this.p = this.p.subarray(0, -4);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Unzlib;\n}());\nexport { Unzlib };\n/**\n * Asynchronous streaming Zlib decompression\n */\nvar AsyncUnzlib = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous Zlib decompression stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncUnzlib(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n zule,\n function () { return [astrm, Inflate, Unzlib]; }\n ], this, 0, function () {\n var strm = new Unzlib();\n onmessage = astrm(strm);\n }, 11);\n }\n return AsyncUnzlib;\n}());\nexport { AsyncUnzlib };\nexport function unzlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return cbify(data, opts, [\n bInflt,\n zule,\n function () { return [unzlibSync]; }\n ], function (ev) { return pbf(unzlibSync(ev.data[0], gu8(ev.data[1]))); }, 5, cb);\n}\n/**\n * Expands Zlib data\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function unzlibSync(data, out) {\n return inflt((zlv(data), data.subarray(2, -4)), out);\n}\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzip as compress, AsyncGzip as AsyncCompress };\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzipSync as compressSync, Gzip as Compress };\n/**\n * Streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar Decompress = /*#__PURE__*/ (function () {\n /**\n * Creates a decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function Decompress(cb) {\n this.G = Gunzip;\n this.I = Inflate;\n this.Z = Unzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Decompress.prototype.push = function (chunk, final) {\n if (!this.ondata)\n throw 'no stream handler';\n if (!this.s) {\n if (this.p && this.p.length) {\n var n = new u8(this.p.length + chunk.length);\n n.set(this.p), n.set(chunk, this.p.length);\n }\n else\n this.p = chunk;\n if (this.p.length > 2) {\n var _this_1 = this;\n var cb = function () { _this_1.ondata.apply(_this_1, arguments); };\n this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)\n ? new this.G(cb)\n : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))\n ? new this.I(cb)\n : new this.Z(cb);\n this.s.push(this.p, final);\n this.p = null;\n }\n }\n else\n this.s.push(chunk, final);\n };\n return Decompress;\n}());\nexport { Decompress };\n/**\n * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar AsyncDecompress = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function AsyncDecompress(cb) {\n this.G = AsyncGunzip;\n this.I = AsyncInflate;\n this.Z = AsyncUnzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncDecompress.prototype.push = function (chunk, final) {\n Decompress.prototype.push.call(this, chunk, final);\n };\n return AsyncDecompress;\n}());\nexport { AsyncDecompress };\nexport function decompress(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzip(data, opts, cb)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflate(data, opts, cb)\n : unzlib(data, opts, cb);\n}\n/**\n * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function decompressSync(data, out) {\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzipSync(data, out)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflateSync(data, out)\n : unzlibSync(data, out);\n}\n// flatten a directory structure\nvar fltn = function (d, p, t, o) {\n for (var k in d) {\n var val = d[k], n = p + k;\n if (val instanceof u8)\n t[n] = [val, o];\n else if (Array.isArray(val))\n t[n] = [val[0], mrg(o, val[1])];\n else\n fltn(val, n + '/', t, o);\n }\n};\n/**\n * Converts a string into a Uint8Array for use with compression/decompression methods\n * @param str The string to encode\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless decoding a binary string.\n * @returns The string encoded in UTF-8/Latin-1 binary\n */\nexport function strToU8(str, latin1) {\n var l = str.length;\n if (!latin1 && typeof TextEncoder != 'undefined')\n return new TextEncoder().encode(str);\n var ar = new u8(str.length + (str.length >>> 1));\n var ai = 0;\n var w = function (v) { ar[ai++] = v; };\n for (var i = 0; i < l; ++i) {\n if (ai + 5 > ar.length) {\n var n = new u8(ai + 8 + ((l - i) << 1));\n n.set(ar);\n ar = n;\n }\n var c = str.charCodeAt(i);\n if (c < 128 || latin1)\n w(c);\n else if (c < 2048)\n w(192 | (c >>> 6)), w(128 | (c & 63));\n else if (c > 55295 && c < 57344)\n c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),\n w(240 | (c >>> 18)), w(128 | ((c >>> 12) & 63)), w(128 | ((c >>> 6) & 63)), w(128 | (c & 63));\n else\n w(224 | (c >>> 12)), w(128 | ((c >>> 6) & 63)), w(128 | (c & 63));\n }\n return slc(ar, 0, ai);\n}\n/**\n * Converts a Uint8Array to a string\n * @param dat The data to decode to string\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless encoding to binary string.\n * @returns The original UTF-8/Latin-1 string\n */\nexport function strFromU8(dat, latin1) {\n var r = '';\n if (!latin1 && typeof TextDecoder != 'undefined')\n return new TextDecoder().decode(dat);\n for (var i = 0; i < dat.length;) {\n var c = dat[i++];\n if (c < 128 || latin1)\n r += String.fromCharCode(c);\n else if (c < 224)\n r += String.fromCharCode((c & 31) << 6 | (dat[i++] & 63));\n else if (c < 240)\n r += String.fromCharCode((c & 15) << 12 | (dat[i++] & 63) << 6 | (dat[i++] & 63));\n else\n c = ((c & 15) << 18 | (dat[i++] & 63) << 12 | (dat[i++] & 63) << 6 | (dat[i++] & 63)) - 65536,\n r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));\n }\n return r;\n}\n;\n// skip local zip header\nvar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };\n// read zip header\nvar zh = function (d, b, z) {\n var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl;\n var _a = z ? z64e(d, es) : [b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];\n return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];\n};\n// read zip64 extra field\nvar z64e = function (d, b) {\n for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))\n ;\n return [b4(d, b + 12), b4(d, b + 4), b4(d, b + 20)];\n};\n// write zip header\nvar wzh = function (d, b, c, cmp, su, fn, u, o, ce, t) {\n var fl = fn.length, l = cmp.length;\n wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;\n if (ce != null)\n d[b] = 20, b += 2;\n d[b] = 20, b += 2; // spec compliance? what's that?\n d[b++] = (t == 8 && (o.level == 1 ? 6 : o.level < 6 ? 4 : o.level == 9 ? 2 : 0)), d[b++] = u && 8;\n d[b] = t, b += 2;\n var dt = new Date(o.mtime || Date.now()), y = dt.getFullYear() - 1980;\n if (y < 0 || y > 119)\n throw 'date not in range 1980-2099';\n wbytes(d, b, ((y << 24) * 2) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1));\n b += 4;\n wbytes(d, b, c);\n wbytes(d, b + 4, l);\n wbytes(d, b + 8, su);\n wbytes(d, b + 12, fl), b += 16; // skip extra field, comment\n if (ce != null)\n wbytes(d, b += 10, ce), b += 4;\n d.set(fn, b);\n b += fl;\n if (ce == null)\n d.set(cmp, b);\n};\n// write zip footer (end of central directory)\nvar wzf = function (o, b, c, d, e) {\n wbytes(o, b, 0x6054B50); // skip disk\n wbytes(o, b + 8, c);\n wbytes(o, b + 10, c);\n wbytes(o, b + 12, d);\n wbytes(o, b + 16, e);\n};\nexport function zip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n var r = {};\n fltn(data, '', r, opts);\n var k = Object.keys(r);\n var lft = k.length, o = 0, tot = 0;\n var slft = lft, files = new Array(lft);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var cbf = function () {\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n tot = 0;\n for (var i = 0; i < slft; ++i) {\n var f = files[i];\n try {\n wzh(out, tot, f.c, f.d, f.m, f.n, f.u, f.p, null, f.t);\n wzh(out, o, f.c, f.d, f.m, f.n, f.u, f.p, tot, f.t), o += 46 + f.n.length, tot += 30 + f.n.length + f.d.length;\n }\n catch (e) {\n return cb(e, null);\n }\n }\n wzf(out, o, files.length, cdl, oe);\n cb(null, out);\n };\n if (!lft)\n cbf();\n var _loop_1 = function (i) {\n var fn = k[i];\n var _a = r[fn], file = _a[0], p = _a[1];\n var c = crc(), m = file.length;\n c.p(file);\n var n = strToU8(fn), s = n.length;\n var t = p.level == 0 ? 0 : 8;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cb(e, null);\n }\n else {\n var l = d.length;\n files[i] = {\n t: t,\n d: d,\n m: m,\n c: c.d(),\n u: fn.length != l,\n n: n,\n p: p\n };\n o += 30 + s + l;\n tot += 76 + 2 * s + l;\n if (!--lft)\n cbf();\n }\n };\n if (n.length > 65535)\n cbl('filename too long', null);\n if (!t)\n cbl(null, file);\n else if (m < 160000) {\n try {\n cbl(null, deflateSync(file, p));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(deflate(file, p, cbl));\n };\n // Cannot use lft because it can decrease\n for (var i = 0; i < slft; ++i) {\n _loop_1(i);\n }\n return tAll;\n}\n/**\n * Synchronously creates a ZIP file. Prefer using `zip` for better performance\n * with more than one file.\n * @param data The directory structure for the ZIP archive\n * @param opts The main options, merged with per-file options\n * @returns The generated ZIP archive\n */\nexport function zipSync(data, opts) {\n if (opts === void 0) { opts = {}; }\n var r = {};\n var files = [];\n fltn(data, '', r, opts);\n var o = 0;\n var tot = 0;\n for (var fn in r) {\n var _a = r[fn], file = _a[0], p = _a[1];\n var t = p.level == 0 ? 0 : 8;\n var n = strToU8(fn), s = n.length;\n if (n.length > 65535)\n throw 'filename too long';\n var d = t ? deflateSync(file, p) : file, l = d.length;\n var c = crc();\n c.p(file);\n files.push({\n t: t,\n d: d,\n m: file.length,\n c: c.d(),\n u: fn.length != s,\n n: n,\n o: o,\n p: p\n });\n o += 30 + s + l;\n tot += 76 + 2 * s + l;\n }\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n for (var i = 0; i < files.length; ++i) {\n var f = files[i];\n wzh(out, f.o, f.c, f.d, f.m, f.n, f.u, f.p, null, f.t);\n wzh(out, o, f.c, f.d, f.m, f.n, f.u, f.p, f.o, f.t), o += 46 + f.n.length;\n }\n wzf(out, o, files.length, cdl, oe);\n return out;\n}\n/**\n * Asynchronously decompresses a ZIP archive\n * @param data The raw compressed ZIP file\n * @param cb The callback to call with the decompressed files\n * @returns A function that can be used to immediately terminate the unzipping\n */\nexport function unzip(data, cb) {\n if (typeof cb != 'function')\n throw 'no callback';\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var files = {};\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558) {\n cb('invalid zip file', null);\n return;\n }\n }\n ;\n var lft = b2(data, e + 8);\n if (!lft)\n cb(null, {});\n var c = lft;\n var o = b4(data, e + 16);\n var z = o == 4294967295;\n if (z) {\n e = b4(data, e - 12);\n if (b4(data, e) != 0x6064B50)\n throw 'invalid zip file';\n c = lft = b4(data, e + 32);\n o = b4(data, e + 48);\n }\n var _loop_2 = function (i) {\n var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cb(e, null);\n }\n else {\n files[fn] = d;\n if (!--lft)\n cb(null, files);\n }\n };\n if (!c_1)\n cbl(null, slc(data, b, b + sc));\n else if (c_1 == 8) {\n var infl = data.subarray(b, b + sc);\n if (sc < 320000) {\n try {\n cbl(null, inflateSync(infl, new u8(su)));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(inflate(infl, { size: su }, cbl));\n }\n else\n cbl('unknown compression type ' + c_1, null);\n };\n for (var i = 0; i < c; ++i) {\n _loop_2(i);\n }\n return tAll;\n}\n/**\n * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better\n * performance with more than one file.\n * @param data The raw compressed ZIP file\n * @returns The decompressed files\n */\nexport function unzipSync(data) {\n var files = {};\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558)\n throw 'invalid zip file';\n }\n ;\n var c = b2(data, e + 8);\n if (!c)\n return {};\n var o = b4(data, e + 16);\n var z = o == 4294967295;\n if (z) {\n e = b4(data, e - 12);\n if (b4(data, e) != 0x6064B50)\n throw 'invalid zip file';\n c = b4(data, e + 32);\n o = b4(data, e + 48);\n }\n for (var i = 0; i < c; ++i) {\n var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n if (!c_2)\n files[fn] = slc(data, b, b + sc);\n else if (c_2 == 8)\n files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su));\n else\n throw 'unknown compression type ' + c_2;\n }\n return files;\n}\n", "import { each, find } from './utils'\nimport Config from './config'\nimport { Compression, RequestWithOptions, RequestResponse } from './types'\nimport { formDataToQuery } from './utils/request-utils'\n\nimport { logger } from './utils/logger'\nimport { AbortController, CompressionStream, fetch, navigator, XMLHttpRequest } from './utils/globals'\nimport { gzipSync, strToU8 } from 'fflate'\n\nimport { _base64Encode } from './utils/encode-utils'\nimport { gzipCompress, isNativeAsyncGzipReadError } from '@posthog/core'\n\ninterface RequestWithEncodedBody extends RequestWithOptions {\n _encodedBody?: EncodedBody\n}\n\n// eslint-disable-next-line compat/compat\nexport const SUPPORTS_REQUEST = !!XMLHttpRequest || !!fetch\n\nconst CONTENT_TYPE_PLAIN = 'text/plain'\nconst CONTENT_TYPE_JSON = 'application/json'\nconst CONTENT_TYPE_FORM = 'application/x-www-form-urlencoded'\nconst SIXTY_FOUR_KILOBYTES = 64 * 1024\n/*\n fetch will fail if we request keepalive with a body greater than 64kb\n sets the threshold lower than that so that\n any overhead doesn't push over the threshold after checking here\n*/\nconst KEEP_ALIVE_THRESHOLD = SIXTY_FOUR_KILOBYTES * 0.8\nlet nativeAsyncGzipDisabled = false\n\ntype EncodedBody = {\n contentType: string\n body: string | BlobPart | ArrayBuffer\n estimatedSize: number\n}\n\n/**\n * Extends a URL with additional query parameters\n * @param url - The URL to extend\n * @param params - The parameters to add\n * @param replace - When true (default), new params overwrite existing ones with same key. When false, existing params are preserved.\n * @returns The URL with extended parameters\n */\nexport const extendURLParams = (url: string, params: Record, replace: boolean = true): string => {\n const [baseUrl, search] = url.split('?')\n const newParams = { ...params }\n\n const updatedSearch =\n search?.split('&').map((pair) => {\n const [key, origValue] = pair.split('=')\n const value = replace ? (newParams[key] ?? origValue) : origValue\n delete newParams[key]\n return `${key}=${value}`\n }) ?? []\n\n const remaining = formDataToQuery(newParams)\n if (remaining) {\n updatedSearch.push(remaining)\n }\n\n return `${baseUrl}?${updatedSearch.join('&')}`\n}\n\nexport const jsonStringify = (data: any, space?: string | number): string => {\n // With plain JSON.stringify, we get an exception when a property is a BigInt. This has caused problems for some users,\n // see https://github.com/PostHog/posthog-js/issues/1440\n // To work around this, we convert BigInts to strings before stringifying the data. This is not ideal, as we lose\n // information that this was originally a number, but given ClickHouse doesn't support BigInts, the customer\n // would not be able to operate on these numerically anyway.\n return JSON.stringify(data, (_, value) => (typeof value === 'bigint' ? value.toString() : value), space)\n}\n\nconst encodeToDataString = (data: string | Record): string => {\n return 'data=' + encodeURIComponent(typeof data === 'string' ? data : jsonStringify(data))\n}\n\nconst encodePostData = (options: RequestWithEncodedBody): EncodedBody | undefined => {\n // Use pre-encoded body if available (set by async compression in the request entrypoint)\n if (options._encodedBody) {\n return options._encodedBody\n }\n\n const { data, compression } = options\n if (!data) {\n return\n }\n\n if (compression === Compression.GZipJS) {\n const gzipData = gzipSync(strToU8(jsonStringify(data)), { mtime: 0 })\n return {\n contentType: CONTENT_TYPE_PLAIN,\n body: gzipData.buffer.slice(gzipData.byteOffset, gzipData.byteOffset + gzipData.byteLength) as ArrayBuffer,\n estimatedSize: gzipData.byteLength,\n }\n }\n\n if (compression === Compression.Base64) {\n const b64data = _base64Encode(jsonStringify(data))\n const encodedBody = encodeToDataString(b64data)\n\n return {\n contentType: CONTENT_TYPE_FORM,\n body: encodedBody,\n estimatedSize: new Blob([encodedBody]).size,\n }\n }\n\n const jsonBody = jsonStringify(data)\n return {\n contentType: CONTENT_TYPE_JSON,\n body: jsonBody,\n estimatedSize: new Blob([jsonBody]).size,\n }\n}\n\n/**\n * Pre-encode the request body using async native CompressionStream.\n * This avoids blocking the main thread with fflate's synchronous gzip,\n * which can take 300ms+ on constrained devices.\n *\n * Callers must check preconditions (data exists, gzip compression, CompressionStream available)\n * before calling this function.\n */\nconst preEncodeAsync = async (options: RequestWithEncodedBody): Promise => {\n const jsonData = jsonStringify(options.data)\n const compressed = await gzipCompress(jsonData, Config.DEBUG, { rethrow: true })\n if (!compressed) {\n return options\n }\n const body = await compressed.arrayBuffer()\n\n return {\n ...options,\n _encodedBody: {\n contentType: CONTENT_TYPE_PLAIN,\n body,\n estimatedSize: body.byteLength,\n },\n }\n}\n\nconst xhr = (options: RequestWithOptions) => {\n const req = new XMLHttpRequest!()\n req.open(options.method || 'GET', options.url, true)\n const { contentType, body } = encodePostData(options) ?? {}\n\n each(options.headers, function (headerValue, headerName) {\n req.setRequestHeader(headerName, headerValue)\n })\n\n if (contentType) {\n req.setRequestHeader('Content-Type', contentType)\n }\n\n if (options.timeout) {\n req.timeout = options.timeout\n }\n if (!options.disableXHRCredentials) {\n // send the ph_optout cookie\n // withCredentials cannot be modified until after calling .open on Android and Mobile Safari\n req.withCredentials = true\n }\n req.onreadystatechange = () => {\n // XMLHttpRequest.DONE == 4, except in safari 4\n if (req.readyState === 4) {\n const response: RequestResponse = {\n statusCode: req.status,\n text: req.responseText,\n }\n if (req.status === 200) {\n try {\n response.json = JSON.parse(req.responseText)\n } catch {\n // logger.error(e)\n }\n }\n\n options.callback?.(response)\n }\n }\n req.send(body)\n}\n\nconst _fetch = (options: RequestWithOptions) => {\n const { contentType, body, estimatedSize } = encodePostData(options) ?? {}\n\n // eslint-disable-next-line compat/compat\n const headers = new Headers()\n each(options.headers, function (headerValue, headerName) {\n headers.append(headerName, headerValue)\n })\n\n if (contentType) {\n headers.append('Content-Type', contentType)\n }\n\n const url = options.url\n let aborter: { signal: any; timeout: ReturnType } | null = null\n\n if (AbortController) {\n const controller = new AbortController()\n aborter = {\n signal: controller.signal,\n timeout: setTimeout(() => controller.abort(), options.timeout),\n }\n }\n\n fetch!(url, {\n method: options?.method || 'GET',\n headers,\n // if body is greater than 64kb, then fetch with keepalive will error\n // see 8:10:5 at https://fetch.spec.whatwg.org/#http-network-or-cache-fetch,\n // but we do want to set keepalive sometimes as it can help with success\n // when e.g. a page is being closed\n // so let's get the best of both worlds and only set keepalive for POST requests\n // where the body is less than 64kb\n // NB this is fetch keepalive and not http keepalive\n keepalive: options.method === 'POST' && (estimatedSize || 0) < KEEP_ALIVE_THRESHOLD,\n body,\n signal: aborter?.signal,\n ...options.fetchOptions,\n })\n .then((response) => {\n return response.text().then((responseText) => {\n const res: RequestResponse = {\n statusCode: response.status,\n text: responseText,\n }\n\n if (response.status === 200) {\n try {\n res.json = JSON.parse(responseText)\n } catch (e) {\n logger.error(e)\n }\n }\n\n options.callback?.(res)\n })\n })\n .catch((error) => {\n logger.error(error)\n options.callback?.({ statusCode: 0, error })\n })\n .finally(() => (aborter ? clearTimeout(aborter.timeout) : null))\n\n return\n}\n\nconst _sendBeacon = (options: RequestWithOptions) => {\n // beacon documentation https://w3c.github.io/beacon/\n // beacons format the message and use the type property\n\n const url = extendURLParams(options.url, {\n beacon: '1',\n })\n\n try {\n const { contentType, body } = encodePostData(options) ?? {}\n if (!body) {\n return\n }\n // sendBeacon requires a Blob to set the Content-Type header correctly.\n // Without wrapping, ArrayBuffer bodies are sent with no Content-Type,\n // which can cause issues with proxies/WAFs that require it.\n const sendBeaconBody = body instanceof Blob ? body : new Blob([body], { type: contentType })\n navigator!.sendBeacon!(url, sendBeaconBody)\n } catch {\n // send beacon is a best-effort, fire-and-forget mechanism on page unload,\n // we don't want to throw errors here\n }\n}\n\nconst buildRequestURL = (url: string, compression?: RequestWithOptions['compression']): string => {\n return extendURLParams(url, {\n _: new Date().getTime().toString(),\n ver: Config.JS_SDK_VERSION,\n compression,\n })\n}\n\nconst AVAILABLE_TRANSPORTS: {\n transport: RequestWithOptions['transport']\n method: (options: RequestWithOptions) => void\n}[] = []\n\n// We add the transports in order of preference\nif (fetch) {\n AVAILABLE_TRANSPORTS.push({\n transport: 'fetch',\n method: _fetch,\n })\n}\n\nif (XMLHttpRequest) {\n AVAILABLE_TRANSPORTS.push({\n transport: 'XHR',\n method: xhr,\n })\n}\n\nif (navigator?.sendBeacon) {\n AVAILABLE_TRANSPORTS.push({\n transport: 'sendBeacon',\n method: _sendBeacon,\n })\n}\n\n// This is the entrypoint. It takes care of sanitizing the options and then calls the appropriate request method.\nexport const request = (_options: RequestWithOptions) => {\n // Clone the options so we don't modify the original object\n const options: RequestWithEncodedBody = { ..._options }\n options.timeout = options.timeout || 60000\n\n options.url = buildRequestURL(options.url, options.compression)\n\n const transport = options.transport ?? 'fetch'\n\n const availableTransports = AVAILABLE_TRANSPORTS.filter(\n (t) => !options.disableTransport || !t.transport || !options.disableTransport.includes(t.transport)\n )\n\n const transportMethod =\n find(availableTransports, (t) => t.transport === transport)?.method ?? availableTransports[0].method\n\n if (!transportMethod) {\n throw new Error('No available transport method')\n }\n\n // For non-sendBeacon transports, use async native CompressionStream when available\n // to avoid blocking the main thread with fflate's synchronous gzip (which can take 300ms+).\n // sendBeacon must remain synchronous as it's used during page unload.\n if (\n transport !== 'sendBeacon' &&\n options.data &&\n options.compression === Compression.GZipJS &&\n !!CompressionStream &&\n !nativeAsyncGzipDisabled\n ) {\n preEncodeAsync(options)\n .then((encodedOptions) => {\n transportMethod(encodedOptions)\n })\n .catch((error) => {\n if (isNativeAsyncGzipReadError(error)) {\n nativeAsyncGzipDisabled = true\n transportMethod({\n ...options,\n compression: undefined,\n url: buildRequestURL(_options.url, undefined),\n })\n return\n }\n\n // If async compression fails for another reason, fall back to the synchronous fflate path\n transportMethod(options)\n })\n } else {\n transportMethod(options)\n }\n}\n", "/**\n * UTF-8 safe base64 encoding.\n * Uses encodeURIComponent to handle Unicode, then converts percent-encoded bytes\n * back to characters that btoa can handle.\n */\nexport function _base64Encode(data: null): null\nexport function _base64Encode(data: undefined): undefined\nexport function _base64Encode(data: string): string\nexport function _base64Encode(data: string | null | undefined): string | null | undefined {\n if (!data) {\n return data\n }\n return btoa(encodeURIComponent(data).replace(/%([0-9A-F]{2})/g, (_, p1) => String.fromCharCode(parseInt(p1, 16))))\n}\n", "import { QueuedRequestWithOptions, RequestQueueConfig } from './types'\nimport { each } from './utils'\n\nimport { isArray, isUndefined, clampToRange } from '@posthog/core'\nimport { logger } from './utils/logger'\n\nexport const DEFAULT_FLUSH_INTERVAL_MS = 3000\n\nexport class RequestQueue {\n // We start in a paused state and only start flushing when enabled by the parent\n private _isPaused: boolean = true\n private _queue: QueuedRequestWithOptions[] = []\n private _flushTimeout?: ReturnType\n private _flushTimeoutMs: number\n private _sendRequest: (req: QueuedRequestWithOptions) => void\n\n constructor(sendRequest: (req: QueuedRequestWithOptions) => void, config?: RequestQueueConfig) {\n this._flushTimeoutMs = clampToRange(\n config?.flush_interval_ms || DEFAULT_FLUSH_INTERVAL_MS,\n 250,\n 5000,\n logger.createLogger('flush interval'),\n DEFAULT_FLUSH_INTERVAL_MS\n )\n this._sendRequest = sendRequest\n }\n\n enqueue(req: QueuedRequestWithOptions): void {\n this._queue.push(req)\n\n if (!this._flushTimeout) {\n this._setFlushTimeout()\n }\n }\n\n unload(): void {\n this._clearFlushTimeout()\n const requests = this._queue.length > 0 ? this._formatQueue() : {}\n const requestValues = Object.values(requests)\n\n // Always force events to be sent before recordings, as events are more important, and recordings are bigger and thus less likely to arrive\n const sortedRequests = [\n ...requestValues.filter((r) => r.url.indexOf('/e') === 0),\n ...requestValues.filter((r) => r.url.indexOf('/e') !== 0),\n ]\n sortedRequests.map((req) => {\n this._sendRequest({ ...req, transport: 'sendBeacon' })\n })\n }\n\n enable(): void {\n this._isPaused = false\n this._setFlushTimeout()\n }\n\n private _setFlushTimeout(): void {\n if (this._isPaused) {\n return\n }\n this._flushTimeout = setTimeout(() => {\n this._clearFlushTimeout()\n if (this._queue.length > 0) {\n const requests = this._formatQueue()\n for (const key in requests) {\n const req = requests[key]\n const now = new Date().getTime()\n\n if (req.data && isArray(req.data)) {\n each(req.data, (data) => {\n data['offset'] = Math.abs(data['timestamp'] - now)\n delete data['timestamp']\n })\n }\n this._sendRequest(req)\n }\n }\n }, this._flushTimeoutMs)\n }\n\n private _clearFlushTimeout(): void {\n clearTimeout(this._flushTimeout)\n this._flushTimeout = undefined\n }\n\n private _formatQueue(): Record {\n const requests: Record = {}\n each(this._queue, (request: QueuedRequestWithOptions) => {\n const req = request\n const key = (req ? req.batchKey : null) || req.url\n if (isUndefined(requests[key])) {\n // TODO: What about this -it seems to batch data into an array - do we always want that?\n requests[key] = { ...req, data: [] }\n }\n\n requests[key].data?.push(req.data)\n })\n\n this._queue = []\n return requests\n }\n}\n", "import { RetriableRequestWithOptions } from './types'\n\nimport { isPositiveNumber, isUndefined } from '@posthog/core'\nimport { logger } from './utils/logger'\nimport { window } from './utils/globals'\nimport { PostHog } from './posthog-core'\nimport { extendURLParams } from './request'\nimport { addEventListener } from './utils'\n\nconst thirtyMinutes = 30 * 60 * 1000\n\n/**\n * Generates a jitter-ed exponential backoff delay in milliseconds\n *\n * The base value is 6 seconds, which is doubled with each retry\n * up to the maximum of 30 minutes\n *\n * Each value then has +/- 50% jitter\n *\n * Giving a range of 6 seconds up to 45 minutes\n */\nexport function pickNextRetryDelay(retriesPerformedSoFar: number): number {\n const rawBackoffTime = 3000 * 2 ** retriesPerformedSoFar\n const minBackoff = rawBackoffTime / 2\n const cappedBackoffTime = Math.min(thirtyMinutes, rawBackoffTime)\n const jitterFraction = Math.random() - 0.5 // A random number between -0.5 and 0.5\n const jitter = jitterFraction * (cappedBackoffTime - minBackoff)\n return Math.ceil(cappedBackoffTime + jitter)\n}\n\ninterface RetryQueueElement {\n retryAt: number\n requestOptions: RetriableRequestWithOptions\n}\n\nexport class RetryQueue {\n private _isPolling: boolean = false\n private _poller: number | undefined\n private _pollIntervalMs: number = 3000\n private _queue: RetryQueueElement[] = []\n private _areWeOnline: boolean\n private _onlineListener: (() => void) | undefined\n private _offlineListener: (() => void) | undefined\n\n constructor(private _instance: PostHog) {\n this._queue = []\n this._areWeOnline = true\n\n if (!isUndefined(window) && 'onLine' in window.navigator) {\n this._areWeOnline = window.navigator.onLine\n\n this._onlineListener = () => {\n this._areWeOnline = true\n this._flush()\n }\n\n this._offlineListener = () => {\n this._areWeOnline = false\n }\n\n addEventListener(window, 'online', this._onlineListener)\n addEventListener(window, 'offline', this._offlineListener)\n }\n }\n\n get length() {\n return this._queue.length\n }\n\n retriableRequest({ retriesPerformedSoFar, ...options }: RetriableRequestWithOptions): void {\n if (isPositiveNumber(retriesPerformedSoFar)) {\n options.url = extendURLParams(options.url, { retry_count: retriesPerformedSoFar })\n }\n\n this._instance._send_request({\n ...options,\n callback: (response) => {\n if (response.statusCode !== 200 && (response.statusCode < 400 || response.statusCode >= 500)) {\n if ((retriesPerformedSoFar ?? 0) < 10) {\n this._enqueue({\n retriesPerformedSoFar,\n ...options,\n })\n return\n }\n }\n\n options.callback?.(response)\n },\n })\n }\n\n private _enqueue(requestOptions: RetriableRequestWithOptions): void {\n const retriesPerformedSoFar = requestOptions.retriesPerformedSoFar || 0\n requestOptions.retriesPerformedSoFar = retriesPerformedSoFar + 1\n\n const msToNextRetry = pickNextRetryDelay(retriesPerformedSoFar)\n const retryAt = Date.now() + msToNextRetry\n\n this._queue.push({ retryAt, requestOptions })\n\n let logMessage = `Enqueued failed request for retry in ${msToNextRetry}`\n if (!navigator.onLine) {\n logMessage += ' (Browser is offline)'\n }\n logger.warn(logMessage)\n\n if (!this._isPolling) {\n this._isPolling = true\n this._poll()\n }\n }\n\n private _poll(): void {\n this._poller && clearTimeout(this._poller)\n\n if (this._queue.length === 0) {\n this._isPolling = false\n this._poller = undefined\n return\n }\n\n this._poller = setTimeout(() => {\n if (this._areWeOnline && this._queue.length > 0) {\n this._flush()\n }\n this._poll()\n }, this._pollIntervalMs) as any as number\n }\n\n private _flush(): void {\n const now = Date.now()\n const notToFlush: RetryQueueElement[] = []\n const toFlush = this._queue.filter((item) => {\n if (item.retryAt < now) {\n return true\n }\n notToFlush.push(item)\n return false\n })\n\n this._queue = notToFlush\n\n if (toFlush.length > 0) {\n for (const { requestOptions } of toFlush) {\n this.retriableRequest(requestOptions)\n }\n }\n }\n\n unload(): void {\n if (this._poller) {\n clearTimeout(this._poller)\n this._poller = undefined\n }\n\n this._isPolling = false\n\n if (!isUndefined(window)) {\n if (this._onlineListener) {\n window.removeEventListener('online', this._onlineListener)\n this._onlineListener = undefined\n }\n if (this._offlineListener) {\n window.removeEventListener('offline', this._offlineListener)\n this._offlineListener = undefined\n }\n }\n\n for (const { requestOptions } of this._queue) {\n try {\n // we've had send beacon in place for at least 2 years\n // eslint-disable-next-line compat/compat\n this._instance._send_request({\n ...requestOptions,\n transport: 'sendBeacon',\n })\n } catch (e) {\n // Note sendBeacon automatically retries, and after the first retry it will lose reference to contextual `this`.\n // This means in some cases `this.getConfig` will be undefined.\n logger.error(e)\n }\n }\n this._queue = []\n }\n}\n", "import { window } from './utils/globals'\nimport { PostHog } from './posthog-core'\nimport { addEventListener } from './utils'\nimport { isArray } from '@posthog/core'\n\nexport interface ScrollContext {\n // scroll is how far down the page the user has scrolled,\n // content is how far down the page the user can view content\n // (e.g. if the page is 1000 tall, but the user's screen is only 500 tall,\n // and they don't scroll at all, then scroll is 0 and content is 500)\n maxScrollHeight?: number\n maxScrollY?: number\n lastScrollY?: number\n maxContentHeight?: number\n maxContentY?: number\n lastContentY?: number\n}\n\n// This class is responsible for tracking scroll events and maintaining the scroll context\nexport class ScrollManager {\n private _context: ScrollContext | undefined\n\n constructor(private _instance: PostHog) {}\n\n private get _scrollRoot() {\n return this._instance.config.scroll_root_selector\n }\n\n getContext(): ScrollContext | undefined {\n return this._context\n }\n\n resetContext(): ScrollContext | undefined {\n const ctx = this._context\n\n // update the scroll properties for the new page, but wait until the next tick\n // of the event loop\n setTimeout(this._updateScrollData, 0)\n\n return ctx\n }\n\n private _updateScrollData = () => {\n if (!this._context) {\n this._context = {}\n }\n\n const el = this.scrollElement()\n\n const scrollY = this.scrollY()\n const scrollHeight = el ? Math.max(0, el.scrollHeight - el.clientHeight) : 0\n const contentY = scrollY + (el?.clientHeight || 0)\n const contentHeight = el?.scrollHeight || 0\n\n this._context.lastScrollY = Math.ceil(scrollY)\n this._context.maxScrollY = Math.max(scrollY, this._context.maxScrollY ?? 0)\n this._context.maxScrollHeight = Math.max(scrollHeight, this._context.maxScrollHeight ?? 0)\n\n this._context.lastContentY = contentY\n this._context.maxContentY = Math.max(contentY, this._context.maxContentY ?? 0)\n this._context.maxContentHeight = Math.max(contentHeight, this._context.maxContentHeight ?? 0)\n }\n\n // `capture: true` is required to get scroll events for other scrollable elements\n // on the page, not just the window\n // see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#usecapture\n startMeasuringScrollPosition() {\n addEventListener(window, 'scroll', this._updateScrollData, { capture: true })\n addEventListener(window, 'scrollend', this._updateScrollData, { capture: true })\n addEventListener(window, 'resize', this._updateScrollData)\n }\n\n public scrollElement(): Element | undefined {\n if (this._scrollRoot) {\n const selectors = isArray(this._scrollRoot) ? this._scrollRoot : [this._scrollRoot]\n for (const selector of selectors) {\n const element = window?.document.querySelector(selector)\n if (element) {\n return element\n }\n }\n return undefined\n } else {\n return window?.document.documentElement\n }\n }\n\n public scrollY(): number {\n if (this._scrollRoot) {\n const element = this.scrollElement()\n return (element && element.scrollTop) || 0\n } else {\n return window ? window.scrollY || window.pageYOffset || window.document.documentElement.scrollTop || 0 : 0\n }\n }\n\n public scrollX(): number {\n if (this._scrollRoot) {\n const element = this.scrollElement()\n return (element && element.scrollLeft) || 0\n } else {\n return window ? window.scrollX || window.pageXOffset || window.document.documentElement.scrollLeft || 0 : 0\n }\n }\n}\n", "/* Store some session-level attribution-related properties in the persistence layer\n *\n * These have the same lifespan as a session_id, meaning that if the session_id changes, these properties will be reset.\n *\n * We only store the entry URL and referrer, and derive many props (such as utm tags) from those.\n *\n * Given that the cookie is limited to 4K bytes, we don't want to store too much data, so we chose not to store device\n * properties (such as browser, OS, etc) here, as usually getting the current value of those from event properties is\n * sufficient.\n */\nimport { getPersonInfo, getPersonPropsFromInfo } from './utils/event-utils'\nimport type { SessionIdManager } from './sessionid'\nimport type { PostHogPersistence } from './posthog-persistence'\nimport { CLIENT_SESSION_PROPS } from './constants'\nimport type { PostHog } from './posthog-core'\nimport { each, stripEmptyProperties } from './utils'\nimport { stripLeadingDollar } from '@posthog/core'\n\ninterface LegacySessionSourceProps {\n initialPathName: string\n referringDomain: string // Is actually referring host, but named referring domain for internal consistency. Should contain a port if there is one.\n utm_medium?: string\n utm_source?: string\n utm_campaign?: string\n utm_content?: string\n utm_term?: string\n}\n\ninterface CurrentSessionSourceProps {\n r: string // Referring host\n u: string | undefined // full URL\n}\n\ninterface StoredSessionSourceProps {\n sessionId: string\n props: LegacySessionSourceProps | CurrentSessionSourceProps\n}\n\nconst generateSessionSourceParams = (posthog?: PostHog): LegacySessionSourceProps | CurrentSessionSourceProps => {\n return getPersonInfo(posthog?.config.mask_personal_data_properties, posthog?.config.custom_personal_data_properties)\n}\n\nexport class SessionPropsManager {\n private readonly _instance: PostHog\n private readonly _sessionIdManager: SessionIdManager\n private readonly _persistence: PostHogPersistence\n private readonly _sessionSourceParamGenerator: (\n instance?: PostHog\n ) => LegacySessionSourceProps | CurrentSessionSourceProps\n\n constructor(\n instance: PostHog,\n sessionIdManager: SessionIdManager,\n persistence: PostHogPersistence,\n sessionSourceParamGenerator?: (instance?: PostHog) => LegacySessionSourceProps | CurrentSessionSourceProps\n ) {\n this._instance = instance\n this._sessionIdManager = sessionIdManager\n this._persistence = persistence\n this._sessionSourceParamGenerator = sessionSourceParamGenerator || generateSessionSourceParams\n\n this._sessionIdManager.onSessionId(this._onSessionIdCallback)\n }\n\n _getStored(): StoredSessionSourceProps | undefined {\n return this._persistence.props[CLIENT_SESSION_PROPS]\n }\n\n _onSessionIdCallback = (sessionId: string) => {\n const stored = this._getStored()\n if (stored && stored.sessionId === sessionId) {\n return\n }\n\n const newProps: StoredSessionSourceProps = {\n sessionId,\n props: this._sessionSourceParamGenerator(this._instance),\n }\n this._persistence.register({ [CLIENT_SESSION_PROPS]: newProps })\n }\n\n getSetOnceProps() {\n const p = this._getStored()?.props\n if (!p) {\n return {}\n }\n if ('r' in p) {\n return getPersonPropsFromInfo(p)\n } else {\n return {\n $referring_domain: p.referringDomain,\n $pathname: p.initialPathName,\n utm_source: p.utm_source,\n utm_campaign: p.utm_campaign,\n utm_medium: p.utm_medium,\n utm_content: p.utm_content,\n utm_term: p.utm_term,\n }\n }\n }\n\n getSessionProps() {\n // it's the same props, but don't include null for unset properties, and add a prefix\n const p: Record = {}\n each(stripEmptyProperties(this.getSetOnceProps()), (v, k) => {\n if (k === '$current_url') {\n // $session_entry_current_url would be a weird name, call it $session_entry_url instead\n k = 'url'\n }\n p[`$session_entry_${stripLeadingDollar(k)}`] = v\n })\n return p\n }\n}\n", "export class SimpleEventEmitter {\n private _events: { [key: string]: ((...args: any[]) => void)[] } = {}\n\n on(event: string, listener: (...args: any[]) => void): () => void {\n if (!this._events[event]) {\n this._events[event] = []\n }\n this._events[event].push(listener)\n\n return () => {\n this._events[event] = this._events[event].filter((x) => x !== listener)\n }\n }\n\n emit(event: string, payload: any): void {\n for (const listener of this._events[event] || []) {\n listener(payload)\n }\n for (const listener of this._events['*'] || []) {\n listener(event, payload)\n }\n }\n}\n", "import { PostHogPersistence } from './posthog-persistence'\nimport { COOKIELESS_ALWAYS, DOM_EVENT_BEFOREUNLOAD, SESSION_ID } from './constants'\nimport { sessionStore } from './storage'\nimport { PostHogConfig, SessionIdChangedCallback } from './types'\nimport { uuid7ToTimestampMs, uuidv7 } from './uuidv7'\nimport { window } from './utils/globals'\n\nimport { createLogger } from './utils/logger'\n\nimport { isArray, isUndefined, clampToRange, isPositiveNumber } from '@posthog/core'\nimport { PostHog } from './posthog-core'\nimport { addEventListener } from './utils'\nimport { SimpleEventEmitter } from './utils/simple-event-emitter'\n\nconst logger = createLogger('[SessionId]')\n\nexport const DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS = 30 * 60 // 30 minutes\nexport const MAX_SESSION_IDLE_TIMEOUT_SECONDS = 10 * 60 * 60 // 10 hours\nconst MIN_SESSION_IDLE_TIMEOUT_SECONDS = 60 // 1 minute\nconst SESSION_LENGTH_LIMIT_MILLISECONDS = 24 * 3600 * 1000 // 24 hours\n\nexport class SessionIdManager {\n private readonly _sessionIdGenerator: () => string\n private readonly _windowIdGenerator: () => string\n private _config: Partial\n private _persistence: PostHogPersistence\n private _windowId: string | null | undefined\n private _sessionId: string | null | undefined\n private readonly _window_id_storage_key: string\n private readonly _primary_window_exists_storage_key: string\n private _sessionStartTimestamp: number | null\n\n private _sessionActivityTimestamp: number | null\n private _sessionIdChangedHandlers: SessionIdChangedCallback[] = []\n private readonly _sessionTimeoutMs: number\n\n // we track activity so we can end the session proactively when it has passed the idle timeout\n private _enforceIdleTimeout: ReturnType | undefined\n\n private _beforeUnloadListener: (() => void) | undefined = undefined\n\n private _eventEmitter: SimpleEventEmitter = new SimpleEventEmitter()\n public on(event: 'forcedIdleReset', handler: () => void): () => void {\n return this._eventEmitter.on(event, handler)\n }\n\n constructor(instance: PostHog, sessionIdGenerator?: () => string, windowIdGenerator?: () => string) {\n if (!instance.persistence) {\n throw new Error('SessionIdManager requires a PostHogPersistence instance')\n }\n if (instance.config.cookieless_mode === COOKIELESS_ALWAYS) {\n throw new Error('SessionIdManager cannot be used with cookieless_mode=\"always\"')\n }\n\n this._config = instance.config\n this._persistence = instance.persistence\n this._windowId = undefined\n this._sessionId = undefined\n this._sessionStartTimestamp = null\n this._sessionActivityTimestamp = null\n this._sessionIdGenerator = sessionIdGenerator || uuidv7\n this._windowIdGenerator = windowIdGenerator || uuidv7\n\n const persistenceName = this._config['persistence_name'] || this._config['token']\n\n const desiredTimeout = this._config['session_idle_timeout_seconds'] || DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS\n this._sessionTimeoutMs =\n clampToRange(\n desiredTimeout,\n MIN_SESSION_IDLE_TIMEOUT_SECONDS,\n MAX_SESSION_IDLE_TIMEOUT_SECONDS,\n logger.createLogger('session_idle_timeout_seconds'),\n DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS\n ) * 1000\n\n instance.register({ $configured_session_timeout_ms: this._sessionTimeoutMs })\n this._resetIdleTimer()\n\n this._window_id_storage_key = 'ph_' + persistenceName + '_window_id'\n this._primary_window_exists_storage_key = 'ph_' + persistenceName + '_primary_window_exists'\n\n // primary_window_exists is set when the DOM has been loaded and is cleared on unload\n // if it exists here it means there was no unload which suggests this window is opened as a tab duplication, window.open, etc.\n if (this._canUseSessionStorage()) {\n const lastWindowId = sessionStore._parse(this._window_id_storage_key)\n\n const primaryWindowExists = sessionStore._parse(this._primary_window_exists_storage_key)\n if (lastWindowId && !primaryWindowExists) {\n // Persist window from previous storage state\n this._windowId = lastWindowId\n } else {\n // Wipe any reference to previous window id\n sessionStore._remove(this._window_id_storage_key)\n }\n // Flag this session as having a primary window\n sessionStore._set(this._primary_window_exists_storage_key, true)\n }\n\n if (this._config.bootstrap?.sessionID) {\n try {\n const sessionStartTimestamp = uuid7ToTimestampMs(this._config.bootstrap.sessionID)\n this._setSessionId(this._config.bootstrap.sessionID, new Date().getTime(), sessionStartTimestamp)\n } catch (e) {\n logger.error('Invalid sessionID in bootstrap', e)\n }\n }\n\n this._listenToReloadWindow()\n }\n\n get sessionTimeoutMs(): number {\n return this._sessionTimeoutMs\n }\n\n onSessionId(callback: SessionIdChangedCallback): () => void {\n // KLUDGE: when running in tests the handlers array was always undefined\n // it's yucky but safe to set it here so that it's always definitely available\n if (isUndefined(this._sessionIdChangedHandlers)) {\n this._sessionIdChangedHandlers = []\n }\n\n this._sessionIdChangedHandlers.push(callback)\n if (this._sessionId) {\n callback(this._sessionId, this._windowId)\n }\n return () => {\n this._sessionIdChangedHandlers = this._sessionIdChangedHandlers.filter((h) => h !== callback)\n }\n }\n\n private _canUseSessionStorage(): boolean {\n // We only want to use sessionStorage if persistence is enabled and not memory storage\n return this._config.persistence !== 'memory' && !this._persistence._disabled && sessionStore._is_supported()\n }\n\n // Note: this tries to store the windowId in sessionStorage. SessionStorage is unique to the current window/tab,\n // and persists page loads/reloads. So it's uniquely suited for storing the windowId. This function also respects\n // when persistence is disabled (by user config) and when sessionStorage is not supported (it *should* be supported on all browsers),\n // and in that case, it falls back to memory (which sadly, won't persist page loads)\n private _setWindowId(windowId: string): void {\n if (windowId !== this._windowId) {\n this._windowId = windowId\n if (this._canUseSessionStorage()) {\n sessionStore._set(this._window_id_storage_key, windowId)\n }\n }\n }\n\n private _getWindowId(): string | null {\n if (this._windowId) {\n return this._windowId\n }\n if (this._canUseSessionStorage()) {\n return sessionStore._parse(this._window_id_storage_key)\n }\n // New window id will be generated\n return null\n }\n\n // Note: 'this.persistence.register' can be disabled in the config.\n // In that case, this works by storing sessionId and the timestamp in memory.\n private _setSessionId(\n sessionId: string | null,\n sessionActivityTimestamp: number | null,\n sessionStartTimestamp: number | null\n ): void {\n if (\n sessionId !== this._sessionId ||\n sessionActivityTimestamp !== this._sessionActivityTimestamp ||\n sessionStartTimestamp !== this._sessionStartTimestamp\n ) {\n this._sessionStartTimestamp = sessionStartTimestamp\n this._sessionActivityTimestamp = sessionActivityTimestamp\n this._sessionId = sessionId\n\n this._persistence.register({\n [SESSION_ID]: [sessionActivityTimestamp, sessionId, sessionStartTimestamp],\n })\n }\n }\n\n private _getSessionId(): [number, string, number] {\n // Always read from persistence - it's the source of truth\n // The in-memory cache could become stale (e.g., in a frozen tab scenario where\n // time passes but the cache isn't updated)\n const sessionIdInfo = this._persistence.props[SESSION_ID]\n\n if (isArray(sessionIdInfo) && sessionIdInfo.length === 2) {\n // Storage does not yet have a session start time. Add the last activity timestamp as the start time\n sessionIdInfo.push(sessionIdInfo[0])\n }\n\n return sessionIdInfo || [0, null, 0]\n }\n\n // Resets the session id by setting it to null. On the subsequent call to checkAndGetSessionAndWindowId,\n // new ids will be generated.\n resetSessionId(): void {\n this._setSessionId(null, null, null)\n }\n\n /**\n * Cleans up resources used by SessionIdManager.\n * Should be called when the SessionIdManager is no longer needed to prevent memory leaks.\n */\n destroy(): void {\n // Clear the idle timeout timer\n clearTimeout(this._enforceIdleTimeout)\n this._enforceIdleTimeout = undefined\n\n // Remove the beforeunload event listener\n if (this._beforeUnloadListener && window) {\n window.removeEventListener(DOM_EVENT_BEFOREUNLOAD, this._beforeUnloadListener, { capture: false } as any)\n this._beforeUnloadListener = undefined\n }\n\n // Clear session id changed handlers\n this._sessionIdChangedHandlers = []\n }\n\n /*\n * Listens to window unloads and removes the primaryWindowExists key from sessionStorage.\n * Reloaded or fresh tabs created after a DOM unloads (reloading the same tab) WILL NOT have this primaryWindowExists flag in session storage.\n * Cloned sessions (new tab, tab duplication, window.open(), ...) WILL have this primaryWindowExists flag in their copied session storage.\n * We conditionally check the primaryWindowExists value in the constructor to decide if the window id in the last session storage should be carried over.\n */\n private _listenToReloadWindow(): void {\n this._beforeUnloadListener = () => {\n if (this._canUseSessionStorage()) {\n sessionStore._remove(this._primary_window_exists_storage_key)\n }\n }\n addEventListener(window, DOM_EVENT_BEFOREUNLOAD, this._beforeUnloadListener, { capture: false })\n }\n\n private _sessionHasBeenIdleTooLong = (timestamp: unknown, lastActivityTimestamp: unknown): boolean => {\n if (!isPositiveNumber(timestamp) || !isPositiveNumber(lastActivityTimestamp)) {\n return false\n }\n return Math.abs(timestamp - lastActivityTimestamp) > this.sessionTimeoutMs\n }\n\n /*\n * This function returns the current sessionId and windowId. It should be used to\n * access these values over directly calling `._sessionId` or `._windowId`.\n * In addition to returning the sessionId and windowId, this function also manages cycling the\n * sessionId and windowId when appropriate by doing the following:\n *\n * 1. If the sessionId or windowId is not set, it will generate a new one and store it.\n * 2. If the readOnly param is set to false, it will:\n * a. Check if it has been > SESSION_CHANGE_THRESHOLD since the last call with this flag set.\n * If so, it will generate a new sessionId and store it.\n * b. Update the timestamp stored with the sessionId to ensure the current session is extended\n * for the appropriate amount of time.\n *\n * @param {boolean} readOnly (optional) Defaults to False. Should be set to True when the call to the function should not extend or cycle the session (e.g. being called for non-user generated events)\n * @param {Number} timestamp (optional) Defaults to the current time. The timestamp to be stored with the sessionId (used when determining if a new sessionId should be generated)\n */\n checkAndGetSessionAndWindowId(readOnly = false, _timestamp: number | null = null) {\n if (this._config.cookieless_mode === COOKIELESS_ALWAYS) {\n throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode=\"always\"')\n }\n const timestamp = _timestamp || new Date().getTime()\n\n // eslint-disable-next-line prefer-const\n let [lastActivityTimestamp, sessionId, startTimestamp] = this._getSessionId()\n let windowId = this._getWindowId()\n\n const sessionPastMaximumLength =\n isPositiveNumber(startTimestamp) && Math.abs(timestamp - startTimestamp) > SESSION_LENGTH_LIMIT_MILLISECONDS\n\n let valuesChanged = false\n const noSessionId = !sessionId\n const activityTimeout =\n !noSessionId && !readOnly && this._sessionHasBeenIdleTooLong(timestamp, lastActivityTimestamp)\n if (noSessionId || activityTimeout || sessionPastMaximumLength) {\n sessionId = this._sessionIdGenerator()\n windowId = this._windowIdGenerator()\n logger.info('new session ID generated', {\n sessionId,\n windowId,\n changeReason: { noSessionId, activityTimeout, sessionPastMaximumLength },\n })\n startTimestamp = timestamp\n valuesChanged = true\n } else if (!windowId) {\n windowId = this._windowIdGenerator()\n valuesChanged = true\n }\n\n const noActivityTimestamp = !isPositiveNumber(lastActivityTimestamp)\n const shouldPreserveActivityTimestamp = !noActivityTimestamp && readOnly && !sessionPastMaximumLength\n const newActivityTimestamp = shouldPreserveActivityTimestamp ? lastActivityTimestamp : timestamp\n\n const noStartTimestamp = !isPositiveNumber(startTimestamp)\n const sessionStartTimestamp = noStartTimestamp ? new Date().getTime() : startTimestamp\n\n this._setWindowId(windowId)\n this._setSessionId(sessionId, newActivityTimestamp, sessionStartTimestamp)\n\n if (!readOnly) {\n this._resetIdleTimer()\n }\n\n if (valuesChanged) {\n this._sessionIdChangedHandlers.forEach((handler) =>\n handler(\n sessionId,\n windowId,\n valuesChanged ? { noSessionId, activityTimeout, sessionPastMaximumLength } : undefined\n )\n )\n }\n\n return {\n sessionId,\n windowId,\n sessionStartTimestamp,\n changeReason: valuesChanged ? { noSessionId, activityTimeout, sessionPastMaximumLength } : undefined,\n lastActivityTimestamp: lastActivityTimestamp,\n }\n }\n\n private _resetIdleTimer() {\n clearTimeout(this._enforceIdleTimeout)\n this._enforceIdleTimeout = setTimeout(() => {\n // enforce idle timeout a little after the session timeout to ensure the session is reset even without activity\n // we need to check session activity first in case a different window has kept the session active\n // while this window has been idle - and the timer has not progressed - e.g. window memory frozen while hidden\n const [lastActivityTimestamp] = this._getSessionId()\n if (this._sessionHasBeenIdleTooLong(new Date().getTime(), lastActivityTimestamp)) {\n const idleSessionId = this._sessionId\n this.resetSessionId()\n this._eventEmitter.emit('forcedIdleReset', { idleSessionId })\n }\n }, this.sessionTimeoutMs * 1.1)\n }\n}\n", "// Re-export shared bot detection logic from @posthog/core\nimport { isBlockedUA as isBlockedUACore } from '@posthog/core'\nexport { DEFAULT_BLOCKED_UA_STRS, isBlockedUA } from '@posthog/core'\n\n// There's more in the type, but this is all we use. It's currently experimental, see\n// https://developer.mozilla.org/en-US/docs/Web/API/Navigator/userAgentData\n// if you're reading this in the future, when it's no longer experimental, please remove this type and use an official one.\n// Be extremely defensive here to ensure backwards and *forwards* compatibility, and remove this defensiveness in the\n// future when it is safe to do so.\nexport interface NavigatorUAData {\n brands?: {\n brand: string\n version: string\n }[]\n platform?: string\n}\ndeclare global {\n interface Navigator {\n userAgentData?: NavigatorUAData\n }\n}\n\nexport const isLikelyBot = function (navigator: Navigator | undefined, customBlockedUserAgents: string[]): boolean {\n if (!navigator) {\n return false\n }\n const ua = navigator.userAgent\n if (ua) {\n if (isBlockedUACore(ua, customBlockedUserAgents)) {\n return true\n }\n }\n try {\n // eslint-disable-next-line compat/compat\n const uaData = navigator?.userAgentData as NavigatorUAData\n if (\n uaData?.brands &&\n uaData.brands.some((brandObj) => isBlockedUACore(brandObj?.brand, customBlockedUserAgents))\n ) {\n return true\n }\n } catch {\n // ignore the error, we were using experimental browser features\n }\n\n return !!navigator.webdriver\n\n // There's some more enhancements we could make in this area, e.g. it's possible to check if Chrome dev tools are\n // open, which will detect some bots that are trying to mask themselves and might get past the checks above.\n // However, this would give false positives for actual humans who have dev tools open.\n\n // We could also use the data in navigator.userAgentData.getHighEntropyValues() to detect bots, but we should wait\n // until this stops being experimental. The MDN docs imply that this might eventually require user permission.\n // See https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/getHighEntropyValues\n // It would be very bad if posthog-js caused a permission prompt to appear on every page load.\n}\n", "export const isValidRegex = function (str: string): boolean {\n try {\n new RegExp(str)\n } catch {\n return false\n }\n return true\n}\n\nexport const isMatchingRegex = function (value: string, pattern: string): boolean {\n if (!isValidRegex(pattern)) return false\n\n try {\n return new RegExp(pattern).test(value)\n } catch {\n return false\n }\n}\n", "import { isArray, isNull, isUndefined } from '@posthog/core'\nimport { jsonStringify } from '../request'\nimport { PropertyFilters, PropertyOperator } from '../posthog-surveys-types'\nimport type { Properties, SessionRecordingTriggerPropertyFilter } from '../types'\nimport { isMatchingRegex } from './regex-utils'\n\nexport function getPersonPropertiesHash(\n distinct_id: string,\n userPropertiesToSet?: Properties,\n userPropertiesToSetOnce?: Properties\n): string {\n return jsonStringify({ distinct_id, userPropertiesToSet, userPropertiesToSetOnce })\n}\n\nexport const propertyComparisons: Record boolean> = {\n exact: (targets, values) => values.some((value) => targets.some((target) => value === target)),\n is_not: (targets, values) => values.every((value) => targets.every((target) => value !== target)),\n regex: (targets, values) => values.some((value) => targets.some((target) => isMatchingRegex(value, target))),\n not_regex: (targets, values) => values.every((value) => targets.every((target) => !isMatchingRegex(value, target))),\n icontains: (targets, values) =>\n values.map(toLowerCase).some((value) => targets.map(toLowerCase).some((target) => value.includes(target))),\n not_icontains: (targets, values) =>\n values.map(toLowerCase).every((value) => targets.map(toLowerCase).every((target) => !value.includes(target))),\n gt: (targets, values) =>\n values.some((value) => {\n const numValue = parseFloat(value)\n return !isNaN(numValue) && targets.some((t) => numValue > parseFloat(t))\n }),\n lt: (targets, values) =>\n values.some((value) => {\n const numValue = parseFloat(value)\n return !isNaN(numValue) && targets.some((t) => numValue < parseFloat(t))\n }),\n}\n\nconst toLowerCase = (v: string): string => v.toLowerCase()\n\n// Operators whose semantics mean \"property is not X\". When the property being\n// filtered on is missing or null, these match — absence of the property\n// satisfies a \"not equal to X\" check. This aligns with how PostHog's feature\n// flag matchers (posthog/queries/base.py, rust/feature-flags) treat missing\n// properties for negative operators.\nconst NEGATIVE_OPERATORS: ReadonlySet = new Set(['is_not', 'not_icontains', 'not_regex'])\n\n/**\n * Evaluate trigger property filters (WHERE clauses) against event and person properties.\n * All filters must match (implicit AND). Returns true if no filters are present.\n */\nexport function matchTriggerPropertyFilters(\n filters: SessionRecordingTriggerPropertyFilter[] | undefined,\n eventProperties: Properties | undefined,\n personProperties: Properties | undefined\n): boolean {\n if (!filters || filters.length === 0) {\n return true\n }\n\n return filters.every((filter) => {\n const source = filter.type === 'person' ? personProperties : eventProperties\n const propertyValue = source?.[filter.key]\n const operator = filter.operator || 'exact'\n\n // Missing or null property: for negative operators, absence counts as a\n // match (nothing can't equal EU, so \"is_not EU\" is satisfied). For\n // positive operators, we can't confirm a match without a value.\n if (isUndefined(propertyValue) || isNull(propertyValue)) {\n return NEGATIVE_OPERATORS.has(operator)\n }\n\n const comparisonFunction = propertyComparisons[operator as PropertyOperator]\n if (!comparisonFunction) {\n return false\n }\n\n if (isUndefined(filter.value) || isNull(filter.value)) {\n return false\n }\n\n // Normalize filter value and property value to string arrays for comparison\n const targetValues = isArray(filter.value) ? filter.value.map(String) : [String(filter.value)]\n const actualValues = isArray(propertyValue) ? propertyValue.map(String) : [String(propertyValue)]\n\n return comparisonFunction(targetValues, actualValues)\n })\n}\n\nexport function matchPropertyFilters(\n propertyFilters: PropertyFilters | undefined,\n eventProperties: Properties | undefined\n): boolean {\n // if there are no property filters, it means we're only matching on event name\n if (!propertyFilters) {\n return true\n }\n\n return Object.entries(propertyFilters).every(([propertyName, filter]) => {\n const eventPropertyValue = eventProperties?.[propertyName]\n\n if (isUndefined(eventPropertyValue) || isNull(eventPropertyValue)) {\n return false\n }\n\n // convert event property to string array for comparison\n const eventValues = [String(eventPropertyValue)]\n\n const comparisonFunction = propertyComparisons[filter.operator]\n if (!comparisonFunction) {\n return false\n }\n\n return comparisonFunction(filter.values, eventValues)\n })\n}\n", "import { PostHog } from '../posthog-core'\n\n/**\n * The request router helps simplify the logic to determine which endpoints should be called for which things\n * The basic idea is that for a given region (US or EU), we have a set of endpoints that we should call depending\n * on the type of request (events, replays, flags, etc.) and handle overrides that may come from configs or the flags endpoint\n */\n\nexport const RequestRouterRegion = {\n US: 'us',\n EU: 'eu',\n CUSTOM: 'custom',\n} as const\nexport type RequestRouterRegion = (typeof RequestRouterRegion)[keyof typeof RequestRouterRegion]\n\nexport type RequestRouterTarget = 'api' | 'ui' | 'assets' | 'flags'\n\nconst ingestionDomain = 'i.posthog.com'\nconst staticAssetPath = /^\\/static\\//\n\nexport class RequestRouter {\n instance: PostHog\n private _regionCache: Record = {}\n\n constructor(instance: PostHog) {\n this.instance = instance\n }\n\n get apiHost(): string {\n const host = this.instance.config.api_host.trim().replace(/\\/$/, '')\n if (host === 'https://app.posthog.com') {\n return 'https://us.i.posthog.com'\n }\n return host\n }\n\n get flagsApiHost(): string {\n const customHost = this.instance.config.flags_api_host\n if (customHost) {\n return customHost.trim().replace(/\\/$/, '')\n }\n // Backwards compatibility: if no custom flags_api_host is set, fall back to the regular apiHost\n return this.apiHost\n }\n\n get uiHost(): string | undefined {\n let host = this.instance.config.ui_host?.replace(/\\/$/, '')\n\n if (!host) {\n // No ui_host set, get it from the api_host. But api_host differs\n // from the actual UI host, so replace the ingestion subdomain with just posthog.com\n host = this.apiHost.replace(`.${ingestionDomain}`, '.posthog.com')\n }\n\n if (host === 'https://app.posthog.com') {\n return 'https://us.posthog.com'\n }\n\n return host\n }\n\n get region(): RequestRouterRegion {\n // We don't need to compute this every time so we cache the result\n if (!this._regionCache[this.apiHost]) {\n if (/https:\\/\\/(app|us|us-assets)(\\.i)?\\.posthog\\.com/i.test(this.apiHost)) {\n this._regionCache[this.apiHost] = RequestRouterRegion.US\n } else if (/https:\\/\\/(eu|eu-assets)(\\.i)?\\.posthog\\.com/i.test(this.apiHost)) {\n this._regionCache[this.apiHost] = RequestRouterRegion.EU\n } else {\n this._regionCache[this.apiHost] = RequestRouterRegion.CUSTOM\n }\n }\n return this._regionCache[this.apiHost]\n }\n\n private _staticAssetHostOverride(path: string): string | undefined {\n const override = this.instance.config.__preview_external_dependency_versioned_paths\n if (typeof override !== 'string' || !staticAssetPath.test(path)) {\n return undefined\n }\n\n const normalizedOverride = override.trim().replace(/\\/$/, '')\n return normalizedOverride || undefined\n }\n\n endpointFor(target: RequestRouterTarget, path: string = ''): string {\n if (path) {\n path = path[0] === '/' ? path : `/${path}`\n }\n\n if (target === 'ui') {\n return this.uiHost + path\n }\n\n if (target === 'flags') {\n return this.flagsApiHost + path\n }\n\n if (target === 'assets') {\n const assetHostOverride = this._staticAssetHostOverride(path)\n if (assetHostOverride) {\n return `${assetHostOverride}${path}`\n }\n }\n\n if (this.region === RequestRouterRegion.CUSTOM) {\n return this.apiHost + path\n }\n\n const suffix = ingestionDomain + path\n\n switch (target) {\n case 'assets':\n return `https://${this.region}-assets.${suffix}`\n case 'api':\n return `https://${this.region}.${suffix}`\n }\n }\n}\n", "import { DisplaySurveyOptions, Survey, SurveyType, DisplaySurveyType } from '../posthog-surveys-types'\nimport { createLogger } from '../utils/logger'\n\nexport const SURVEY_LOGGER = createLogger('[Surveys]')\n\nexport function isSurveyRunning(survey: Survey): boolean {\n return !!(survey.start_date && !survey.end_date)\n}\n\nexport function doesSurveyActivateByEvent(survey: Pick): boolean {\n return !!survey.conditions?.events?.values?.length\n}\n\nexport function doesSurveyActivateByAction(survey: Pick): boolean {\n return !!survey.conditions?.actions?.values?.length\n}\n\nexport const SURVEY_SEEN_PREFIX = 'seenSurvey_'\nexport const SURVEY_IN_PROGRESS_PREFIX = 'inProgressSurvey_'\nexport const SURVEY_ABANDONED_PREFIX = 'abandonedSurvey_'\n\nexport const getSurveyInteractionProperty = (\n survey: Pick,\n action: 'responded' | 'dismissed'\n): string => {\n let surveyProperty = `$survey_${action}/${survey.id}`\n if (survey.current_iteration && survey.current_iteration > 0) {\n surveyProperty = `$survey_${action}/${survey.id}/${survey.current_iteration}`\n }\n\n return surveyProperty\n}\n\nconst getSurveyStorageKey = (prefix: string, survey: Pick): string => {\n let key = `${prefix}${survey.id}`\n if (survey.current_iteration && survey.current_iteration > 0) {\n key = `${prefix}${survey.id}_${survey.current_iteration}`\n }\n return key\n}\n\nexport const getSurveySeenKey = (survey: Pick): string => {\n return getSurveyStorageKey(SURVEY_SEEN_PREFIX, survey)\n}\n\nexport const getSurveyAbandonedKey = (survey: Pick): string => {\n return getSurveyStorageKey(SURVEY_ABANDONED_PREFIX, survey)\n}\n\nexport const setSurveySeenOnLocalStorage = (survey: Pick) => {\n const isSurveySeen = localStorage.getItem(getSurveySeenKey(survey))\n // if survey is already seen, no need to set it again\n if (isSurveySeen) {\n return\n }\n\n localStorage.setItem(getSurveySeenKey(survey), 'true')\n}\n\n// These surveys are relevant for the getActiveMatchingSurveys method. They are used to\n// display surveys in our customer's application. Any new in-app survey type should be added here.\nexport const IN_APP_SURVEY_TYPES: SurveyType[] = [SurveyType.Popover, SurveyType.Widget, SurveyType.API]\n\nexport const DEFAULT_DISPLAY_SURVEY_OPTIONS: DisplaySurveyOptions = {\n ignoreConditions: false,\n ignoreDelay: false,\n displayType: DisplaySurveyType.Popover,\n}\n", "import { PostHog } from '../posthog-core'\nimport { ExternalIntegrationKind } from '../types'\nimport { assignableWindow, ExternalExtensionKind } from '../utils/globals'\nimport { createLogger } from '../utils/logger'\n\nconst logger = createLogger('[PostHog ExternalIntegrations]')\n\nconst MAPPED_INTEGRATIONS: Record = {\n intercom: 'intercom-integration',\n crispChat: 'crisp-chat-integration',\n}\n\nexport class ExternalIntegrations {\n constructor(private readonly _instance: PostHog) {}\n\n private _loadScript(name: ExternalExtensionKind, cb: () => void): void {\n assignableWindow.__PosthogExtensions__?.loadExternalDependency?.(this._instance, name, (err) => {\n if (err) {\n return logger.error('failed to load script', err)\n }\n cb()\n })\n }\n\n public startIfEnabledOrStop() {\n for (const [key, value] of Object.entries(this._instance.config.integrations ?? {})) {\n // if the integration is enabled, and not present, then load it\n if (value && !assignableWindow.__PosthogExtensions__?.integrations?.[key as ExternalIntegrationKind]) {\n this._loadScript(MAPPED_INTEGRATIONS[key as ExternalIntegrationKind], () => {\n assignableWindow.__PosthogExtensions__?.integrations?.[key as ExternalIntegrationKind]?.start(\n this._instance\n )\n })\n }\n // if the integration is disabled, and present, then stop it\n if (!value && assignableWindow.__PosthogExtensions__?.integrations?.[key as ExternalIntegrationKind]) {\n assignableWindow.__PosthogExtensions__?.integrations?.[key as ExternalIntegrationKind]?.stop()\n }\n }\n }\n}\n", "import Config from './config'\nimport { ConsentManager, ConsentStatus } from './consent'\nimport {\n ALIAS_ID_KEY,\n COOKIELESS_MODE_FLAG_PROPERTY,\n COOKIELESS_SENTINEL_VALUE,\n COOKIELESS_ON_REJECT,\n DEVICE_ID,\n PERSON_PROFILES_IDENTIFIED_ONLY,\n USER_STATE_ANONYMOUS,\n USER_STATE_IDENTIFIED,\n DOM_EVENT_VISIBILITYCHANGE,\n ENABLE_PERSON_PROCESSING,\n EVENT_GROUPIDENTIFY,\n EVENT_IDENTIFY,\n EVENT_PAGELEAVE,\n EVENT_PAGEVIEW,\n FLAG_CALL_REPORTED,\n PEOPLE_DISTINCT_ID_KEY,\n SURVEYS_REQUEST_TIMEOUT_MS,\n USER_STATE,\n COOKIELESS_ALWAYS,\n} from './constants'\nimport { isDeadClicksEnabledForAutocapture } from './extensions/dead-clicks-autocapture'\nimport { setupSegmentIntegration } from './extensions/segment-integration'\nimport { SentryIntegration, sentryIntegration, SentryIntegrationOptions } from './extensions/sentry-integration'\nimport { PageViewManager } from './page-view'\nimport { PostHogPersistence } from './posthog-persistence'\nimport {\n type DisplaySurveyOptions,\n type SurveyCallback,\n SurveyEventName,\n SurveyEventProperties,\n type SurveyRenderReason,\n} from './posthog-surveys-types'\nimport { ProductTourEventName, ProductTourEventProperties } from './posthog-product-tours-types'\nimport { RateLimiter } from './rate-limiter'\nimport { RemoteConfigLoader } from './remote-config'\nimport { extendURLParams, request, SUPPORTS_REQUEST } from './request'\nimport { DEFAULT_FLUSH_INTERVAL_MS, RequestQueue } from './request-queue'\nimport { RetryQueue } from './retry-queue'\nimport { ScrollManager } from './scroll-manager'\nimport { SessionPropsManager } from './session-props'\nimport { SessionIdManager } from './sessionid'\nimport { localStore } from './storage'\nimport {\n CaptureLogOptions,\n CaptureOptions,\n CaptureResult,\n Compression,\n ConfigDefaults,\n EarlyAccessFeatureCallback,\n EarlyAccessFeatureStage,\n EventName,\n ExceptionAutoCaptureConfig,\n FeatureFlagsCallback,\n FeatureFlagOptions,\n FeatureFlagResult,\n JsonType,\n OverrideConfig,\n PostHogConfig,\n Properties,\n Property,\n QueuedRequestWithOptions,\n RemoteConfig,\n RequestCallback,\n SessionIdChangedCallback,\n SnippetArrayItem,\n ToolbarParams,\n PostHogInterface,\n} from './types'\nimport type { TreeShakeable } from '@posthog/types'\nimport {\n _copyAndTruncateStrings,\n addEventListener,\n each,\n eachArray,\n extend,\n isCrossDomainCookie,\n migrateConfigField,\n safewrapClass,\n} from './utils'\nimport { isLikelyBot } from './utils/blocked-uas'\nimport { getEventProperties } from './utils/event-utils'\nimport { assignableWindow, document, location, navigator, userAgent, window } from './utils/globals'\nimport { logger } from './utils/logger'\nimport { getPersonPropertiesHash } from './utils/property-utils'\nimport { RequestRouter, RequestRouterRegion } from './utils/request-router'\nimport { SimpleEventEmitter } from './utils/simple-event-emitter'\nimport {\n DEFAULT_DISPLAY_SURVEY_OPTIONS,\n getSurveyInteractionProperty,\n setSurveySeenOnLocalStorage,\n} from './utils/survey-utils'\nimport {\n isEmptyString,\n isFunction,\n isKnownUnsafeEditableEvent,\n isNullish,\n isNumber,\n isString,\n isUndefined,\n includes,\n isDistinctIdStringLike,\n isArray,\n isEmptyObject,\n isObject,\n isBoolean,\n} from '@posthog/core'\nimport { uuidv7 } from './uuidv7'\nimport { ExternalIntegrations } from './extensions/external-integration'\nimport type { PostHogSurveys } from './posthog-surveys'\nimport type { Autocapture } from './autocapture'\nimport type { DeadClicksAutocapture } from './extensions/dead-clicks-autocapture'\nimport type { ExceptionObserver } from './extensions/exception-autocapture'\nimport type { HistoryAutocapture } from './extensions/history-autocapture'\nimport type { WebVitalsAutocapture } from './extensions/web-vitals'\nimport type { Heatmaps } from './heatmaps'\nimport type { PostHogConversations } from './extensions/conversations/posthog-conversations'\nimport type { PostHogExceptions } from './posthog-exceptions'\nimport type { PostHogLogs } from './posthog-logs'\nimport type { PostHogProductTours } from './posthog-product-tours'\nimport type { SiteApps } from './site-apps'\nimport type { SessionRecording } from './extensions/replay/session-recording'\nimport type { Extension } from './extensions/types'\nimport type { Toolbar } from './extensions/toolbar'\nimport type { PostHogFeatureFlags } from './posthog-featureflags'\nimport type { WebExperiments } from './web-experiments'\n\n/*\nSIMPLE STYLE GUIDE:\n\nUse TypeScript accessibility modifiers, e.g. private/protected\n\nIf something is not part of the public interface:\n* prefix it with _ to allow mangling\n* prefix it with __ to disable mangling, but signal that it is internal\n\nGlobals should be all caps\n*/\n\n/* posthog.init is called with `Partial`\n * and we want to ensure that only valid keys are passed to the config object.\n * TypeScript does not enforce that the object passed does not have extra keys.\n * So someone can call with { bootstrap: { distinctId: '123'} }\n * which is not a valid key. They should have passed distinctID (upper case D).\n * That's a really tricky mistake to spot.\n * The OnlyValidKeys type ensures that only keys that are valid in the PostHogConfig type are allowed.\n */\ntype OnlyValidKeys = T extends Shape ? (Exclude extends never ? T : never) : never\n\nconst instances: Record = {}\n\n// Tracks re-entrant calls to _execute_array. Used to detect when a third-party\n// Proxy (e.g., TikTok's in-app browser) wraps window.posthog and converts method\n// calls into push() calls, which would otherwise cause infinite recursion.\nlet _executeArrayDepth = 0\n\nconst __NOOP = () => {}\nconst CONSENT_COOKIELESS_WARN = 'Consent opt in/out is not valid with cookieless_mode=\"always\" and will be ignored'\nconst SURVEYS_NOT_AVAILABLE = 'Surveys module not available'\nconst SANITIZE_DEPRECATED = 'sanitize_properties is deprecated. Use before_send instead'\nconst DENYLIST_INVALID = 'Invalid value for property_denylist config: '\n\nconst PRIMARY_INSTANCE_NAME = 'posthog'\n\n/*\n * Dynamic... constants? Is that an oxymoron?\n */\n// http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/\n// https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#withCredentials\n\n// IE<10 does not support cross-origin XHR's but script tags\n// with defer won't block window.onload; ENQUEUE_REQUESTS\n// should only be true for Opera<12\nlet ENQUEUE_REQUESTS = !SUPPORTS_REQUEST && userAgent?.indexOf('MSIE') === -1 && userAgent?.indexOf('Mozilla') === -1\n\nconst defaultsThatVaryByConfig = (\n defaults?: ConfigDefaults\n): Pick<\n PostHogConfig,\n | 'rageclick'\n | 'capture_pageview'\n | 'session_recording'\n | 'external_scripts_inject_target'\n | 'internal_or_test_user_hostname'\n> => ({\n rageclick: defaults && defaults >= '2025-11-30' ? { content_ignorelist: true } : true,\n capture_pageview: defaults && defaults >= '2025-05-24' ? 'history_change' : true,\n session_recording: defaults && defaults >= '2025-11-30' ? { strictMinimumDuration: true } : {},\n external_scripts_inject_target: defaults && defaults >= '2026-01-30' ? 'head' : 'body',\n internal_or_test_user_hostname: defaults && defaults >= '2026-01-30' ? /^(localhost|127\\.0\\.0\\.1)$/ : undefined,\n})\n\n// NOTE: Remember to update `types.ts` when changing a default value\n// to guarantee documentation is up to date, make sure to also update our website docs\n// NOTE²: This shouldn't ever change because we try very hard to be backwards-compatible\nexport const defaultConfig = (defaults?: ConfigDefaults): PostHogConfig => ({\n api_host: 'https://us.i.posthog.com',\n flags_api_host: null,\n ui_host: null,\n token: '',\n autocapture: true,\n cross_subdomain_cookie: isCrossDomainCookie(document?.location),\n persistence: 'localStorage+cookie', // up to 1.92.0 this was 'cookie'. It's easy to migrate as 'localStorage+cookie' will migrate data from cookie storage\n persistence_name: '',\n cookie_persisted_properties: [],\n loaded: __NOOP,\n save_campaign_params: true,\n custom_campaign_params: [],\n custom_blocked_useragents: [],\n save_referrer: true,\n capture_pageleave: 'if_capture_pageview', // We'll only capture pageleave events if capture_pageview is also true\n defaults: defaults ?? 'unset',\n __preview_deferred_init_extensions: false, // Opt-in only for now\n __preview_external_dependency_versioned_paths: false,\n debug: (location && isString(location?.search) && location.search.indexOf('__posthog_debug=true') !== -1) || false,\n cookie_expiration: 365,\n upgrade: false,\n disable_session_recording: false,\n disable_persistence: false,\n disable_web_experiments: true, // disabled in beta.\n disable_surveys: false,\n disable_surveys_automatic_display: false,\n disable_conversations: false,\n disable_product_tours: false,\n disable_external_dependency_loading: false,\n enable_recording_console_log: undefined, // When undefined, it falls back to the server-side setting\n secure_cookie: window?.location?.protocol === 'https:',\n ip: false,\n opt_out_capturing_by_default: false,\n opt_out_persistence_by_default: false,\n opt_out_useragent_filter: false,\n opt_out_capturing_persistence_type: 'localStorage',\n consent_persistence_name: null,\n opt_out_capturing_cookie_prefix: null,\n opt_in_site_apps: false,\n property_denylist: [],\n respect_dnt: false,\n sanitize_properties: null,\n request_headers: {}, // { header: value, header2: value }\n request_batching: true,\n properties_string_max_length: 65535,\n mask_all_element_attributes: false,\n mask_all_text: false,\n mask_personal_data_properties: false,\n custom_personal_data_properties: [],\n advanced_disable_flags: false,\n advanced_disable_decide: false,\n advanced_disable_feature_flags: false,\n advanced_disable_feature_flags_on_first_load: false,\n advanced_only_evaluate_survey_feature_flags: false,\n advanced_feature_flags_dedup_per_session: false,\n advanced_enable_surveys: false,\n advanced_disable_toolbar_metrics: false,\n feature_flag_request_timeout_ms: 3000,\n surveys_request_timeout_ms: SURVEYS_REQUEST_TIMEOUT_MS,\n on_request_error: (res) => {\n const error = 'Bad HTTP status: ' + res.statusCode + ' ' + res.text\n logger.error(error)\n },\n get_device_id: (uuid) => uuid,\n capture_performance: undefined,\n name: 'posthog',\n bootstrap: {},\n disable_compression: false,\n session_idle_timeout_seconds: 30 * 60, // 30 minutes\n person_profiles: PERSON_PROFILES_IDENTIFIED_ONLY,\n before_send: undefined,\n request_queue_config: { flush_interval_ms: DEFAULT_FLUSH_INTERVAL_MS },\n error_tracking: {},\n\n // Used for internal testing\n _onCapture: __NOOP,\n\n // make the default be lazy loading replay\n __preview_eager_load_replay: false,\n\n ...defaultsThatVaryByConfig(defaults),\n})\n\nconst CONFIG_RENAMES: [keyof PostHogConfig, keyof PostHogConfig][] = [\n ['process_person', 'person_profiles'],\n ['xhr_headers', 'request_headers'],\n ['cookie_name', 'persistence_name'],\n ['disable_cookie', 'disable_persistence'],\n ['store_google', 'save_campaign_params'],\n ['verbose', 'debug'],\n]\n\nexport const configRenames = (origConfig: Partial): Partial => {\n const renames: Partial = {}\n for (const [oldKey, newKey] of CONFIG_RENAMES) {\n if (!isUndefined((origConfig as any)[oldKey])) {\n ;(renames as any)[newKey] = (origConfig as any)[oldKey]\n }\n }\n // on_xhr_error is not present, as the type is different to on_request_error\n\n // the original config takes priority over the renames\n const newConfig = extend({}, renames, origConfig)\n\n // merge property_blacklist into property_denylist\n if (isArray(origConfig.property_blacklist)) {\n if (isUndefined(origConfig.property_denylist)) {\n newConfig.property_denylist = origConfig.property_blacklist\n } else if (isArray(origConfig.property_denylist)) {\n newConfig.property_denylist = [...origConfig.property_blacklist, ...origConfig.property_denylist]\n } else {\n logger.error(DENYLIST_INVALID + origConfig.property_denylist)\n }\n }\n\n return newConfig\n}\n\nclass DeprecatedWebPerformanceObserver {\n get _forceAllowLocalhost(): boolean {\n return this.__forceAllowLocalhost\n }\n\n set _forceAllowLocalhost(value: boolean) {\n logger.error(\n 'WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`'\n )\n this.__forceAllowLocalhost = value\n }\n\n private __forceAllowLocalhost: boolean = false\n}\n\n/**\n *\n * This is the SDK reference for the PostHog JavaScript Web SDK.\n * You can learn more about example usage in the\n * [JavaScript Web SDK documentation](/docs/libraries/js).\n * You can also follow [framework specific guides](/docs/frameworks)\n * to integrate PostHog into your project.\n *\n * This SDK is designed for browser environments.\n * Use the PostHog [Node.js SDK](/docs/libraries/node) for server-side usage.\n *\n * @constructor\n */\nexport class PostHog implements PostHogInterface {\n static __defaultExtensionClasses: PostHogConfig['__extensionClasses'] = {}\n\n __loaded: boolean\n config: PostHogConfig\n _originalUserConfig?: Partial\n\n rateLimiter: RateLimiter\n scrollManager: ScrollManager\n pageViewManager: PageViewManager\n featureFlags: TreeShakeable\n surveys: TreeShakeable\n conversations: TreeShakeable\n logs: TreeShakeable\n experiments: TreeShakeable\n toolbar: TreeShakeable\n exceptions: TreeShakeable\n consent: ConsentManager\n\n // These are instance-specific state created after initialisation\n persistence?: PostHogPersistence\n sessionPersistence?: PostHogPersistence\n sessionManager?: SessionIdManager\n sessionPropsManager?: SessionPropsManager\n requestRouter: RequestRouter\n siteApps?: SiteApps\n autocapture?: Autocapture\n heatmaps?: Heatmaps\n webVitalsAutocapture?: WebVitalsAutocapture\n exceptionObserver?: ExceptionObserver\n deadClicksAutocapture?: DeadClicksAutocapture\n historyAutocapture?: HistoryAutocapture\n productTours?: PostHogProductTours\n\n _requestQueue?: RequestQueue\n _retryQueue?: RetryQueue\n sessionRecording?: SessionRecording\n externalIntegrations?: ExternalIntegrations\n webPerformance = new DeprecatedWebPerformanceObserver()\n\n _initialPageviewCaptured: boolean\n _visibilityStateListener: (() => void) | null\n _personProcessingSetOncePropertiesSent: boolean = false\n _triggered_notifs: any\n compression?: Compression\n __request_queue: QueuedRequestWithOptions[]\n _pendingRemoteConfig?: RemoteConfig\n _remoteConfigLoader?: RemoteConfigLoader\n analyticsDefaultEndpoint: string\n version: string = Config.LIB_VERSION\n _initialPersonProfilesConfig: 'always' | 'never' | 'identified_only' | null\n _cachedPersonProperties: string | null\n\n SentryIntegration: typeof SentryIntegration\n sentryIntegration: (options?: SentryIntegrationOptions) => ReturnType\n\n _internalEventEmitter = new SimpleEventEmitter()\n\n private readonly _extensions: Extension[] = []\n\n private _replaceExtension(oldExt: T | undefined, newExt: T): T {\n if (oldExt) {\n const idx = this._extensions.indexOf(oldExt)\n if (idx !== -1) {\n this._extensions.splice(idx, 1)\n }\n }\n this._extensions.push(newExt)\n newExt.initialize?.()\n return newExt\n }\n\n // Legacy property to support existing usage - this isn't technically correct but it's what it has always been - a proxy for flags being loaded\n /** @deprecated Use `flagsEndpointWasHit` instead. We migrated to using a new feature flag endpoint and the new method is more semantically accurate */\n public get decideEndpointWasHit(): boolean {\n return this.featureFlags?.hasLoadedFlags ?? false\n }\n\n public get flagsEndpointWasHit(): boolean {\n return this.featureFlags?.hasLoadedFlags ?? false\n }\n\n /** DEPRECATED: We keep this to support existing usage but now one should just call .setPersonProperties */\n people: {\n set: (prop: string | Properties, to?: string, callback?: RequestCallback) => void\n set_once: (prop: string | Properties, to?: string, callback?: RequestCallback) => void\n }\n\n constructor() {\n this.config = defaultConfig()\n\n this.SentryIntegration = SentryIntegration\n this.sentryIntegration = (options?: SentryIntegrationOptions) => sentryIntegration(this, options)\n this.__request_queue = []\n this.__loaded = false\n this.analyticsDefaultEndpoint = '/e/'\n this._initialPageviewCaptured = false\n this._visibilityStateListener = null\n this._initialPersonProfilesConfig = null\n this._cachedPersonProperties = null\n this.scrollManager = new ScrollManager(this)\n this.pageViewManager = new PageViewManager(this)\n this.rateLimiter = new RateLimiter(this)\n this.requestRouter = new RequestRouter(this)\n this.consent = new ConsentManager(this)\n this.externalIntegrations = new ExternalIntegrations(this)\n\n // Eagerly construct extensions from default classes so they're available before init().\n // For the slim bundle, these remain undefined until _initExtensions sets them from config.\n const ext = PostHog.__defaultExtensionClasses ?? {}\n this.featureFlags = ext.featureFlags && new ext.featureFlags(this)\n this.toolbar = ext.toolbar && new ext.toolbar(this)\n this.surveys = ext.surveys && new ext.surveys(this)\n this.conversations = ext.conversations && new ext.conversations(this)\n this.logs = ext.logs && new ext.logs(this)\n this.experiments = ext.experiments && new ext.experiments(this)\n this.exceptions = ext.exceptions && new ext.exceptions(this)\n\n // NOTE: See the property definition for deprecation notice\n this.people = {\n set: (prop: string | Properties, to?: string, callback?: RequestCallback) => {\n const setProps = isString(prop) ? { [prop]: to } : prop\n this.setPersonProperties(setProps)\n callback?.({} as any)\n },\n set_once: (prop: string | Properties, to?: string, callback?: RequestCallback) => {\n const setProps = isString(prop) ? { [prop]: to } : prop\n this.setPersonProperties(undefined, setProps)\n callback?.({} as any)\n },\n }\n\n this.on('eventCaptured', (data) => logger.info(`send \"${data?.event}\"`, data))\n }\n\n // Initialization methods\n\n /**\n * Initializes a new instance of the PostHog capturing object.\n *\n * @remarks\n * All new instances are added to the main posthog object as sub properties (such as\n * `posthog.library_name`) and also returned by this function. [Learn more about configuration options](https://github.com/posthog/posthog-js/blob/6e0e873/src/posthog-core.js#L57-L91)\n *\n * @example\n * ```js\n * // basic initialization\n * posthog.init('', {\n * api_host: ''\n * })\n * ```\n *\n * @example\n * ```js\n * // multiple instances\n * posthog.init('', {}, 'project1')\n * posthog.init('', {}, 'project2')\n * ```\n *\n * @public\n *\n * @param token - Your PostHog API token\n * @param config - A dictionary of config options to override\n * @param name - The name for the new posthog instance that you want created\n *\n * {@label Initialization}\n *\n * @returns The newly initialized PostHog instance\n */\n init(\n token: string,\n config?: OnlyValidKeys, Partial>,\n name?: string\n ): PostHog {\n if (!name || name === PRIMARY_INSTANCE_NAME) {\n // This means we are initializing the primary instance (i.e. this)\n return this._init(token, config, name)\n } else {\n const namedPosthog = instances[name] ?? new PostHog()\n namedPosthog._init(token, config, name)\n instances[name] = namedPosthog\n\n // Add as a property to the primary instance (this isn't type-safe but it is how it was always done)\n ;(instances[PRIMARY_INSTANCE_NAME] as any)[name] = namedPosthog\n\n return namedPosthog\n }\n }\n\n // posthog._init(token:string, config:object, name:string)\n //\n // This function sets up the current instance of the posthog\n // library. The difference between this method and the init(...)\n // method is this one initializes the actual instance, whereas the\n // init(...) method sets up a new library and calls _init on it.\n //\n // Note that there are operations that can be asynchronous, so we\n // accept a callback that is called when all the asynchronous work\n // is done. Note that we do not use promises because we want to be\n // IE11 compatible. We could use polyfills, which would make the\n // code a bit cleaner, but will add some overhead.\n //\n _init(token: string, config: Partial = {}, name?: string): PostHog {\n if (isUndefined(token) || isEmptyString(token)) {\n logger.critical(\n 'PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()'\n )\n return this\n }\n\n if (this.__loaded) {\n // need to be able to log before having processed debug config\n // eslint-disable-next-line no-console\n console.warn('[PostHog.js]', 'You have already initialized PostHog! Re-initializing is a no-op')\n return this\n }\n\n this.__loaded = true\n this.config = {} as PostHogConfig // will be set right below\n config.debug = this._checkLocalStorageForDebug(config.debug)\n this._originalUserConfig = config // Store original user config for migration\n\n this._triggered_notifs = []\n\n if (config.person_profiles) {\n this._initialPersonProfilesConfig = config.person_profiles\n } else if (config.process_person) {\n this._initialPersonProfilesConfig = config.process_person\n }\n\n this.set_config(\n extend({}, defaultConfig(config.defaults), configRenames(config), {\n name: name,\n token: token,\n })\n )\n\n if (this.config.on_xhr_error) {\n logger.error('on_xhr_error is deprecated. Use on_request_error instead')\n }\n\n this.compression = config.disable_compression ? undefined : Compression.GZipJS\n\n const persistenceDisabled = this._is_persistence_disabled()\n\n this.persistence = new PostHogPersistence(this.config, persistenceDisabled)\n this.sessionPersistence =\n this.config.persistence === 'sessionStorage' || this.config.persistence === 'memory'\n ? this.persistence\n : new PostHogPersistence({ ...this.config, persistence: 'sessionStorage' }, persistenceDisabled)\n\n // should I store the initial person profiles config in persistence?\n const initialPersistenceProps = { ...this.persistence.props }\n const initialSessionProps = { ...this.sessionPersistence.props }\n\n this.register({ $initialization_time: new Date().toISOString() })\n\n this._requestQueue = new RequestQueue(\n (req) => this._send_retriable_request(req),\n this.config.request_queue_config\n )\n this._retryQueue = new RetryQueue(this)\n this.__request_queue = []\n\n const startInCookielessMode =\n this.config.cookieless_mode === COOKIELESS_ALWAYS ||\n (this.config.cookieless_mode === COOKIELESS_ON_REJECT && this.consent.isExplicitlyOptedOut())\n\n if (!startInCookielessMode) {\n this.sessionManager = new SessionIdManager(this)\n this.sessionPropsManager = new SessionPropsManager(this, this.sessionManager, this.persistence)\n }\n\n // Conditionally defer extension initialization based on config\n if (this.config.__preview_deferred_init_extensions) {\n // EXPERIMENTAL: Defer non-critical extension initialization to next tick\n // This reduces main thread blocking during init\n // while keeping critical path (persistence, sessions, capture) synchronous\n logger.info('Deferring extension initialization to improve startup performance')\n setTimeout(() => {\n this._initExtensions(startInCookielessMode)\n }, 0)\n } else {\n // Legacy synchronous initialization (default for now)\n logger.info('Initializing extensions synchronously')\n this._initExtensions(startInCookielessMode)\n }\n\n // if any instance on the page has debug = true, we set the\n // global debug to be true\n Config.DEBUG = Config.DEBUG || this.config.debug\n if (Config.DEBUG) {\n logger.info('Starting in debug mode', {\n this: this,\n config,\n thisC: { ...this.config },\n p: initialPersistenceProps,\n s: initialSessionProps,\n })\n }\n\n // When identity_distinct_id is provided at init time, use it as the\n // bootstrap distinct ID so the Person record is created from the first event.\n if (this.config.identity_distinct_id && !config.bootstrap?.distinctID) {\n config.bootstrap = {\n ...config.bootstrap,\n distinctID: this.config.identity_distinct_id,\n isIdentifiedID: true,\n }\n }\n\n // isUndefined doesn't provide typehint here so wouldn't reduce bundle as we'd need to assign\n // eslint-disable-next-line posthog-js/no-direct-undefined-check\n if (config.bootstrap?.distinctID !== undefined) {\n const bootstrapDistinctId = config.bootstrap.distinctID\n const existingDistinctId = this.get_distinct_id()\n const existingUserState = this.persistence.get_property(USER_STATE)\n\n if (\n config.bootstrap.isIdentifiedID &&\n existingDistinctId != null &&\n existingDistinctId !== bootstrapDistinctId &&\n existingUserState === USER_STATE_ANONYMOUS\n ) {\n // The server bootstrapped identity for an identified user, but local persistence\n // still has an anonymous ID from a previous session. Calling identify() merges\n // the anonymous user into the identified user, ensuring consistent identity\n // for feature flag evaluation and preventing duplicate $feature_flag_called events.\n //\n // Note: this runs during _init(), before _loaded() enables the request queue.\n // The $identify event is enqueued and flushed once the queue starts. The\n // reloadFeatureFlags() call inside identify() sets _reloadDebouncer, so the\n // subsequent ensureFlagsLoaded() from _onRemoteConfig is a no-op (no double request).\n this.identify(bootstrapDistinctId)\n } else if (\n config.bootstrap.isIdentifiedID &&\n existingDistinctId != null &&\n existingDistinctId !== bootstrapDistinctId &&\n existingUserState === USER_STATE_IDENTIFIED\n ) {\n // The existing user is already identified with a different ID. Silently\n // switching identities without an $identify event would corrupt analytics.\n // Preserve the existing identity and log a warning.\n logger.warn(\n 'Bootstrap distinctID differs from an already-identified user. ' +\n 'The existing identity is preserved. Call reset() before reinitializing ' +\n 'if you intend to switch users.'\n )\n } else {\n const uuid = this.config.get_device_id(uuidv7())\n const deviceID = config.bootstrap.isIdentifiedID ? uuid : bootstrapDistinctId\n this.persistence.set_property(\n USER_STATE,\n config.bootstrap.isIdentifiedID ? USER_STATE_IDENTIFIED : USER_STATE_ANONYMOUS\n )\n this.register({\n distinct_id: bootstrapDistinctId,\n $device_id: deviceID,\n })\n }\n }\n\n if (startInCookielessMode) {\n this.register_once(\n {\n distinct_id: COOKIELESS_SENTINEL_VALUE,\n $device_id: null,\n },\n ''\n )\n } else if (!this.get_distinct_id()) {\n // There is no need to set the distinct id\n // or the device id if something was already stored\n // in the persistence\n const uuid = this.config.get_device_id(uuidv7())\n\n this.register_once(\n {\n distinct_id: uuid,\n $device_id: uuid,\n },\n ''\n )\n // distinct id == $device_id is a proxy for anonymous user\n this.persistence.set_property(USER_STATE, USER_STATE_ANONYMOUS)\n }\n // Set up event handler for pageleave\n // Use `onpagehide` if available, see https://calendar.perfplanet.com/2020/beaconing-in-practice/#beaconing-reliability-avoiding-abandons\n //\n // Not making it passive to try and force the browser to handle this before the page is unloaded\n addEventListener(window, 'onpagehide' in self ? 'pagehide' : 'unload', this._handle_unload.bind(this), {\n passive: false,\n })\n\n // We want to avoid promises for IE11 compatibility, so we use callbacks here\n if (config.segment) {\n setupSegmentIntegration(this, () => this._loaded())\n } else {\n this._loaded()\n }\n\n if (isFunction(this.config._onCapture) && this.config._onCapture !== __NOOP) {\n logger.warn('onCapture is deprecated. Please use `before_send` instead')\n this.on('eventCaptured', (data) => this.config._onCapture(data.event, data))\n }\n\n if (this.config.ip) {\n logger.warn(\n 'The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or \"Discard IP data\" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'\n )\n }\n\n return this\n }\n\n private _initExtensions(startInCookielessMode: boolean): void {\n // we don't support IE11 anymore, so performance.now is safe\n // eslint-disable-next-line compat/compat\n const initStartTime = performance.now()\n const ext = { ...PostHog.__defaultExtensionClasses, ...this.config.__extensionClasses }\n const initTasks: Array<() => void> = []\n\n // Due to name mangling, we can't easily iterate and assign these extensions\n // The assignment needs to also be mangled. Thus, the loop is unrolled.\n if (ext.featureFlags) {\n this._extensions.push((this.featureFlags = this.featureFlags ?? new ext.featureFlags(this)))\n }\n if (ext.exceptions) {\n this._extensions.push((this.exceptions = this.exceptions ?? new ext.exceptions(this)))\n }\n if (ext.historyAutocapture) {\n this._extensions.push((this.historyAutocapture = new ext.historyAutocapture(this)))\n }\n if (ext.tracingHeaders) {\n this._extensions.push(new ext.tracingHeaders(this))\n }\n if (ext.siteApps) {\n this._extensions.push((this.siteApps = new ext.siteApps(this)))\n }\n if (ext.sessionRecording && !startInCookielessMode) {\n this._extensions.push((this.sessionRecording = new ext.sessionRecording(this)))\n }\n if (!this.config.disable_scroll_properties) {\n initTasks.push(() => {\n this.scrollManager.startMeasuringScrollPosition()\n })\n }\n if (ext.autocapture) {\n this._extensions.push((this.autocapture = new ext.autocapture(this)))\n }\n if (ext.surveys) {\n this._extensions.push((this.surveys = this.surveys ?? new ext.surveys(this)))\n }\n if (ext.logs) {\n this._extensions.push((this.logs = this.logs ?? new ext.logs(this)))\n }\n if (ext.conversations) {\n this._extensions.push((this.conversations = this.conversations ?? new ext.conversations(this)))\n }\n if (ext.productTours) {\n this._extensions.push((this.productTours = new ext.productTours(this)))\n }\n if (ext.heatmaps) {\n this._extensions.push((this.heatmaps = new ext.heatmaps(this)))\n }\n if (ext.webVitalsAutocapture) {\n this._extensions.push((this.webVitalsAutocapture = new ext.webVitalsAutocapture(this)))\n }\n if (ext.exceptionObserver) {\n this._extensions.push((this.exceptionObserver = new ext.exceptionObserver(this)))\n }\n if (ext.deadClicksAutocapture) {\n this._extensions.push(\n (this.deadClicksAutocapture = new ext.deadClicksAutocapture(this, isDeadClicksEnabledForAutocapture))\n )\n }\n if (ext.toolbar) {\n this._extensions.push((this.toolbar = this.toolbar ?? new ext.toolbar(this)))\n }\n if (ext.experiments) {\n this._extensions.push((this.experiments = this.experiments ?? new ext.experiments(this)))\n }\n\n this._extensions.forEach((extension) => {\n if (!extension.initialize) return\n initTasks.push(() => {\n extension.initialize?.()\n })\n })\n\n // Replay any pending remote config that arrived before extensions were ready\n initTasks.push(() => {\n if (this._pendingRemoteConfig) {\n const config = this._pendingRemoteConfig\n this._pendingRemoteConfig = undefined // Clear before replaying to avoid re-storing\n this._onRemoteConfig(config)\n }\n })\n\n // Process tasks with time-slicing to avoid blocking\n this._processInitTaskQueue(initTasks, initStartTime)\n }\n\n private _processInitTaskQueue(queue: Array<() => void>, initStartTime: number): void {\n const TIME_BUDGET_MS = 30 // Respect frame budget (~60fps = 16ms, but we're already deferred)\n\n while (queue.length > 0) {\n // Only time-slice if deferred init is enabled, otherwise run synchronously\n if (this.config.__preview_deferred_init_extensions) {\n // we don't support IE11 anymore, so performance.now is safe\n // eslint-disable-next-line compat/compat\n const elapsed = performance.now() - initStartTime\n\n // Check if we've exceeded our time budget\n if (elapsed >= TIME_BUDGET_MS && queue.length > 0) {\n // Yield to browser, then continue processing\n setTimeout(() => {\n this._processInitTaskQueue(queue, initStartTime)\n }, 0)\n return\n }\n }\n\n // Process next task\n const task = queue.shift()\n if (task) {\n try {\n task()\n } catch (error) {\n logger.error('Error initializing extension:', error)\n }\n }\n }\n\n // All tasks complete - record timing for both sync and deferred modes\n // we don't support IE11 anymore, so performance.now is safe\n // eslint-disable-next-line compat/compat\n const taskInitTiming = Math.round(performance.now() - initStartTime)\n this.register_for_session({\n $sdk_debug_extensions_init_method: this.config.__preview_deferred_init_extensions\n ? 'deferred'\n : 'synchronous',\n $sdk_debug_extensions_init_time_ms: taskInitTiming,\n })\n if (this.config.__preview_deferred_init_extensions) {\n logger.info(`PostHog extensions initialized (${taskInitTiming}ms)`)\n }\n }\n\n _onRemoteConfig(config: RemoteConfig) {\n if (!(document && document.body)) {\n logger.info('document not ready yet, trying again in 500 milliseconds...')\n setTimeout(() => {\n this._onRemoteConfig(config)\n }, 500)\n return\n }\n\n // Store config in case extensions aren't initialized yet (only needed for deferred init)\n if (this.config.__preview_deferred_init_extensions) {\n this._pendingRemoteConfig = config\n }\n\n this.compression = undefined\n if (config.supportedCompression && !this.config.disable_compression) {\n this.compression = includes(config['supportedCompression'], Compression.GZipJS)\n ? Compression.GZipJS\n : includes(config['supportedCompression'], Compression.Base64)\n ? Compression.Base64\n : undefined\n }\n\n if (config.analytics?.endpoint) {\n this.analyticsDefaultEndpoint = config.analytics.endpoint\n }\n\n this.set_config({\n person_profiles: this._initialPersonProfilesConfig\n ? this._initialPersonProfilesConfig\n : PERSON_PROFILES_IDENTIFIED_ONLY,\n })\n\n this._extensions.forEach((ext) => ext.onRemoteConfig?.(config))\n }\n\n _loaded(): void {\n try {\n this.config.loaded(this)\n } catch (err) {\n logger.critical('`loaded` function failed', err)\n }\n\n this._start_queue_if_opted_in()\n\n // Check if current hostname matches internal_or_test_user_hostname pattern and mark as test user before any events\n if (this.config.internal_or_test_user_hostname && location?.hostname) {\n const hostname = location.hostname\n const pattern = this.config.internal_or_test_user_hostname\n const matches = typeof pattern === 'string' ? hostname === pattern : pattern.test(hostname)\n if (matches) {\n this.setInternalOrTestUser()\n }\n }\n\n // this happens after \"loaded\" so a user can call identify or any other things before the pageview fires\n if (this.config.capture_pageview) {\n // NOTE: We want to fire this on the next tick as the previous implementation had this side effect\n // and some clients may rely on it\n setTimeout(() => {\n if (this.consent.isOptedIn() || this.config.cookieless_mode === COOKIELESS_ALWAYS) {\n this._captureInitialPageview()\n }\n }, 1)\n }\n\n this._remoteConfigLoader = new RemoteConfigLoader(this)\n this._remoteConfigLoader.load()\n }\n\n _start_queue_if_opted_in(): void {\n if (this.is_capturing()) {\n if (this.config.request_batching) {\n this._requestQueue?.enable()\n }\n }\n }\n\n _dom_loaded(): void {\n if (this.is_capturing()) {\n eachArray(this.__request_queue, (item) => this._send_retriable_request(item))\n }\n\n this.__request_queue = []\n this._start_queue_if_opted_in()\n }\n\n _handle_unload(): void {\n this.surveys?.handlePageUnload()\n\n if (!this.config.request_batching) {\n if (this._shouldCapturePageleave()) {\n this.capture(EVENT_PAGELEAVE, null, { transport: 'sendBeacon' })\n }\n return\n }\n\n if (this._shouldCapturePageleave()) {\n this.capture(EVENT_PAGELEAVE)\n }\n\n this.logs?.flushLogs('sendBeacon')\n this._requestQueue?.unload()\n this._retryQueue?.unload()\n }\n\n _send_request(options: QueuedRequestWithOptions): void {\n if (!this.__loaded) {\n return\n }\n\n if (ENQUEUE_REQUESTS) {\n this.__request_queue.push(options)\n return\n }\n\n if (this.rateLimiter.isServerRateLimited(options.batchKey)) {\n return\n }\n\n options.transport = options.transport || this.config.api_transport\n options.url = extendURLParams(options.url, {\n // Whether to detect ip info or not\n ip: this.config.ip ? 1 : 0,\n })\n options.headers = {\n ...this.config.request_headers,\n ...options.headers,\n }\n options.compression = options.compression === 'best-available' ? this.compression : options.compression\n options.disableXHRCredentials = this.config.__preview_disable_xhr_credentials\n if (this.config.__preview_disable_beacon) {\n options.disableTransport = ['sendBeacon']\n }\n\n // Specially useful if you're doing SSR with NextJS\n // Users must be careful when tweaking `cache` because they might get out-of-date feature flags\n options.fetchOptions = options.fetchOptions || this.config.fetch_options\n\n request({\n ...options,\n callback: (response) => {\n this.rateLimiter.checkForLimiting(response)\n\n if (response.statusCode >= 400) {\n this.config.on_request_error?.(response)\n }\n\n options.callback?.(response)\n },\n })\n }\n\n _send_retriable_request(options: QueuedRequestWithOptions): void {\n if (this._retryQueue) {\n this._retryQueue.retriableRequest(options)\n } else {\n this._send_request(options)\n }\n }\n\n /**\n * _execute_array() deals with processing any posthog function\n * calls that were called before the PostHog library were loaded\n * (and are thus stored in an array so they can be called later)\n *\n * Note: we fire off all the posthog function calls && user defined\n * functions BEFORE we fire off posthog capturing calls. This is so\n * identify/register/set_config calls can properly modify early\n * capturing calls.\n *\n * @param {Array} array\n */\n _execute_array(array: SnippetArrayItem[]): void {\n _executeArrayDepth++\n try {\n let fn_name\n const alias_calls: SnippetArrayItem[] = []\n const other_calls: SnippetArrayItem[] = []\n const capturing_calls: SnippetArrayItem[] = []\n eachArray(array, (item) => {\n if (item) {\n fn_name = item[0]\n if (isArray(fn_name)) {\n capturing_calls.push(item) // chained call e.g. posthog.get_group().set()\n } else if (isFunction(item)) {\n ;(item as any).call(this)\n } else if (isArray(item) && fn_name === 'alias') {\n alias_calls.push(item)\n } else if (\n isArray(item) &&\n fn_name.indexOf('capture') !== -1 &&\n isFunction((this as any)[fn_name])\n ) {\n capturing_calls.push(item)\n } else {\n other_calls.push(item)\n }\n }\n })\n\n const execute = function (calls: SnippetArrayItem[], thisArg: any) {\n eachArray(calls, function (item) {\n if (isArray(item[0])) {\n // chained call\n let caller = thisArg\n each(item, function (call) {\n caller = caller[call[0]].apply(caller, call.slice(1))\n })\n } else {\n thisArg[item[0]].apply(thisArg, item.slice(1))\n }\n })\n }\n\n execute(alias_calls, this)\n execute(other_calls, this)\n execute(capturing_calls, this)\n } finally {\n _executeArrayDepth--\n }\n }\n\n /**\n * push() keeps the standard async-array-push\n * behavior around after the lib is loaded.\n * This is only useful for external integrations that\n * do not wish to rely on our convenience methods\n * (created in the snippet).\n *\n * @example\n * ```js\n * posthog.push(['register', { a: 'b' }]);\n * ```\n *\n * @param {Array} item A [function_name, args...] array to be executed\n */\n push(item: SnippetArrayItem): void {\n if (_executeArrayDepth > 0 && isArray(item) && isString(item[0])) {\n // push() is being called while _execute_array is already running.\n // This happens when a third-party Proxy (e.g., TikTok's in-app browser)\n // wraps window.posthog and converts method calls into push() calls,\n // creating an infinite loop: _execute_array -> this[method] -> Proxy ->\n // push -> _execute_array -> ...\n // Dispatch directly from the prototype to break the cycle.\n const fn = (PostHog.prototype as any)[item[0]]\n if (isFunction(fn)) {\n fn.apply(this, item.slice(1))\n }\n return\n }\n this._execute_array([item])\n }\n\n /**\n * Captures an event with optional properties and configuration.\n *\n * @remarks\n * You can capture arbitrary object-like values as events. [Learn about capture best practices](/docs/product-analytics/capture-events)\n *\n * @example\n * ```js\n * // basic event capture\n * posthog.capture('cta-button-clicked', {\n * button_name: 'Get Started',\n * page: 'homepage'\n * })\n * ```\n *\n * {@label Capture}\n *\n * @public\n *\n * @param event_name - The name of the event (e.g., 'Sign Up', 'Button Click', 'Purchase')\n * @param properties - Properties to include with the event describing the user or event details\n * @param options - Optional configuration for the capture request\n *\n * @returns The capture result containing event data, or undefined if capture failed\n */\n capture(\n event_name: EventName,\n properties?: Properties | null,\n options?: CaptureOptions\n ): CaptureResult | undefined {\n // While developing, a developer might purposefully _not_ call init(),\n // in this case, we would like capture to be a noop.\n if (!this.__loaded || !this.persistence || !this.sessionPersistence || !this._requestQueue) {\n logger.uninitializedWarning('posthog.capture')\n return\n }\n\n if (!this.is_capturing()) {\n return\n }\n\n // typing doesn't prevent interesting data\n if (isUndefined(event_name) || !isString(event_name)) {\n logger.error('No event name provided to posthog.capture')\n return\n }\n\n const isBot = !this.config.opt_out_useragent_filter && this._is_bot()\n const shouldDropBotEvent = isBot && !this.config.__preview_capture_bot_pageviews\n\n // We drop bot events unless the preview flag to send bot pageviews is enabled\n // or the user has explicitly opted out of useragent filtering\n if (shouldDropBotEvent) {\n return\n }\n\n const clientRateLimitContext = !options?.skip_client_rate_limiting\n ? this.rateLimiter.clientRateLimitContext()\n : undefined\n\n if (clientRateLimitContext?.isRateLimited) {\n logger.critical('This capture call is ignored due to client rate limiting.')\n return\n }\n\n if (properties?.$current_url && !isString(properties?.$current_url)) {\n logger.error(\n 'Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value.'\n )\n delete properties?.$current_url\n }\n\n if (event_name === '$exception' && !options?._originatedFromCaptureException) {\n logger.warn(\n \"Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically.\"\n )\n }\n\n // update persistence\n this.sessionPersistence.update_search_keyword()\n\n // The initial campaign/referrer props need to be stored in the regular persistence, as they are there to mimic\n // the person-initial props. The non-initial versions are stored in the sessionPersistence, as they are sent\n // with every event and used by the session table to create session-initial props.\n if (this.config.save_campaign_params) {\n this.sessionPersistence.update_campaign_params()\n }\n if (this.config.save_referrer) {\n this.sessionPersistence.update_referrer_info()\n }\n\n if (this.config.save_campaign_params || this.config.save_referrer) {\n this.persistence.set_initial_person_info()\n }\n\n const systemTime = new Date()\n const timestamp = options?.timestamp || systemTime\n\n const uuid = uuidv7()\n let data: CaptureResult = {\n uuid,\n event: event_name,\n properties: this.calculateEventProperties(event_name, properties || {}, timestamp, uuid),\n }\n\n // Route pageviews to $bot_pageview when bot detected and preview flag enabled\n if (event_name === EVENT_PAGEVIEW && this.config.__preview_capture_bot_pageviews && isBot) {\n data.event = '$bot_pageview'\n // While it's obvious that a $bot_pageview is (likely) from a bot, we explicitly set $browser_type\n // to make it easy to filter and test bot pageviews in the product\n data.properties.$browser_type = 'bot'\n }\n\n if (clientRateLimitContext) {\n data.properties['$lib_rate_limit_remaining_tokens'] = clientRateLimitContext.remainingTokens\n }\n\n const setProperties = options?.$set\n if (setProperties) {\n data.$set = options?.$set\n }\n // $groupidentify doesn't process person $set_once on the server, so don't mark\n // initial person props as sent. This ensures they're included with subsequent\n // $identify calls.\n const markSetOnceAsSent = event_name !== EVENT_GROUPIDENTIFY\n // $identify should always include initial props because it creates/merges persons\n // and may be processed before earlier anonymous events on the server\n const forceIncludeInitialProps = event_name === EVENT_IDENTIFY\n const setOnceProperties = this._calculate_set_once_properties(\n options?.$set_once,\n markSetOnceAsSent,\n forceIncludeInitialProps\n )\n if (setOnceProperties) {\n data.$set_once = setOnceProperties\n }\n\n if (!options?._noTruncate) {\n data = _copyAndTruncateStrings(data, this.config.properties_string_max_length)\n }\n data.timestamp = timestamp\n if (!isUndefined(options?.timestamp)) {\n data.properties['$event_time_override_provided'] = true\n data.properties['$event_time_override_system_time'] = systemTime\n }\n\n if (event_name === SurveyEventName.DISMISSED || event_name === SurveyEventName.SENT) {\n const surveyId = properties?.[SurveyEventProperties.SURVEY_ID]\n const surveyIteration = properties?.[SurveyEventProperties.SURVEY_ITERATION]\n setSurveySeenOnLocalStorage({ id: surveyId, current_iteration: surveyIteration })\n data.$set = {\n ...data.$set,\n [getSurveyInteractionProperty(\n { id: surveyId, current_iteration: surveyIteration },\n event_name === SurveyEventName.SENT ? 'responded' : 'dismissed'\n )]: true,\n }\n } else if (event_name === SurveyEventName.SHOWN) {\n data.$set = {\n ...data.$set,\n [SurveyEventProperties.SURVEY_LAST_SEEN_DATE]: new Date().toISOString(),\n }\n }\n\n if (event_name === ProductTourEventName.SHOWN) {\n const tourType = properties?.[ProductTourEventProperties.TOUR_TYPE]\n if (tourType) {\n data.$set = {\n ...data.$set,\n [`${ProductTourEventProperties.TOUR_LAST_SEEN_DATE}/${tourType}`]: new Date().toISOString(),\n }\n }\n }\n\n // Top-level $set overriding values from the one from properties is taken from the plugin-server normalizeEvent\n // This doesn't handle $set_once, because posthog-people doesn't either\n const finalSet = { ...data.properties['$set'], ...data['$set'] }\n if (!isEmptyObject(finalSet)) {\n this.setPersonPropertiesForFlags(finalSet)\n }\n\n if (!isNullish(this.config.before_send)) {\n const beforeSendResult = this._runBeforeSend(data)\n if (!beforeSendResult) {\n return\n } else {\n data = beforeSendResult\n }\n }\n\n this._internalEventEmitter.emit('eventCaptured', data)\n\n const requestOptions: QueuedRequestWithOptions = {\n method: 'POST',\n url: options?._url ?? this.requestRouter.endpointFor('api', this.analyticsDefaultEndpoint),\n data,\n compression: 'best-available',\n batchKey: options?._batchKey,\n }\n\n if (this.config.request_batching && (!options || options?._batchKey) && !options?.send_instantly) {\n this._requestQueue.enqueue(requestOptions)\n } else {\n this._send_retriable_request(requestOptions)\n }\n\n return data\n }\n\n _addCaptureHook(callback: (eventName: string, eventPayload?: CaptureResult) => void): () => void {\n return this.on('eventCaptured', (data) => callback(data.event, data))\n }\n\n /**\n * This method is used internally to calculate the event properties before sending it to PostHog. It can also be\n * used by integrations (e.g. Segment) to enrich events with PostHog properties before sending them to Segment,\n * which is required for some PostHog products to work correctly. (e.g. to have a correct $session_id property).\n *\n * @param {String} eventName The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', '$pageview', etc.\n * @param {Object} eventProperties The properties to include with the event.\n * @param {Date} [timestamp] The timestamp of the event, e.g. for calculating time on page. If not set, it'll automatically be set to the current time.\n * @param {String} [uuid] The uuid of the event, e.g. for storing the $pageview ID.\n * @param {Boolean} [readOnly] Set this if you do not intend to actually send the event, and therefore do not want to update internal state e.g. session timeout\n *\n * @internal\n */\n public calculateEventProperties(\n eventName: string,\n eventProperties: Properties,\n timestamp?: Date,\n uuid?: string,\n readOnly?: boolean\n ): Properties {\n timestamp = timestamp || new Date()\n if (!this.persistence || !this.sessionPersistence) {\n return eventProperties\n }\n\n // set defaults\n const startTimestamp = readOnly ? undefined : this.persistence.remove_event_timer(eventName)\n let properties = { ...eventProperties }\n properties['token'] = this.config.token\n properties['$config_defaults'] = this.config.defaults\n\n if (\n this.config.cookieless_mode == COOKIELESS_ALWAYS ||\n (this.config.cookieless_mode == COOKIELESS_ON_REJECT && this.consent.isExplicitlyOptedOut())\n ) {\n // Set a flag to tell the plugin server to use cookieless server hash mode\n properties[COOKIELESS_MODE_FLAG_PROPERTY] = true\n }\n\n if (eventName === '$snapshot') {\n const persistenceProps = { ...this.persistence.properties(), ...this.sessionPersistence.properties() }\n properties['distinct_id'] = persistenceProps.distinct_id\n if (\n // we spotted one customer that was managing to send `false` for ~9k events a day\n !(isString(properties['distinct_id']) || isNumber(properties['distinct_id'])) ||\n isEmptyString(properties['distinct_id'])\n ) {\n logger.error('Invalid distinct_id for replay event. This indicates a bug in your implementation')\n }\n return properties\n }\n\n const infoProperties = getEventProperties(\n this.config.mask_personal_data_properties,\n this.config.custom_personal_data_properties\n )\n\n if (this.sessionManager) {\n const { sessionId, windowId } = this.sessionManager.checkAndGetSessionAndWindowId(\n readOnly,\n timestamp.getTime()\n )\n properties['$session_id'] = sessionId\n properties['$window_id'] = windowId\n }\n if (this.sessionPropsManager) {\n extend(properties, this.sessionPropsManager.getSessionProps())\n }\n\n try {\n if (this.sessionRecording) {\n extend(properties, this.sessionRecording.sdkDebugProperties)\n }\n properties['$sdk_debug_retry_queue_size'] = this._retryQueue?.length\n } catch (e: any) {\n properties['$sdk_debug_error_capturing_properties'] = String(e)\n }\n\n if (this.requestRouter.region === RequestRouterRegion.CUSTOM) {\n properties['$lib_custom_api_host'] = this.config.api_host\n }\n\n let pageviewProperties: Record\n if (eventName === EVENT_PAGEVIEW && !readOnly) {\n pageviewProperties = this.pageViewManager.doPageView(timestamp, uuid)\n } else if (eventName === EVENT_PAGELEAVE && !readOnly) {\n pageviewProperties = this.pageViewManager.doPageLeave(timestamp)\n } else {\n pageviewProperties = this.pageViewManager.doEvent()\n }\n properties = extend(properties, pageviewProperties)\n\n if (eventName === EVENT_PAGEVIEW && document) {\n properties['title'] = document.title\n }\n\n // set $duration if time_event was previously called for this event\n if (!isUndefined(startTimestamp)) {\n const duration_in_ms = timestamp.getTime() - startTimestamp\n properties['$duration'] = parseFloat((duration_in_ms / 1000).toFixed(3))\n }\n\n // this is only added when this.config.opt_out_useragent_filter is true,\n // or it would always add \"browser\"\n if (userAgent && this.config.opt_out_useragent_filter) {\n properties['$browser_type'] = this._is_bot() ? 'bot' : 'browser'\n }\n\n // note: extend writes to the first object, so lets make sure we\n // don't write to the persistence properties object and info\n // properties object by passing in a new object\n\n // update properties with pageview info and super-properties\n properties = extend(\n {},\n infoProperties,\n this.persistence.properties(),\n this.sessionPersistence.properties(),\n properties\n )\n\n properties['$is_identified'] = this._isIdentified()\n\n if (isArray(this.config.property_denylist)) {\n each(this.config.property_denylist, function (denylisted_prop) {\n delete properties[denylisted_prop]\n })\n } else {\n logger.error(\n DENYLIST_INVALID +\n this.config.property_denylist +\n ' or property_blacklist config: ' +\n this.config.property_blacklist\n )\n }\n\n const sanitize_properties = this.config.sanitize_properties\n if (sanitize_properties) {\n logger.error(SANITIZE_DEPRECATED)\n properties = sanitize_properties(properties, eventName)\n }\n\n // add person processing flag as very last step, so it cannot be overridden\n const hasPersonProcessing = this._hasPersonProcessing()\n properties['$process_person_profile'] = hasPersonProcessing\n // if the event has person processing, ensure that all future events will too, even if the setting changes\n if (hasPersonProcessing && !readOnly) {\n this._requirePersonProcessing('_calculate_event_properties')\n }\n\n return properties\n }\n\n /** @deprecated - deprecated in 1.241.0, use `calculateEventProperties` instead */\n _calculate_event_properties = this.calculateEventProperties.bind(this)\n\n /**\n * Add additional set_once properties to the event when creating a person profile. This allows us to create the\n * profile with mostly-accurate properties, despite earlier events not setting them. We do this by storing them in\n * persistence.\n * @param dataSetOnce\n * @param markAsSent - if true, marks the properties as sent so they won't be included in future events.\n * Set to false for events like $groupidentify where the server doesn't process person props.\n * @param forceIncludeInitialProps - if true, include initial person props even if they've already been sent.\n * Used for $identify which creates/merges persons and may be processed out of order.\n */\n _calculate_set_once_properties(\n dataSetOnce?: Properties,\n markAsSent: boolean = true,\n forceIncludeInitialProps: boolean = false\n ): Properties | undefined {\n if (!this.persistence || !this._hasPersonProcessing()) {\n return dataSetOnce\n }\n\n if (this._personProcessingSetOncePropertiesSent && !forceIncludeInitialProps) {\n // We only need to send these properties once. Sending them with later events would be redundant and would\n // just require extra work on the server to process them.\n return dataSetOnce\n }\n // if we're an identified person, send initial params with every event\n const initialProps = this.persistence.get_initial_props()\n const sessionProps = this.sessionPropsManager?.getSetOnceProps()\n let setOnceProperties = extend({}, initialProps, sessionProps || {}, dataSetOnce || {})\n const sanitize_properties = this.config.sanitize_properties\n if (sanitize_properties) {\n logger.error(SANITIZE_DEPRECATED)\n setOnceProperties = sanitize_properties(setOnceProperties, '$set_once')\n }\n if (markAsSent) {\n this._personProcessingSetOncePropertiesSent = true\n }\n if (isEmptyObject(setOnceProperties)) {\n return undefined\n }\n return setOnceProperties\n }\n\n /**\n * Registers super properties that are included with all events.\n *\n * @remarks\n * Super properties are stored in persistence and automatically added to every event you capture.\n * These values will overwrite any existing super properties with the same keys.\n *\n * @example\n * ```js\n * // register a single property\n * posthog.register({ plan: 'premium' })\n * ```\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * // register multiple properties\n * posthog.register({\n * email: 'user@example.com',\n * account_type: 'business',\n * signup_date: '2023-01-15'\n * })\n * ```\n *\n * @example\n * ```js\n * // register with custom expiration\n * posthog.register({ campaign: 'summer_sale' }, 7) // expires in 7 days\n * ```\n *\n * @public\n *\n * @param {Object} properties properties to store about the user\n * @param {Number} [days] How many days since the user's last visit to store the super properties\n */\n register(properties: Properties, days?: number): void {\n this.persistence?.register(properties, days)\n }\n\n /**\n * Registers super properties only if they haven't been set before.\n *\n * @remarks\n * Unlike `register()`, this method will not overwrite existing super properties.\n * Use this for properties that should only be set once, like signup date or initial referrer.\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * // register once-only properties\n * posthog.register_once({\n * first_login_date: new Date().toISOString(),\n * initial_referrer: document.referrer\n * })\n * ```\n *\n * @example\n * ```js\n * // override existing value if it matches default\n * posthog.register_once(\n * { user_type: 'premium' },\n * 'unknown' // overwrite if current value is 'unknown'\n * )\n * ```\n *\n * @public\n *\n * @param {Object} properties An associative array of properties to store about the user\n * @param {*} [default_value] Value to override if already set in super properties (ex: 'False') Default: 'None'\n * @param {Number} [days] How many days since the users last visit to store the super properties\n */\n register_once(properties: Properties, default_value?: Property, days?: number): void {\n this.persistence?.register_once(properties, default_value, days)\n }\n\n /**\n * Registers super properties for the current session only.\n *\n * @remarks\n * Session super properties are automatically added to all events during the current browser session.\n * Unlike regular super properties, these are cleared when the session ends and are stored in sessionStorage.\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * // register session-specific properties\n * posthog.register_for_session({\n * current_page_type: 'checkout',\n * ab_test_variant: 'control'\n * })\n * ```\n *\n * @example\n * ```js\n * // register properties for user flow tracking\n * posthog.register_for_session({\n * selected_plan: 'pro',\n * completed_steps: 3,\n * flow_id: 'signup_flow_v2'\n * })\n * ```\n *\n * @public\n *\n * @param {Object} properties An associative array of properties to store about the user\n */\n register_for_session(properties: Properties): void {\n this.sessionPersistence?.register(properties)\n }\n\n /**\n * Removes a super property from persistent storage.\n *\n * @remarks\n * This will stop the property from being automatically included in future events.\n * The property will be permanently removed from the user's profile.\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * // remove a super property\n * posthog.unregister('plan_type')\n * ```\n *\n * @public\n *\n * @param {String} property The name of the super property to remove\n */\n unregister(property: string): void {\n this.persistence?.unregister(property)\n }\n\n /**\n * Removes a session super property from the current session.\n *\n * @remarks\n * This will stop the property from being automatically included in future events for this session.\n * The property is removed from sessionStorage.\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * // remove a session property\n * posthog.unregister_for_session('current_flow')\n * ```\n *\n * @public\n *\n * @param {String} property The name of the session super property to remove\n */\n unregister_for_session(property: string): void {\n this.sessionPersistence?.unregister(property)\n }\n\n _register_single(prop: string, value: Property) {\n this.register({ [prop]: value })\n }\n\n /**\n * Gets the value of a feature flag for the current user.\n *\n * @remarks\n * Returns the feature flag value which can be a boolean, string, or undefined.\n * Supports multivariate flags that can return custom string values.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // check boolean flag\n * if (posthog.getFeatureFlag('new-feature')) {\n * // show new feature\n * }\n * ```\n *\n * @example\n * ```js\n * // check multivariate flag\n * const variant = posthog.getFeatureFlag('button-color')\n * if (variant === 'red') {\n * // show red button\n * }\n * ```\n *\n * @public\n *\n * @param {Object|String} prop Key of the feature flag.\n * @param {Object|String} options (optional) If {send_event: false}, we won't send an $feature_flag_call event to PostHog.\n * If {fresh: true}, we won't return cached values from localStorage - only values loaded from the server.\n */\n getFeatureFlag(key: string, options?: FeatureFlagOptions): boolean | string | undefined {\n return this.featureFlags?.getFeatureFlag(key, options)\n }\n\n /**\n * Get feature flag payload value matching key for user (supports multivariate flags).\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * if(posthog.getFeatureFlag('beta-feature') === 'some-value') {\n * const someValue = posthog.getFeatureFlagPayload('beta-feature')\n * // do something\n * }\n * ```\n *\n * @public\n *\n * @deprecated Use `getFeatureFlagResult()` instead\n *\n * @param {Object|String} prop Key of the feature flag.\n */\n getFeatureFlagPayload(key: string): JsonType {\n return this.featureFlags?.getFeatureFlagPayload(key)\n }\n\n /**\n * Get a feature flag evaluation result including both the flag value and payload.\n *\n * By default, this method emits the `$feature_flag_called` event.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * const result = posthog.getFeatureFlagResult('my-flag')\n * if (result?.enabled) {\n * console.log('Flag is enabled with payload:', result.payload)\n * }\n * ```\n *\n * @example\n * ```js\n * // multivariate flag\n * const result = posthog.getFeatureFlagResult('button-color')\n * if (result?.variant === 'red') {\n * showRedButton(result.payload)\n * }\n * ```\n *\n * @public\n *\n * @param {string} key Key of the feature flag.\n * @param {Object} [options] Options for the feature flag lookup.\n * @param {boolean} [options.send_event=true] If false, won't send the $feature_flag_called event.\n * @param {boolean} [options.fresh=false] If true, won't return cached values from localStorage - only values loaded from the server.\n * @returns {FeatureFlagResult | undefined} The feature flag result including key, enabled, variant, and payload.\n */\n getFeatureFlagResult(key: string, options?: FeatureFlagOptions): FeatureFlagResult | undefined {\n return this.featureFlags?.getFeatureFlagResult(key, options)\n }\n\n /**\n * Checks if a feature flag is enabled for the current user.\n *\n * @remarks\n * Returns true if the flag is enabled, false if disabled, or undefined if not found.\n * This is a convenience method that treats any truthy value as enabled.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // simple feature flag check\n * if (posthog.isFeatureEnabled('new-checkout')) {\n * showNewCheckout()\n * }\n * ```\n *\n * @example\n * ```js\n * // disable event tracking\n * if (posthog.isFeatureEnabled('feature', { send_event: false })) {\n * // flag checked without sending $feature_flag_call event\n * }\n * ```\n *\n * @public\n *\n * @param {Object|String} prop Key of the feature flag.\n * @param {Object|String} options (optional) If {send_event: false}, we won't send an $feature_flag_call event to PostHog.\n * If {fresh: true}, we won't return cached values from localStorage - only values loaded from the server.\n */\n isFeatureEnabled(key: string, options?: FeatureFlagOptions): boolean | undefined {\n return this.featureFlags?.isFeatureEnabled(key, options)\n }\n\n /**\n * Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call this method.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * posthog.reloadFeatureFlags()\n * ```\n *\n * @public\n */\n reloadFeatureFlags(): void {\n this.featureFlags?.reloadFeatureFlags()\n }\n\n /**\n * Manually update feature flag values without making a network request.\n *\n * This is useful when you have feature flag values from an external source\n * (e.g., server-side evaluation, edge middleware) and want to inject them\n * into the client SDK.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // Replace all flags with server-evaluated values\n * posthog.updateFlags({\n * 'my-flag': true,\n * 'my-experiment': 'variant-a'\n * })\n *\n * // Merge with existing flags (update only specified flags)\n * posthog.updateFlags(\n * { 'my-flag': true },\n * undefined,\n * { merge: true }\n * )\n *\n * // With payloads\n * posthog.updateFlags(\n * { 'my-flag': true },\n * { 'my-flag': { some: 'data' } }\n * )\n * ```\n *\n * @param flags - An object mapping flag keys to their values (boolean or string variant)\n * @param payloads - Optional object mapping flag keys to their JSON payloads\n * @param options - Optional settings. Use `{ merge: true }` to merge with existing flags instead of replacing.\n * @public\n */\n updateFlags(\n flags: Record,\n payloads?: Record,\n options?: { merge?: boolean }\n ): void {\n this.featureFlags?.updateFlags(flags, payloads, options)\n }\n\n /**\n * Opt the user in or out of an early access feature. [Learn more in the docs](/docs/feature-flags/early-access-feature-management#option-2-custom-implementation)\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * const toggleBeta = (betaKey) => {\n * if (activeBetas.some(\n * beta => beta.flagKey === betaKey\n * )) {\n * posthog.updateEarlyAccessFeatureEnrollment(\n * betaKey,\n * false\n * )\n * setActiveBetas(\n * prevActiveBetas => prevActiveBetas.filter(\n * item => item.flagKey !== betaKey\n * )\n * );\n * return\n * }\n *\n * posthog.updateEarlyAccessFeatureEnrollment(\n * betaKey,\n * true\n * )\n * setInactiveBetas(\n * prevInactiveBetas => prevInactiveBetas.filter(\n * item => item.flagKey !== betaKey\n * )\n * );\n * }\n *\n * const registerInterest = (featureKey) => {\n * posthog.updateEarlyAccessFeatureEnrollment(\n * featureKey,\n * true\n * )\n * // Update UI to show user has registered\n * }\n * ```\n *\n * @public\n *\n * @param {String} key The key of the feature flag to update.\n * @param {Boolean} isEnrolled Whether the user is enrolled in the feature.\n * @param {String} [stage] The stage of the feature flag to update.\n */\n updateEarlyAccessFeatureEnrollment(key: string, isEnrolled: boolean, stage?: string): void {\n this.featureFlags?.updateEarlyAccessFeatureEnrollment(key, isEnrolled, stage)\n }\n\n /**\n * Get the list of early access features. To check enrollment status, use `isFeatureEnabled`. [Learn more in the docs](/docs/feature-flags/early-access-feature-management#option-2-custom-implementation)\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * const posthog = usePostHog()\n * const activeFlags = useActiveFeatureFlags()\n *\n * const [activeBetas, setActiveBetas] = useState([])\n * const [inactiveBetas, setInactiveBetas] = useState([])\n * const [comingSoonFeatures, setComingSoonFeatures] = useState([])\n *\n * useEffect(() => {\n * posthog.getEarlyAccessFeatures((features) => {\n * // Filter features by stage\n * const betaFeatures = features.filter(feature => feature.stage === 'beta')\n * const conceptFeatures = features.filter(feature => feature.stage === 'concept')\n *\n * setComingSoonFeatures(conceptFeatures)\n *\n * if (!activeFlags || activeFlags.length === 0) {\n * setInactiveBetas(betaFeatures)\n * return\n * }\n *\n * const activeBetas = betaFeatures.filter(\n * beta => activeFlags.includes(beta.flagKey)\n * );\n * const inactiveBetas = betaFeatures.filter(\n * beta => !activeFlags.includes(beta.flagKey)\n * );\n * setActiveBetas(activeBetas)\n * setInactiveBetas(inactiveBetas)\n * }, true, ['concept', 'beta'])\n * }, [activeFlags])\n * ```\n *\n * @public\n *\n * @param {Function} callback The callback function will be called when the early access features are loaded.\n * @param {Boolean} [force_reload] Whether to force a reload of the early access features.\n * @param {String[]} [stages] The stages of the early access features to load.\n */\n getEarlyAccessFeatures(\n callback: EarlyAccessFeatureCallback,\n force_reload = false,\n stages?: EarlyAccessFeatureStage[]\n ): void {\n return this.featureFlags?.getEarlyAccessFeatures(callback, force_reload, stages)\n }\n\n /**\n * Exposes a set of events that PostHog will emit.\n * e.g. `eventCaptured` is emitted immediately before trying to send an event\n *\n * Unlike `onFeatureFlags` and `onSessionId` these are not called when the\n * listener is registered, the first callback will be the next event\n * _after_ registering a listener\n *\n * Available events:\n * - `eventCaptured`: Emitted immediately before trying to send an event\n * - `featureFlagsReloading`: Emitted when feature flags are being reloaded (e.g. after `identify()`, `group()`, or `reloadFeatureFlags()`)\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * posthog.on('eventCaptured', (event) => {\n * console.log(event)\n * })\n * ```\n *\n * @example\n * ```js\n * // Track when feature flags are reloading to show a loading state\n * posthog.on('featureFlagsReloading', () => {\n * console.log('Feature flags are being reloaded...')\n * })\n * ```\n *\n * @public\n *\n * @param {String} event The event to listen for.\n * @param {Function} cb The callback function to call when the event is emitted.\n * @returns {Function} A function that can be called to unsubscribe the listener.\n */\n on(event: 'eventCaptured' | 'featureFlagsReloading', cb: (...args: any[]) => void): () => void {\n return this._internalEventEmitter.on(event, cb)\n }\n\n /**\n * Register an event listener that runs when feature flags become available or when they change.\n * If there are flags, the listener is called immediately in addition to being called on future changes.\n * Note that this is not called only when we fetch feature flags from the server, but also when they change in the browser.\n *\n * {@label Feature flags}\n *\n * @public\n *\n * @example\n * ```js\n * posthog.onFeatureFlags(function(featureFlags, featureFlagsVariants, { errorsLoading }) {\n * // do something\n * })\n * ```\n *\n * @param callback - The callback function will be called once the feature flags are ready or when they are updated.\n * It'll return a list of feature flags enabled for the user, the variants,\n * and also a context object indicating whether we succeeded to fetch the flags or not.\n * @returns A function that can be called to unsubscribe the listener. Used by `useEffect` when the component unmounts.\n */\n onFeatureFlags(callback: FeatureFlagsCallback): () => void {\n if (!this.featureFlags) {\n callback([], {}, { errorsLoading: true })\n return () => {}\n }\n return this.featureFlags.onFeatureFlags(callback)\n }\n\n /**\n * Register an event listener that runs when surveys are loaded.\n *\n * Callback parameters:\n * - surveys: Survey[]: An array containing all survey objects fetched from PostHog using the getSurveys method\n * - context: { isLoaded: boolean, error?: string }: An object indicating if the surveys were loaded successfully\n *\n * {@label Surveys}\n *\n * @example\n * ```js\n * posthog.onSurveysLoaded((surveys, context) => { // do something })\n * ```\n *\n *\n * @param {Function} callback The callback function will be called when surveys are loaded or updated.\n * @returns {Function} A function that can be called to unsubscribe the listener.\n */\n onSurveysLoaded(callback: SurveyCallback): () => void {\n if (!this.surveys) {\n callback([], { isLoaded: false, error: SURVEYS_NOT_AVAILABLE })\n return () => {}\n }\n return this.surveys.onSurveysLoaded(callback)\n }\n\n /**\n * Register an event listener that runs whenever the session id or window id change.\n * If there is already a session id, the listener is called immediately in addition to being called on future changes.\n *\n * Can be used, for example, to sync the PostHog session id with a backend session.\n *\n * {@label Identification}\n *\n * @public\n *\n * @example\n * ```js\n * posthog.onSessionId(function(sessionId, windowId) { // do something })\n * ```\n *\n * @param {Function} [callback] The callback function will be called once a session id is present or when it or the window id are updated.\n * @returns {Function} A function that can be called to unsubscribe the listener. E.g. Used by `useEffect` when the component unmounts.\n */\n onSessionId(callback: SessionIdChangedCallback): () => void {\n return this.sessionManager?.onSessionId(callback) ?? (() => {})\n }\n\n /**\n * Get list of all surveys.\n *\n * {@label Surveys}\n *\n * @example\n * ```js\n * function callback(surveys, context) {\n * // do something\n * }\n *\n * posthog.getSurveys(callback, false)\n * ```\n *\n * @public\n *\n * @param {Function} [callback] Function that receives the array of surveys\n * @param {Boolean} [forceReload] Optional boolean to force an API call for updated surveys\n */\n getSurveys(callback: SurveyCallback, forceReload = false): void {\n this.surveys\n ? this.surveys.getSurveys(callback, forceReload)\n : callback([], { isLoaded: false, error: SURVEYS_NOT_AVAILABLE })\n }\n\n /**\n * Get surveys that should be enabled for the current user. See [fetching surveys documentation](/docs/surveys/implementing-custom-surveys#fetching-surveys-manually) for more details.\n *\n * {@label Surveys}\n *\n * @example\n * ```js\n * posthog.getActiveMatchingSurveys((surveys) => {\n * // do something\n * })\n * ```\n *\n * @public\n *\n * @param {Function} [callback] The callback function will be called when the surveys are loaded or updated.\n * @param {Boolean} [forceReload] Whether to force a reload of the surveys.\n */\n getActiveMatchingSurveys(callback: SurveyCallback, forceReload = false): void {\n this.surveys\n ? this.surveys.getActiveMatchingSurveys(callback, forceReload)\n : callback([], { isLoaded: false, error: SURVEYS_NOT_AVAILABLE })\n }\n\n /**\n * Although we recommend using popover surveys and display conditions,\n * if you want to show surveys programmatically without setting up all\n * the extra logic needed for API surveys, you can render surveys\n * programmatically with the renderSurvey method.\n *\n * This takes a survey ID and an HTML selector to render an unstyled survey.\n *\n * {@label Surveys}\n *\n * @example\n * ```js\n * posthog.renderSurvey(coolSurveyID, '#survey-container')\n * ```\n *\n * @deprecated Use displaySurvey instead - it's more complete and also supports popover surveys.\n *\n * @public\n *\n * @param {String} surveyId The ID of the survey to render.\n * @param {String} selector The selector of the HTML element to render the survey on.\n */\n renderSurvey(surveyId: string, selector: string): void {\n this.surveys?.renderSurvey(surveyId, selector)\n }\n\n /**\n * Display a survey programmatically as either a popover or inline element.\n *\n * @param {string} surveyId - The survey ID to display\n * @param {DisplaySurveyOptions} options - Display configuration\n *\n * @example\n * ```js\n * // Display as popover (respects all conditions defined in the dashboard)\n * posthog.displaySurvey('survey-id-123')\n * ```\n *\n * @example\n * ```js\n * // Display inline in a specific element\n * posthog.displaySurvey('survey-id-123', {\n * displayType: DisplaySurveyType.Inline,\n * selector: '#survey-container'\n * })\n * ```\n *\n * @example\n * ```js\n * // Force display ignoring conditions and delays\n * posthog.displaySurvey('survey-id-123', {\n * displayType: DisplaySurveyType.Popover,\n * ignoreConditions: true,\n * ignoreDelay: true\n * })\n * ```\n *\n * {@label Surveys}\n */\n displaySurvey(surveyId: string, options: DisplaySurveyOptions = DEFAULT_DISPLAY_SURVEY_OPTIONS): void {\n this.surveys?.displaySurvey(surveyId, options)\n }\n\n /**\n * Cancels a pending survey that is waiting to be displayed (e.g., due to a popup delay).\n *\n * {@label Surveys}\n */\n cancelPendingSurvey(surveyId: string): void {\n this.surveys?.cancelPendingSurvey(surveyId)\n }\n\n /**\n * Checks the feature flags associated with this Survey to see if the survey can be rendered.\n * This method is deprecated because it's synchronous and won't return the correct result if surveys are not loaded.\n * Use `canRenderSurveyAsync` instead.\n *\n * {@label Surveys}\n *\n * @public\n * @deprecated\n *\n * @param surveyId The ID of the survey to check.\n * @returns A SurveyRenderReason object indicating if the survey can be rendered.\n */\n canRenderSurvey(surveyId: string): SurveyRenderReason | null {\n return (\n this.surveys?.canRenderSurvey(surveyId) ?? {\n visible: false,\n disabledReason: SURVEYS_NOT_AVAILABLE,\n }\n )\n }\n\n /**\n * Checks the feature flags associated with this Survey to see if the survey can be rendered.\n *\n * {@label Surveys}\n *\n * @example\n * ```js\n * posthog.canRenderSurveyAsync(surveyId).then((result) => {\n * if (result.visible) {\n * // Survey can be rendered\n * console.log('Survey can be rendered')\n * } else {\n * // Survey cannot be rendered\n * console.log('Survey cannot be rendered:', result.disabledReason)\n * }\n * })\n * ```\n *\n * @public\n *\n * @param surveyId The ID of the survey to check.\n * @param forceReload If true, the survey will be reloaded from the server, Default: false\n * @returns A SurveyRenderReason object indicating if the survey can be rendered.\n */\n canRenderSurveyAsync(surveyId: string, forceReload = false): Promise {\n return (\n this.surveys?.canRenderSurveyAsync(surveyId, forceReload) ??\n // eslint-disable-next-line compat/compat\n Promise.resolve({ visible: false, disabledReason: SURVEYS_NOT_AVAILABLE })\n )\n }\n\n private _validateIdentifyId(id: string | undefined): id is string {\n if (!id || isEmptyString(id)) {\n logger.critical('Unique user id has not been set in posthog.identify')\n return false\n }\n if (id === COOKIELESS_SENTINEL_VALUE) {\n logger.critical(\n `The string \"${id}\" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.`\n )\n return false\n }\n if (isDistinctIdStringLike(id) || ['undefined', 'null'].includes(id.toLowerCase())) {\n logger.critical(\n `The string \"${id}\" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.`\n )\n return false\n }\n return true\n }\n\n /**\n * Associates a user with a unique identifier instead of an auto-generated ID.\n * Learn more about [identifying users](/docs/product-analytics/identify)\n *\n * {@label Identification}\n *\n * @remarks\n * By default, PostHog assigns each user a randomly generated `distinct_id`. Use this method to\n * replace that ID with your own unique identifier (like a user ID from your database).\n *\n * @example\n * ```js\n * // basic identification\n * posthog.identify('user_12345')\n * ```\n *\n * @example\n * ```js\n * // identify with user properties\n * posthog.identify('user_12345', {\n * email: 'user@example.com',\n * plan: 'premium'\n * })\n * ```\n *\n * @example\n * ```js\n * // identify with set and set_once properties\n * posthog.identify('user_12345',\n * { last_login: new Date() }, // updates every time\n * { signup_date: new Date() } // sets only once\n * )\n * ```\n *\n * @public\n *\n * @param {String} [new_distinct_id] A string that uniquely identifies a user. If not provided, the distinct_id currently in the persistent store (cookie or localStorage) will be used.\n * @param {Object} [userPropertiesToSet] Optional: An associative array of properties to store about the user. Note: For feature flag evaluations, if the same key is present in the userPropertiesToSetOnce,\n * it will be overwritten by the value in userPropertiesToSet.\n * @param {Object} [userPropertiesToSetOnce] Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value.\n */\n identify(new_distinct_id?: string, userPropertiesToSet?: Properties, userPropertiesToSetOnce?: Properties): void {\n if (!this.__loaded || !this.persistence) {\n return logger.uninitializedWarning('posthog.identify')\n }\n if (isNumber(new_distinct_id)) {\n new_distinct_id = (new_distinct_id as number).toString()\n logger.warn(\n 'The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.'\n )\n }\n\n if (!this._validateIdentifyId(new_distinct_id)) {\n return\n }\n\n if (!this._requirePersonProcessing('posthog.identify')) {\n return\n }\n\n const previous_distinct_id = this.get_distinct_id()\n this.register({ $user_id: new_distinct_id })\n\n if (!this.get_property(DEVICE_ID)) {\n // The persisted distinct id might not actually be a device id at all\n // it might be a distinct id of the user from before\n const device_id = previous_distinct_id\n this.register_once(\n {\n $had_persisted_distinct_id: true,\n $device_id: device_id,\n },\n ''\n )\n }\n\n // if the previous distinct id had an alias stored, then we clear it\n if (new_distinct_id !== previous_distinct_id && new_distinct_id !== this.get_property(ALIAS_ID_KEY)) {\n this.unregister(ALIAS_ID_KEY)\n this.register({ distinct_id: new_distinct_id })\n }\n\n const isKnownAnonymous =\n (this.persistence.get_property(USER_STATE) || USER_STATE_ANONYMOUS) === USER_STATE_ANONYMOUS\n\n // send an $identify event any time the distinct_id is changing and the old ID is an anonymous ID\n // - logic on the server will determine whether or not to do anything with it.\n if (new_distinct_id !== previous_distinct_id && isKnownAnonymous) {\n this.persistence.set_property(USER_STATE, USER_STATE_IDENTIFIED)\n\n // Update current user properties\n this.setPersonPropertiesForFlags(\n { $set: userPropertiesToSet || {}, $set_once: userPropertiesToSetOnce || {} },\n false\n )\n\n this.capture(\n EVENT_IDENTIFY,\n {\n distinct_id: new_distinct_id,\n $anon_distinct_id: previous_distinct_id,\n },\n { $set: userPropertiesToSet || {}, $set_once: userPropertiesToSetOnce || {} }\n )\n\n this._cachedPersonProperties = getPersonPropertiesHash(\n new_distinct_id,\n userPropertiesToSet,\n userPropertiesToSetOnce\n )\n\n // let the reload feature flag request know to send this previous distinct id\n // for flag consistency\n this.featureFlags?.setAnonymousDistinctId(previous_distinct_id)\n } else if (userPropertiesToSet || userPropertiesToSetOnce) {\n // If the distinct_id is not changing, but we have user properties to set, we can check if they have changed\n // and if so, send a $set event\n\n this.setPersonProperties(userPropertiesToSet, userPropertiesToSetOnce)\n }\n\n // Reload active feature flags if the user identity changes.\n // Note we don't reload this on property changes as these get processed async\n if (new_distinct_id !== previous_distinct_id) {\n this.reloadFeatureFlags()\n // also clear any stored flag calls\n this.unregister(FLAG_CALL_REPORTED)\n }\n }\n\n /**\n * Sets properties on the person profile associated with the current `distinct_id`.\n * Learn more about [identifying users](/docs/product-analytics/identify)\n *\n * {@label Identification}\n *\n * @remarks\n * Updates user properties that are stored with the person profile in PostHog.\n * If `person_profiles` is set to `identified_only` and no profile exists, this will create one.\n *\n * @example\n * ```js\n * // set user properties\n * posthog.setPersonProperties({\n * email: 'user@example.com',\n * plan: 'premium'\n * })\n * ```\n *\n * @example\n * ```js\n * // set properties\n * posthog.setPersonProperties(\n * { name: 'Max Hedgehog' }, // $set properties\n * { initial_url: '/blog' } // $set_once properties\n * )\n * ```\n *\n * @public\n *\n * @param {Object} [userPropertiesToSet] Optional: An associative array of properties to store about the user. Note: For feature flag evaluations, if the same key is present in the userPropertiesToSetOnce,\n * it will be overwritten by the value in userPropertiesToSet.\n * @param {Object} [userPropertiesToSetOnce] Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value.\n */\n setPersonProperties(userPropertiesToSet?: Properties, userPropertiesToSetOnce?: Properties): void {\n if (!userPropertiesToSet && !userPropertiesToSetOnce) {\n return\n }\n\n if (!this._requirePersonProcessing('posthog.setPersonProperties')) {\n return\n }\n\n const hash = getPersonPropertiesHash(this.get_distinct_id(), userPropertiesToSet, userPropertiesToSetOnce)\n\n // if exactly this $set call has been sent before, don't send it again - determine based on hash of properties\n if (this._cachedPersonProperties === hash) {\n logger.info('A duplicate setPersonProperties call was made with the same properties. It has been ignored.')\n return\n }\n\n // Update current user properties\n this.setPersonPropertiesForFlags(\n { $set: userPropertiesToSet || {}, $set_once: userPropertiesToSetOnce || {} },\n true\n )\n\n this.capture('$set', { $set: userPropertiesToSet || {}, $set_once: userPropertiesToSetOnce || {} })\n\n this._cachedPersonProperties = hash\n }\n\n /**\n * Associates the user with a group for group-based analytics.\n * Learn more about [groups](/docs/product-analytics/group-analytics)\n *\n * {@label Identification}\n *\n * @remarks\n * Groups allow you to analyze users collectively (e.g., by organization, team, or account).\n * This sets the group association for all subsequent events and reloads feature flags.\n *\n * @example\n * ```js\n * // associate user with an organization\n * posthog.group('organization', 'org_12345', {\n * name: 'Acme Corp',\n * plan: 'enterprise'\n * })\n * ```\n *\n * @example\n * ```js\n * // associate with multiple group types\n * posthog.group('organization', 'org_12345')\n * posthog.group('team', 'team_67890')\n * ```\n *\n * @public\n *\n * @param {String} groupType Group type (example: 'organization')\n * @param {String} groupKey Group key (example: 'org::5')\n * @param {Object} groupPropertiesToSet Optional properties to set for group\n */\n group(groupType: string, groupKey: string, groupPropertiesToSet?: Properties): void {\n if (!groupType || !groupKey) {\n logger.error('posthog.group requires a group type and group key')\n return\n }\n\n const existingGroups = this.getGroups()\n const isNewGroup = existingGroups[groupType] !== groupKey\n\n // if group key changes, remove stored group properties\n if (isNewGroup) {\n this.resetGroupPropertiesForFlags(groupType)\n }\n\n this.register({ $groups: { ...existingGroups, [groupType]: groupKey } })\n\n // Send $groupidentify when the group is new/changed OR when properties\n // are provided. Skip only when the group already exists with the same\n // key and no new properties are being set.\n if (isNewGroup || groupPropertiesToSet) {\n const groupIdentifyProperties: Properties = {\n $group_type: groupType,\n $group_key: groupKey,\n }\n if (groupPropertiesToSet) {\n groupIdentifyProperties.$group_set = groupPropertiesToSet\n }\n this.capture(EVENT_GROUPIDENTIFY, groupIdentifyProperties)\n }\n\n if (groupPropertiesToSet) {\n this.setGroupPropertiesForFlags({ [groupType]: groupPropertiesToSet })\n }\n\n // If groups change and no properties change, reload feature flags.\n // The property change reload case is handled in setGroupPropertiesForFlags.\n if (isNewGroup && !groupPropertiesToSet) {\n this.reloadFeatureFlags()\n }\n }\n\n /**\n * Resets only the group properties of the user currently logged in.\n * Learn more about [groups](/docs/product-analytics/group-analytics)\n *\n * {@label Identification}\n *\n * @example\n * ```js\n * posthog.resetGroups()\n * ```\n *\n * @public\n */\n resetGroups(): void {\n this.register({ $groups: {} })\n this.resetGroupPropertiesForFlags()\n\n // If groups changed, reload feature flags.\n this.reloadFeatureFlags()\n }\n\n /**\n * Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet,\n * or were set incorrectly earlier. You can do so by setting properties the flag depends on with these calls:\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // Set properties\n * posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})\n * ```\n *\n * @example\n * ```js\n * // Set properties without reloading\n * posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false)\n * ```\n *\n * @public\n *\n * @param {Object} properties The properties to override.\n * @param {Boolean} [reloadFeatureFlags] Whether to reload feature flags.\n */\n setPersonPropertiesForFlags(properties: Properties, reloadFeatureFlags = true): void {\n this.featureFlags?.setPersonPropertiesForFlags(properties, reloadFeatureFlags)\n }\n\n /**\n * Resets the person properties for feature flags.\n *\n * {@label Feature flags}\n *\n * @public\n *\n * @example\n * ```js\n * posthog.resetPersonPropertiesForFlags()\n * ```\n */\n resetPersonPropertiesForFlags(): void {\n this.featureFlags?.resetPersonPropertiesForFlags()\n }\n\n /**\n * Set override group properties for feature flags.\n * This is used when dealing with new groups / where you don't want to wait for ingestion\n * to update properties.\n * Takes in an object, the key of which is the group type.\n *\n * {@label Feature flags}\n *\n * @public\n *\n * @example\n * ```js\n * // Set properties with reload\n * posthog.setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } })\n * ```\n *\n * @example\n * ```js\n * // Set properties without reload\n * posthog.setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } }, false)\n * ```\n *\n * @param {Object} properties The properties to override, the key of which is the group type.\n * @param {Boolean} [reloadFeatureFlags] Whether to reload feature flags.\n */\n setGroupPropertiesForFlags(properties: { [type: string]: Properties }, reloadFeatureFlags = true): void {\n if (!this._requirePersonProcessing('posthog.setGroupPropertiesForFlags')) {\n return\n }\n this.featureFlags?.setGroupPropertiesForFlags(properties, reloadFeatureFlags)\n }\n\n /**\n * Resets the group properties for feature flags.\n *\n * {@label Feature flags}\n *\n * @public\n *\n * @example\n * ```js\n * posthog.resetGroupPropertiesForFlags()\n * ```\n */\n resetGroupPropertiesForFlags(group_type?: string): void {\n this.featureFlags?.resetGroupPropertiesForFlags(group_type)\n }\n\n /**\n * Resets all user data and starts a fresh session.\n *\n * ⚠️ **Warning**: Only call this when a user logs out. Calling at the wrong time can cause split sessions.\n *\n * This clears:\n * - Session ID and super properties\n * - User identification (sets new random distinct_id)\n * - Cached data and consent settings\n *\n * {@label Identification}\n * @example\n * ```js\n * // reset on user logout\n * function logout() {\n * posthog.reset()\n * // redirect to login page\n * }\n * ```\n *\n * @example\n * ```js\n * // reset and generate new device ID\n * posthog.reset(true) // also resets device_id\n * ```\n *\n * @public\n */\n reset(reset_device_id?: boolean): void {\n logger.info('reset')\n if (!this.__loaded) {\n return logger.uninitializedWarning('posthog.reset')\n }\n const device_id = this.get_property(DEVICE_ID)\n this.consent.reset()\n this.persistence?.clear()\n this.sessionPersistence?.clear()\n this.surveys?.reset()\n // Stop the refresh interval before resetting flags — featureFlags.reset() clears\n // the debouncer, so if the order were reversed a pending refresh could fire after reset.\n this._remoteConfigLoader?.stop()\n this.featureFlags?.reset()\n this.conversations?.reset()\n this.persistence?.set_property(USER_STATE, USER_STATE_ANONYMOUS)\n this.sessionManager?.resetSessionId()\n this._cachedPersonProperties = null\n if (this.config.cookieless_mode === COOKIELESS_ALWAYS) {\n this.register_once(\n {\n distinct_id: COOKIELESS_SENTINEL_VALUE,\n $device_id: null,\n },\n ''\n )\n } else {\n const uuid = this.config.get_device_id(uuidv7())\n this.register_once(\n {\n distinct_id: uuid,\n $device_id: reset_device_id ? uuid : device_id,\n },\n ''\n )\n }\n\n this.register(\n {\n $last_posthog_reset: new Date().toISOString(),\n },\n 1\n )\n\n // Clear HMAC identity verification fields\n delete this.config.identity_distinct_id\n delete this.config.identity_hash\n\n // Reload feature flags for the new anonymous user, just like identify()\n // does when the distinct_id changes.\n this.reloadFeatureFlags()\n }\n\n /**\n * Set HMAC-based identity verification.\n *\n * @remarks\n * When set, products like conversations use server-verified identity\n * (distinct_id + HMAC hash) instead of anonymous session identifiers.\n * The hash should be computed server-side as HMAC-SHA256 of the\n * distinct_id using the project's API secret.\n *\n * @param distinctId - The verified user distinct_id\n * @param hash - HMAC-SHA256 of distinctId using the project API secret\n *\n * @example\n * ```js\n * posthog.setIdentity('user_123', 'a1b2c3d4e5f6...')\n * ```\n *\n * @public\n */\n setIdentity(distinctId: string, hash: string): void {\n this.config.identity_distinct_id = distinctId\n this.config.identity_hash = hash\n this.alias(distinctId)\n this.conversations?._onIdentityChanged()\n }\n\n /**\n * Clear HMAC-based identity verification, reverting to anonymous mode.\n *\n * @example\n * ```js\n * posthog.clearIdentity()\n * ```\n *\n * @public\n */\n clearIdentity(): void {\n delete this.config.identity_distinct_id\n delete this.config.identity_hash\n this.conversations?._onIdentityCleared()\n }\n\n /**\n * Returns the current distinct ID for the user.\n *\n * @remarks\n * This is either the auto-generated ID or the ID set via `identify()`.\n * The distinct ID is used to associate events with users in PostHog.\n *\n * {@label Identification}\n *\n * @example\n * ```js\n * // get the current user ID\n * const userId = posthog.get_distinct_id()\n * console.log('Current user:', userId)\n * ```\n *\n * @example\n * ```js\n * // use in loaded callback\n * posthog.init('token', {\n * loaded: (posthog) => {\n * const id = posthog.get_distinct_id()\n * // use the ID\n * }\n * })\n * ```\n *\n * @public\n *\n * @returns The current distinct ID\n */\n get_distinct_id(): string {\n return this.get_property('distinct_id')\n }\n\n /**\n * Returns the current groups.\n *\n * {@label Identification}\n *\n * @public\n *\n * @returns The current groups\n */\n getGroups(): Record {\n return this.get_property('$groups') || {}\n }\n\n /**\n * Returns the current session_id.\n *\n * @remarks\n * This should only be used for informative purposes.\n * Any actual internal use case for the session_id should be handled by the sessionManager.\n *\n * @public\n *\n * @returns The stored session ID for the current session. This may be an empty string if the client is not yet fully initialized.\n */\n get_session_id(): string {\n return this.sessionManager?.checkAndGetSessionAndWindowId(true).sessionId ?? ''\n }\n\n /**\n * Returns the Replay url for the current session.\n *\n * {@label Session replay}\n *\n * @public\n *\n * @example\n * ```js\n * // basic usage\n * posthog.get_session_replay_url()\n *\n * @example\n * ```js\n * // timestamp\n * posthog.get_session_replay_url({ withTimestamp: true })\n * ```\n *\n * @example\n * ```js\n * // timestamp and lookback\n * posthog.get_session_replay_url({\n * withTimestamp: true,\n * timestampLookBack: 30 // look back 30 seconds\n * })\n * ```\n *\n * @param options Options for the url\n * @param options.withTimestamp Whether to include the timestamp in the url (defaults to false)\n * @param options.timestampLookBack How many seconds to look back for the timestamp (defaults to 10)\n */\n get_session_replay_url(options?: { withTimestamp?: boolean; timestampLookBack?: number }): string {\n if (!this.sessionManager) {\n return ''\n }\n const { sessionId, sessionStartTimestamp } = this.sessionManager.checkAndGetSessionAndWindowId(true)\n let url = this.requestRouter.endpointFor('ui', `/project/${this.config.token}/replay/${sessionId}`)\n if (options?.withTimestamp && sessionStartTimestamp) {\n const LOOK_BACK = options.timestampLookBack ?? 10\n if (!sessionStartTimestamp) {\n return url\n }\n const recordingStartTime = Math.max(\n Math.floor((new Date().getTime() - sessionStartTimestamp) / 1000) - LOOK_BACK,\n 0\n )\n url += `?t=${recordingStartTime}`\n }\n\n return url\n }\n\n /**\n * Creates an alias linking two distinct user identifiers. Learn more about [identifying users](/docs/product-analytics/identify)\n *\n * {@label Identification}\n *\n * @remarks\n * PostHog will use this to link two distinct_ids going forward (not retroactively).\n * Call this when a user signs up to connect their anonymous session with their account.\n *\n *\n * @example\n * ```js\n * // link anonymous user to account on signup\n * posthog.alias('user_12345')\n * ```\n *\n * @example\n * ```js\n * // explicit alias with original ID\n * posthog.alias('user_12345', 'anonymous_abc123')\n * ```\n *\n * @public\n *\n * @param {String} alias A unique identifier that you want to use for this user in the future.\n * @param {String} [original] The current identifier being used for this user.\n */\n alias(alias: string, original?: string): CaptureResult | void | number {\n // If the $people_distinct_id key exists in persistence, there has been a previous\n // posthog.people.identify() call made for this user. It is VERY BAD to make an alias with\n // this ID, as it will duplicate users.\n if (alias === this.get_property(PEOPLE_DISTINCT_ID_KEY)) {\n logger.critical('Attempting to create alias for existing People user - aborting.')\n return -2\n }\n if (!this._requirePersonProcessing('posthog.alias')) {\n return\n }\n\n if (isUndefined(original)) {\n original = this.get_distinct_id()\n }\n if (alias !== original) {\n this._register_single(ALIAS_ID_KEY, alias)\n return this.capture('$create_alias', { alias: alias, distinct_id: original })\n } else {\n logger.warn('alias matches current distinct_id - skipping api call.')\n this.identify(alias)\n return -1\n }\n }\n\n /**\n * Updates the configuration of the PostHog instance.\n *\n * {@label Initialization}\n *\n * @public\n *\n * @param {Partial} config A dictionary of new configuration values to update\n */\n set_config(config: Partial): void {\n const oldConfig = { ...this.config }\n if (isObject(config)) {\n extend(this.config, configRenames(config))\n\n const isPersistenceDisabled = this._is_persistence_disabled()\n this.persistence?.update_config(this.config, oldConfig, isPersistenceDisabled)\n this.sessionPersistence =\n this.config.persistence === 'sessionStorage' || this.config.persistence === 'memory'\n ? this.persistence\n : new PostHogPersistence({ ...this.config, persistence: 'sessionStorage' }, isPersistenceDisabled)\n\n const debugConfigFromLocalStorage = this._checkLocalStorageForDebug(this.config.debug)\n if (isBoolean(debugConfigFromLocalStorage)) {\n this.config.debug = debugConfigFromLocalStorage\n }\n\n if (isBoolean(this.config.debug)) {\n if (this.config.debug) {\n Config.DEBUG = true\n localStore._is_supported() && localStore._set('ph_debug', true)\n logger.info('set_config', {\n config,\n oldConfig,\n newConfig: { ...this.config },\n })\n } else {\n Config.DEBUG = false\n localStore._is_supported() && localStore._remove('ph_debug')\n }\n }\n\n this.exceptionObserver?.onConfigChange()\n\n this.sessionRecording?.startIfEnabledOrStop()\n this.autocapture?.startIfEnabled()\n this.heatmaps?.startIfEnabled()\n this.exceptionObserver?.startIfEnabledOrStop()\n this.deadClicksAutocapture?.startIfEnabledOrStop()\n this.surveys?.loadIfEnabled()\n this._sync_opt_out_with_persistence()\n this.externalIntegrations?.startIfEnabledOrStop()\n }\n }\n\n /**\n * @internal\n * Allows wrapper SDKs (e.g. posthog-flutter, posthog-react-native) to override the\n * `$lib` and `$lib_version` properties sent with every event.\n *\n * This is not a public API and may change without notice.\n */\n _overrideSDKInfo(sdkName: string, sdkVersion: string): void {\n Config.LIB_NAME = sdkName\n Config.LIB_VERSION = sdkVersion\n }\n\n /**\n * turns session recording on, and updates the config option `disable_session_recording` to false\n *\n * {@label Session replay}\n *\n * @public\n *\n * @example\n * ```js\n * // Start and ignore controls\n * posthog.startSessionRecording(true)\n * ```\n *\n * @example\n * ```js\n * // Start and override controls\n * posthog.startSessionRecording({\n * // you don't have to send all of these\n * sampling: true || false,\n * linked_flag: true || false,\n * url_trigger: true || false,\n * event_trigger: true || false\n * })\n * ```\n *\n * @param override.sampling - optional boolean to override the default sampling behavior - ensures the next session recording to start will not be skipped by sampling config.\n * @param override.linked_flag - optional boolean to override the default linked_flag behavior - ensures the next session recording to start will not be skipped by linked_flag config.\n * @param override.url_trigger - optional boolean to override the default url_trigger behavior - ensures the next session recording to start will not be skipped by url_trigger config.\n * @param override.event_trigger - optional boolean to override the default event_trigger behavior - ensures the next session recording to start will not be skipped by event_trigger config.\n * @param override - optional boolean to override the default sampling behavior - ensures the next session recording to start will not be skipped by sampling or linked_flag config. `true` is shorthand for { sampling: true, linked_flag: true }\n */\n startSessionRecording(\n override?: { sampling?: boolean; linked_flag?: boolean; url_trigger?: true; event_trigger?: true } | true\n ): void {\n const overrideAll = override === true\n const overrideConfig: OverrideConfig = {\n sampling: overrideAll || !!override?.sampling,\n linked_flag: overrideAll || !!override?.linked_flag,\n url_trigger: overrideAll || !!override?.url_trigger,\n event_trigger: overrideAll || !!override?.event_trigger,\n }\n\n if (Object.values(overrideConfig).some(Boolean)) {\n // allow the session id check to rotate session id if necessary\n this.sessionManager?.checkAndGetSessionAndWindowId()\n\n if (overrideConfig.sampling) {\n this.sessionRecording?.overrideSampling()\n }\n\n if (overrideConfig.linked_flag) {\n this.sessionRecording?.overrideLinkedFlag()\n }\n\n if (overrideConfig.url_trigger) {\n this.sessionRecording?.overrideTrigger('url')\n }\n\n if (overrideConfig.event_trigger) {\n this.sessionRecording?.overrideTrigger('event')\n }\n }\n\n this.set_config({ disable_session_recording: false })\n }\n\n /**\n * turns session recording off, and updates the config option\n * disable_session_recording to true\n *\n * {@label Session replay}\n *\n * @public\n *\n * @example\n * ```js\n * // Stop session recording\n * posthog.stopSessionRecording()\n * ```\n */\n stopSessionRecording(): void {\n this.set_config({ disable_session_recording: true })\n }\n\n /**\n * returns a boolean indicating whether session recording\n * is currently running\n *\n * {@label Session replay}\n *\n * @public\n *\n * @example\n * ```js\n * // Stop session recording if it's running\n * if (posthog.sessionRecordingStarted()) {\n * posthog.stopSessionRecording()\n * }\n * ```\n */\n sessionRecordingStarted(): boolean {\n return !!this.sessionRecording?.started\n }\n\n /**\n * Capture a caught exception manually\n *\n * {@label Error tracking}\n *\n * @public\n *\n * @example\n * ```js\n * // Capture a caught exception\n * try {\n * // something that might throw\n * } catch (error) {\n * posthog.captureException(error)\n * }\n * ```\n *\n * @example\n * ```js\n * // With additional properties\n * posthog.captureException(error, {\n * customProperty: 'value',\n * anotherProperty: ['I', 'can be a list'],\n * ...\n * })\n * ```\n *\n * @param {Error} error The error to capture\n * @param {Object} [additionalProperties] Any additional properties to add to the error event\n * @returns {CaptureResult} The result of the capture\n */\n captureException(error: unknown, additionalProperties?: Properties): CaptureResult | undefined {\n if (!this.exceptions) return\n\n const syntheticException = new Error('PostHog syntheticException')\n const errorToProperties = this.exceptions.buildProperties(error, {\n handled: true,\n syntheticException,\n })\n return this.exceptions.sendExceptionEvent({\n ...errorToProperties,\n ...additionalProperties,\n })\n }\n\n /**\n * Capture a log entry and send it to the PostHog logs endpoint.\n *\n * {@label Logs}\n *\n * @public\n *\n * @example\n * ```js\n * posthog.captureLog({\n * body: 'checkout completed',\n * level: 'info',\n * attributes: { order_id: 'ord_789', amount_cents: 4999 },\n * })\n * ```\n *\n * @param {CaptureLogOptions} options The log entry options\n */\n captureLog(options: CaptureLogOptions): void {\n this.logs?.captureLog(options)\n }\n\n private static _noopLogger = (() => {\n const noop = () => {}\n return { trace: noop, debug: noop, info: noop, warn: noop, error: noop, fatal: noop }\n })()\n\n /**\n * Logger with convenience methods for each severity level.\n *\n * @example\n * ```js\n * posthog.logger.info('checkout completed', { order_id: 'ord_789' })\n * posthog.logger.error('payment failed', { error_code: 'E001' })\n * ```\n */\n get logger() {\n return this.logs?.logger ?? PostHog._noopLogger\n }\n\n /**\n * turns exception autocapture on, and updates the config option `capture_exceptions` to the provided config (or `true`)\n *\n * {@label Error tracking}\n *\n * @public\n *\n * @example\n * ```js\n * // Start with default exception autocapture rules. No-op if already enabled\n * posthog.startExceptionAutocapture()\n * ```\n *\n * @example\n * ```js\n * // Start and override controls\n * posthog.startExceptionAutocapture({\n * // you don't have to send all of these (unincluded values will use the default)\n * capture_unhandled_errors: true || false,\n * capture_unhandled_rejections: true || false,\n * capture_console_errors: true || false\n * })\n * ```\n *\n * @param config - optional configuration option to control the exception autocapture behavior\n */\n startExceptionAutocapture(config?: ExceptionAutoCaptureConfig): void {\n this.set_config({ capture_exceptions: config ?? true })\n }\n\n /**\n * turns exception autocapture off by updating the config option `capture_exceptions` to `false`\n *\n * {@label Error tracking}\n *\n * @public\n *\n * @example\n * ```js\n * // Stop capturing exceptions automatically\n * posthog.stopExceptionAutocapture()\n * ```\n */\n stopExceptionAutocapture(): void {\n this.set_config({ capture_exceptions: false })\n }\n\n /**\n * returns a boolean indicating whether the [toolbar](/docs/toolbar) loaded\n *\n * {@label Toolbar}\n *\n * @public\n *\n * @param toolbarParams\n * @returns {boolean} Whether the toolbar loaded\n */\n\n loadToolbar(params: ToolbarParams): boolean {\n return this.toolbar?.loadToolbar(params) ?? false\n }\n\n /**\n * Returns the value of a super property. Returns undefined if the property doesn't exist.\n *\n * {@label Identification}\n *\n * @remarks\n * get_property() can only be called after the PostHog library has finished loading.\n * init() has a loaded function available to handle this automatically.\n *\n * @example\n * ```js\n * // grab value for '$user_id' after the posthog library has loaded\n * posthog.init('', {\n * loaded: function(posthog) {\n * user_id = posthog.get_property('$user_id');\n * }\n * });\n * ```\n * @public\n *\n * @param {String} property_name The name of the super property you want to retrieve\n */\n get_property(property_name: string): Property | undefined {\n return this.persistence?.props[property_name]\n }\n\n /**\n * Returns the value of the session super property named property_name. If no such\n * property is set, getSessionProperty() will return the undefined value.\n *\n * {@label Identification}\n *\n * @public\n *\n * @remarks\n * This is based on browser-level `sessionStorage`, NOT the PostHog session.\n * getSessionProperty() can only be called after the PostHog library has finished loading.\n * init() has a loaded function available to handle this automatically.\n *\n * @example\n * ```js\n * // grab value for 'user_id' after the posthog library has loaded\n * posthog.init('YOUR PROJECT TOKEN', {\n * loaded: function(posthog) {\n * user_id = posthog.getSessionProperty('user_id');\n * }\n * });\n * ```\n *\n * @param {String} property_name The name of the session super property you want to retrieve\n */\n getSessionProperty(property_name: string): Property | undefined {\n return this.sessionPersistence?.props[property_name]\n }\n\n /**\n * Returns a string representation of the PostHog instance.\n *\n * {@label Initialization}\n *\n * @internal\n */\n toString(): string {\n let name = this.config.name ?? PRIMARY_INSTANCE_NAME\n if (name !== PRIMARY_INSTANCE_NAME) {\n name = PRIMARY_INSTANCE_NAME + '.' + name\n }\n return name\n }\n\n _isIdentified(): boolean {\n return (\n this.persistence?.get_property(USER_STATE) === USER_STATE_IDENTIFIED ||\n this.sessionPersistence?.get_property(USER_STATE) === USER_STATE_IDENTIFIED\n )\n }\n\n _hasPersonProcessing(): boolean {\n return !(\n this.config.person_profiles === 'never' ||\n (this.config.person_profiles === PERSON_PROFILES_IDENTIFIED_ONLY &&\n !this._isIdentified() &&\n isEmptyObject(this.getGroups()) &&\n !this.persistence?.props?.[ALIAS_ID_KEY] &&\n !this.persistence?.props?.[ENABLE_PERSON_PROCESSING])\n )\n }\n\n _shouldCapturePageleave(): boolean {\n return (\n this.config.capture_pageleave === true ||\n (this.config.capture_pageleave === 'if_capture_pageview' &&\n (this.config.capture_pageview === true || this.config.capture_pageview === 'history_change'))\n )\n }\n\n /**\n * Creates a person profile for the current user, if they don't already have one and config.person_profiles is set\n * to 'identified_only'. Produces a warning and does not create a profile if config.person_profiles is set to\n * 'never'. Learn more about [person profiles](/docs/product-analytics/identify)\n *\n * {@label Identification}\n *\n * @public\n *\n * @example\n * ```js\n * posthog.createPersonProfile()\n * ```\n */\n createPersonProfile(): void {\n if (this._hasPersonProcessing()) {\n // if a person profile already exists, don't send an event when we don't need to\n return\n }\n if (!this._requirePersonProcessing('posthog.createPersonProfile')) {\n return\n }\n // sent a $set event. We don't set any properties here, but attribution props will be added later\n this.setPersonProperties({}, {})\n }\n\n /**\n * Marks the current user as a test user by setting the `$internal_or_test_user` person property to `true`.\n * This also enables person processing for the current user.\n *\n * This is useful for using in a cohort your internal/test filters for your posthog org.\n * @see https://posthog.com/tutorials/filter-internal-users\n * Create a cohort with `$internal_or_test_user` IS SET, and set your internal test filters to be NOT IN that cohort.\n *\n * {@label Identification}\n *\n * @example\n * ```js\n * // Manually mark as test user\n * posthog.setInternalOrTestUser()\n *\n * // Or use internal_or_test_user_hostname config for automatic detection\n * posthog.init('token', { internal_or_test_user_hostname: 'localhost' })\n * ```\n *\n * @public\n */\n setInternalOrTestUser(): void {\n if (!this._requirePersonProcessing('posthog.setInternalOrTestUser')) {\n return\n }\n this.setPersonProperties({ $internal_or_test_user: true })\n }\n\n /**\n * Enables person processing if possible, returns true if it does so or already enabled, false otherwise\n *\n * @param function_name\n */\n _requirePersonProcessing(function_name: string): boolean {\n if (this.config.person_profiles === 'never') {\n logger.error(\n function_name + ' was called, but process_person is set to \"never\". This call will be ignored.'\n )\n return false\n }\n this._register_single(ENABLE_PERSON_PROCESSING, true)\n return true\n }\n\n private _is_persistence_disabled(): boolean {\n if (this.config.cookieless_mode === 'always') {\n return true\n }\n const isOptedOut = this.consent.isOptedOut()\n const defaultPersistenceDisabled =\n this.config.opt_out_persistence_by_default || this.config.cookieless_mode === COOKIELESS_ON_REJECT\n\n // TRICKY: We want a deterministic state for persistence so that a new pageload has the same persistence\n return this.config.disable_persistence || (isOptedOut && !!defaultPersistenceDisabled)\n }\n\n private _sync_opt_out_with_persistence(): boolean {\n const persistenceDisabled = this._is_persistence_disabled()\n\n if (this.persistence?._disabled !== persistenceDisabled) {\n this.persistence?.set_disabled(persistenceDisabled)\n }\n if (this.sessionPersistence?._disabled !== persistenceDisabled) {\n this.sessionPersistence?.set_disabled(persistenceDisabled)\n }\n return persistenceDisabled\n }\n\n /**\n * Opts the user into data capturing and persistence.\n *\n * {@label Privacy}\n *\n * @remarks\n * Enables event tracking and data persistence (cookies/localStorage) for this PostHog instance.\n * By default, captures an `$opt_in` event unless disabled.\n *\n * @example\n * ```js\n * // simple opt-in\n * posthog.opt_in_capturing()\n * ```\n *\n * @example\n * ```js\n * // opt-in with custom event and properties\n * posthog.opt_in_capturing({\n * captureEventName: 'Privacy Accepted',\n * captureProperties: { source: 'banner' }\n * })\n * ```\n *\n * @example\n * ```js\n * // opt-in without capturing event\n * posthog.opt_in_capturing({\n * captureEventName: false\n * })\n * ```\n *\n * @public\n *\n * @param {Object} [config] A dictionary of config options to override\n * @param {string} [config.capture_event_name=$opt_in] Event name to be used for capturing the opt-in action. Set to `null` or `false` to skip capturing the optin event\n * @param {Object} [config.capture_properties] Set of properties to be captured along with the opt-in action\n */\n opt_in_capturing(options?: {\n captureEventName?: EventName | null | false /** event name to be used for capturing the opt-in action */\n captureProperties?: Properties /** set of properties to be captured along with the opt-in action */\n }): void {\n if (this.config.cookieless_mode === COOKIELESS_ALWAYS) {\n logger.warn(CONSENT_COOKIELESS_WARN)\n return\n }\n if (this.config.cookieless_mode === COOKIELESS_ON_REJECT && this.consent.isExplicitlyOptedOut()) {\n // If the user has explicitly opted out on_reject mode, then before we can start sending regular non-cookieless events\n // we need to reset the instance to ensure that there is no leaking of state or data between the cookieless and regular events\n this.reset(true)\n this.sessionManager?.destroy()\n this.pageViewManager?.destroy()\n this.sessionManager = new SessionIdManager(this)\n this.pageViewManager = new PageViewManager(this)\n if (this.persistence) {\n this.sessionPropsManager = new SessionPropsManager(this, this.sessionManager, this.persistence)\n }\n const SessionRecordingClass =\n this.config.__extensionClasses?.sessionRecording ?? PostHog.__defaultExtensionClasses?.sessionRecording\n if (SessionRecordingClass) {\n this.sessionRecording = this._replaceExtension(\n this.sessionRecording,\n new SessionRecordingClass(this) as SessionRecording\n )\n }\n }\n\n this.consent.optInOut(true)\n this._sync_opt_out_with_persistence()\n\n // Start queue after opting in\n this._start_queue_if_opted_in()\n\n // Restart session recording if it should now be enabled\n // (this handles the case where opt_out_capturing_by_default or cookieless_mode prevented it from starting)\n this.sessionRecording?.startIfEnabledOrStop()\n\n // Reinitialize surveys if we're in cookieless mode and just opted in\n if (this.config.cookieless_mode == COOKIELESS_ON_REJECT) {\n this.surveys?.loadIfEnabled()\n }\n\n // Don't capture if captureEventName is null or false\n if (isUndefined(options?.captureEventName) || options?.captureEventName) {\n this.capture(options?.captureEventName ?? '$opt_in', options?.captureProperties, { send_instantly: true })\n }\n\n if (this.config.capture_pageview) {\n this._captureInitialPageview()\n }\n }\n\n /**\n * Opts the user out of data capturing and persistence.\n *\n * {@label Privacy}\n *\n * @remarks\n * Disables event tracking and data persistence (cookies/localStorage) for this PostHog instance.\n * If `opt_out_persistence_by_default` is true, SDK persistence will also be disabled.\n *\n * @example\n * ```js\n * // opt user out (e.g., on privacy settings page)\n * posthog.opt_out_capturing()\n * ```\n *\n * @public\n */\n opt_out_capturing(): void {\n if (this.config.cookieless_mode === COOKIELESS_ALWAYS) {\n logger.warn(CONSENT_COOKIELESS_WARN)\n return\n }\n\n if (this.config.cookieless_mode === COOKIELESS_ON_REJECT && this.consent.isOptedIn()) {\n // If the user has opted in, we need to reset the instance to ensure that there is no leaking of state or data between the cookieless and regular events\n this.reset(true)\n }\n\n this.consent.optInOut(false)\n this._sync_opt_out_with_persistence()\n\n if (this.config.cookieless_mode === COOKIELESS_ON_REJECT) {\n // If cookieless_mode is COOKIELESS_ON_REJECT, we start capturing events in cookieless mode\n this.register({\n distinct_id: COOKIELESS_SENTINEL_VALUE,\n $device_id: null,\n })\n this.sessionManager?.destroy()\n this.pageViewManager?.destroy()\n this.sessionManager = undefined\n this.sessionPropsManager = undefined\n this.sessionRecording?.stopRecording()\n this.sessionRecording = undefined\n this._captureInitialPageview()\n }\n }\n\n /**\n * Checks if the user has opted into data capturing.\n *\n * {@label Privacy}\n *\n * @remarks\n * Returns the current consent status for event tracking and data persistence.\n *\n * @example\n * ```js\n * if (posthog.has_opted_in_capturing()) {\n * // show analytics features\n * }\n * ```\n *\n * @public\n *\n * @returns {boolean} current opt-in status\n */\n has_opted_in_capturing(): boolean {\n return this.consent.isOptedIn()\n }\n\n /**\n * Checks if the user has opted out of data capturing.\n *\n * {@label Privacy}\n *\n * @remarks\n * Returns the current consent status for event tracking and data persistence.\n *\n * @example\n * ```js\n * if (posthog.has_opted_out_capturing()) {\n * // disable analytics features\n * }\n * ```\n *\n * @public\n *\n * @returns {boolean} current opt-out status\n */\n has_opted_out_capturing(): boolean {\n return this.consent.isOptedOut()\n }\n\n /**\n * Returns the explicit consent status of the user.\n *\n * @remarks\n * This can be used to check if the user has explicitly opted in or out of data capturing, or neither. This does not\n * take the default config options into account, only whether the user has made an explicit choice, so this can be\n * used to determine whether to show an initial cookie banner or not.\n *\n * @example\n * ```js\n * const consentStatus = posthog.get_explicit_consent_status()\n * if (consentStatus === \"granted\") {\n * // user has explicitly opted in\n * } else if (consentStatus === \"denied\") {\n * // user has explicitly opted out\n * } else if (consentStatus === \"pending\"){\n * // user has not made a choice, show consent banner\n * }\n * ```\n *\n * @public\n *\n * @returns {boolean | null} current explicit consent status\n */\n get_explicit_consent_status(): 'granted' | 'denied' | 'pending' {\n const consent = this.consent.consent\n return consent === ConsentStatus.GRANTED ? 'granted' : consent === ConsentStatus.DENIED ? 'denied' : 'pending'\n }\n\n /**\n * Checks whether the PostHog library is currently capturing events.\n *\n * Usually this means that the user has not opted out of capturing, but the exact behaviour can be controlled by\n * some config options.\n *\n * Additionally, if the cookieless_mode is set to `'on_reject'`, we will capture events in cookieless mode if the\n * user has explicitly opted out.\n *\n * {@label Privacy}\n *\n * @see {PostHogConfig.cookieless_mode}\n * @see {PostHogConfig.opt_out_persistence_by_default}\n * @see {PostHogConfig.respect_dnt}\n *\n * @returns {boolean} whether the posthog library is capturing events\n */\n is_capturing(): boolean {\n if (this.config.cookieless_mode === COOKIELESS_ALWAYS) {\n return true\n }\n if (this.config.cookieless_mode === COOKIELESS_ON_REJECT) {\n return this.consent.isExplicitlyOptedOut() || this.consent.isOptedIn()\n } else {\n return !this.has_opted_out_capturing()\n }\n }\n\n /**\n * Clear the user's opt in/out status of data capturing and cookies/localstorage for this PostHog instance\n *\n * {@label Privacy}\n *\n * @public\n *\n */\n clear_opt_in_out_capturing(): void {\n this.consent.reset()\n this._sync_opt_out_with_persistence()\n }\n\n _is_bot(): boolean | undefined {\n if (navigator) {\n return isLikelyBot(navigator, this.config.custom_blocked_useragents)\n } else {\n return undefined\n }\n }\n\n _captureInitialPageview(): void {\n if (!document) {\n return\n }\n\n // If page is not visible, add a listener to detect when the page becomes visible\n // and trigger the pageview only then\n // This is useful to avoid `prerender` calls from Chrome/Wordpress/SPAs\n // that are not visible to the user\n\n if (document.visibilityState !== 'visible') {\n if (!this._visibilityStateListener) {\n this._visibilityStateListener = this._captureInitialPageview.bind(this)\n addEventListener(document, DOM_EVENT_VISIBILITYCHANGE, this._visibilityStateListener)\n }\n\n return\n }\n\n // Extra check here to guarantee we only ever trigger a single `$pageview` event\n if (!this._initialPageviewCaptured) {\n this._initialPageviewCaptured = true\n this.capture(EVENT_PAGEVIEW, { title: document.title }, { send_instantly: true })\n\n // After we've captured the initial pageview, we can remove the listener\n if (this._visibilityStateListener) {\n document.removeEventListener(DOM_EVENT_VISIBILITYCHANGE, this._visibilityStateListener)\n this._visibilityStateListener = null\n }\n }\n }\n\n /**\n * Enables or disables debug mode for detailed logging.\n *\n * @remarks\n * Debug mode logs all PostHog calls to the browser console for troubleshooting.\n * Can also be enabled by adding `?__posthog_debug=true` to the URL.\n *\n * {@label Initialization}\n *\n * @example\n * ```js\n * // enable debug mode\n * posthog.debug(true)\n * ```\n *\n * @example\n * ```js\n * // disable debug mode\n * posthog.debug(false)\n * ```\n *\n * @public\n *\n * @param {boolean} [debug] If true, will enable debug mode.\n */\n debug(debug?: boolean): void {\n if (debug === false) {\n window?.console.log(\"You've disabled debug mode.\")\n this.set_config({ debug: false })\n } else {\n window?.console.log(\n \"You're now in debug mode. All calls to PostHog will be logged in your console.\\nYou can disable this with `posthog.debug(false)`.\"\n )\n this.set_config({ debug: true })\n }\n }\n\n /**\n * Helper method to check if external API calls (flags/decide) should be disabled\n * Handles migration from old `advanced_disable_decide` to new `advanced_disable_flags`\n */\n _shouldDisableFlags(): boolean {\n // Check if advanced_disable_flags was explicitly set in original config\n const originalConfig = this._originalUserConfig || {}\n if ('advanced_disable_flags' in originalConfig) {\n return !!originalConfig.advanced_disable_flags\n }\n\n // Check if advanced_disable_flags was set post-init (different from default false)\n if (this.config.advanced_disable_flags !== false) {\n return !!this.config.advanced_disable_flags\n }\n\n // Check for post-init changes to advanced_disable_decide\n if (this.config.advanced_disable_decide === true) {\n logger.warn(\n \"Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. \" +\n 'The old field will be removed in a future major version.'\n )\n return true\n }\n\n // Fall back to migration logic for original user config\n return migrateConfigField(originalConfig, 'advanced_disable_flags', 'advanced_disable_decide', false, logger)\n }\n\n private _runBeforeSend(data: CaptureResult): CaptureResult | null {\n if (isNullish(this.config.before_send)) {\n return data\n }\n\n const fns = isArray(this.config.before_send) ? this.config.before_send : [this.config.before_send]\n let beforeSendResult: CaptureResult | null = data\n for (const fn of fns) {\n beforeSendResult = fn(beforeSendResult)\n if (isNullish(beforeSendResult)) {\n const logMessage = `Event '${data.event}' was rejected in beforeSend function`\n if (isKnownUnsafeEditableEvent(data.event)) {\n logger.warn(`${logMessage}. This can cause unexpected behavior.`)\n } else {\n logger.info(logMessage)\n }\n return null\n }\n if (!beforeSendResult.properties || isEmptyObject(beforeSendResult.properties)) {\n logger.warn(\n `Event '${data.event}' has no properties after beforeSend function, this is likely an error.`\n )\n }\n }\n return beforeSendResult\n }\n\n /**\n * Returns the current page view ID.\n *\n * {@label Initialization}\n *\n * @public\n *\n * @returns {string} The current page view ID\n */\n public getPageViewId(): string | undefined {\n return this.pageViewManager._currentPageview?.pageViewId\n }\n\n /**\n * Capture written user feedback for a LLM trace. Numeric values are converted to strings.\n *\n * {@label LLM analytics}\n *\n * @public\n *\n * @param traceId The trace ID to capture feedback for.\n * @param userFeedback The feedback to capture.\n */\n captureTraceFeedback(traceId: string | number, userFeedback: string) {\n this.capture('$ai_feedback', {\n $ai_trace_id: String(traceId),\n $ai_feedback_text: userFeedback,\n })\n }\n\n /**\n * Capture a metric for a LLM trace. Numeric values are converted to strings.\n *\n * {@label LLM analytics}\n *\n * @public\n *\n * @param traceId The trace ID to capture the metric for.\n * @param metricName The name of the metric to capture.\n * @param metricValue The value of the metric to capture.\n */\n captureTraceMetric(traceId: string | number, metricName: string, metricValue: string | number | boolean) {\n this.capture('$ai_metric', {\n $ai_trace_id: String(traceId),\n $ai_metric_name: metricName,\n $ai_metric_value: String(metricValue),\n })\n }\n\n private _checkLocalStorageForDebug(debugConfig: boolean | undefined) {\n const explicitlyFalse = isBoolean(debugConfig) && !debugConfig\n const isTrueInLocalStorage = localStore._is_supported() && localStore._get('ph_debug') === 'true'\n return explicitlyFalse ? false : isTrueInLocalStorage ? true : debugConfig\n }\n}\n\nsafewrapClass(PostHog, ['identify'])\n\nconst add_dom_loaded_handler = function () {\n // Cross browser DOM Loaded support\n function dom_loaded_handler() {\n // function flag since we only want to execute this once\n if ((dom_loaded_handler as any).done) {\n return\n }\n ;(dom_loaded_handler as any).done = true\n\n ENQUEUE_REQUESTS = false\n\n each(instances, function (inst: PostHog) {\n inst._dom_loaded()\n })\n }\n\n if (document?.addEventListener) {\n if (document.readyState === 'complete') {\n // safari 4 can fire the DOMContentLoaded event before loading all\n // external JS (including this file). you will see some copypasta\n // on the internet that checks for 'complete' and 'loaded', but\n // 'loaded' is an IE thing\n dom_loaded_handler()\n } else {\n addEventListener(document, 'DOMContentLoaded', dom_loaded_handler, { capture: false })\n }\n\n return\n }\n\n // Only IE6-8 don't support `document.addEventListener` and we don't support them\n // so let's simply log an error stating PostHog couldn't be initialized\n // We're checking for `window` to avoid erroring out on a SSR context\n if (window) {\n logger.error(\"Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized\")\n }\n}\n\nexport function init_from_snippet(): void {\n const posthogMain = (instances[PRIMARY_INSTANCE_NAME] = new PostHog())\n\n const snippetPostHog = assignableWindow['posthog']\n\n if (snippetPostHog) {\n /**\n * The snippet uses some clever tricks to allow deferred loading of array.js (this code)\n *\n * window.posthog is an array which the queue of calls made before the lib is loaded\n * It has methods attached to it to simulate the posthog object so for instance\n *\n * window.posthog.init(\"TOKEN\", {api_host: \"foo\" })\n * window.posthog.capture(\"my-event\", {foo: \"bar\" })\n *\n * ... will mean that window.posthog will look like this:\n * window.posthog == [\n * [\"my-event\", {foo: \"bar\"}]\n * ]\n *\n * window.posthog[_i] == [\n * [\"TOKEN\", {api_host: \"foo\" }, \"posthog\"]\n * ]\n *\n * If a name is given to the init function then the same as above is true but as a sub-property on the object:\n *\n * window.posthog.init(\"TOKEN\", {}, \"ph2\")\n * window.posthog.ph2.people.set({foo: \"bar\"})\n *\n * window.posthog.ph2 == []\n * window.posthog.people == [\n * [\"set\", {foo: \"bar\"}]\n * ]\n *\n */\n\n // Call all pre-loaded init calls properly\n\n each(snippetPostHog['_i'], function (item: [token: string, config: Partial, name: string]) {\n if (item && isArray(item)) {\n const instance = posthogMain.init(item[0], item[1], item[2])\n\n const instanceSnippet = snippetPostHog[item[2]] || snippetPostHog\n\n if (instance) {\n // Crunch through the people queue first - we queue this data up &\n // flush on identify, so it's better to do all these operations first\n instance._execute_array.call(instance.people, instanceSnippet.people)\n instance._execute_array(instanceSnippet)\n }\n }\n })\n }\n\n assignableWindow['posthog'] = posthogMain\n\n add_dom_loaded_handler()\n}\n\nexport function init_as_module(): PostHog {\n const posthogMain = (instances[PRIMARY_INSTANCE_NAME] = new PostHog())\n\n add_dom_loaded_handler()\n\n return posthogMain\n}\n", "import { TOOLBAR_CONTAINER_CLASS, TOOLBAR_ID } from '../constants'\n\nexport function isElementInToolbar(el: EventTarget | null): boolean {\n if (el instanceof Element) {\n // closest isn't available in IE11, but we'll polyfill when bundling\n return el.id === TOOLBAR_ID || !!el.closest?.('.' + TOOLBAR_CONTAINER_CLASS)\n }\n return false\n}\n\n/*\n * Check whether an element has nodeType Node.ELEMENT_NODE\n * @param {Element} el - element to check\n * @returns {boolean} whether el is of the correct nodeType\n */\nexport function isElementNode(el: Node | Element | undefined | null): el is Element {\n return !!el && el.nodeType === 1 // Node.ELEMENT_NODE - use integer constant for browser portability\n}\n\n/*\n * Check whether an element is of a given tag type.\n * Due to potential reference discrepancies (such as the webcomponents.js polyfill),\n * we want to match tagNames instead of specific references because something like\n * element === document.body won't always work because element might not be a native\n * element.\n * @param {Element} el - element to check\n * @param {string} tag - tag name (e.g., \"div\")\n * @returns {boolean} whether el is of the given tag type\n */\nexport function isTag(el: Element | undefined | null, tag: string): el is HTMLElement {\n return !!el && !!el.tagName && el.tagName.toLowerCase() === tag.toLowerCase()\n}\n\n/*\n * Check whether an element has nodeType Node.TEXT_NODE\n * @param {Element} el - element to check\n * @returns {boolean} whether el is of the correct nodeType\n */\nexport function isTextNode(el: Element | undefined | null): el is HTMLElement {\n return !!el && el.nodeType === 3 // Node.TEXT_NODE - use integer constant for browser portability\n}\n\n/*\n * Check whether an element has nodeType Node.DOCUMENT_FRAGMENT_NODE\n * @param {Element} el - element to check\n * @returns {boolean} whether el is of the correct nodeType\n */\nexport function isDocumentFragment(el: Element | ParentNode | undefined | null): el is DocumentFragment {\n return !!el && el.nodeType === 11 // Node.DOCUMENT_FRAGMENT_NODE - use integer constant for browser portability\n}\n", "import { AutocaptureConfig, PostHogConfig, Properties } from './types'\nimport { each, entries } from './utils'\n\nimport { isNullish, isString, isUndefined, isArray, isBoolean } from '@posthog/core'\nimport { logger } from './utils/logger'\nimport { window } from './utils/globals'\nimport { isDocumentFragment, isElementNode, isTag, isTextNode } from './utils/element-utils'\nimport { includes, trim } from '@posthog/core'\n\nexport function splitClassString(s: string): string[] {\n return s ? trim(s).split(/\\s+/) : []\n}\n\nfunction checkForURLMatches(urlsList: (string | RegExp)[]): boolean {\n const url = window?.location.href\n return !!(url && urlsList && urlsList.some((regex) => url.match(regex)))\n}\n\n/*\n * Get the className of an element, accounting for edge cases where element.className is an object\n *\n * Because this is a string it can contain unexpected characters\n * So, this method safely splits the className and returns that array.\n */\nexport function getClassNames(el: Element): string[] {\n let className = ''\n switch (typeof el.className) {\n case 'string':\n className = el.className\n break\n // TODO: when is this ever used?\n case 'object': // handle cases where className might be SVGAnimatedString or some other type\n className =\n (el.className && 'baseVal' in el.className ? (el.className as any).baseVal : null) ||\n el.getAttribute('class') ||\n ''\n break\n default:\n className = ''\n }\n\n return splitClassString(className)\n}\n\nexport function makeSafeText(s: string | null | undefined): string | null {\n if (isNullish(s)) {\n return null\n }\n\n return (\n trim(s)\n // scrub potentially sensitive values\n .split(/(\\s+)/)\n .filter((s) => shouldCaptureValue(s))\n .join('')\n // normalize whitespace\n .replace(/[\\r\\n]/g, ' ')\n .replace(/[ ]+/g, ' ')\n // truncate\n .substring(0, 255)\n )\n}\n\n/*\n * Get the direct text content of an element, protecting against sensitive data collection.\n * Concats textContent of each of the element's text node children; this avoids potential\n * collection of sensitive data that could happen if we used element.textContent and the\n * element had sensitive child elements, since element.textContent includes child content.\n * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).\n * @param {Element} el - element to get the text of\n * @returns {string} the element's direct text content\n */\nexport function getSafeText(el: Element): string {\n let elText = ''\n\n if (shouldCaptureElement(el) && !isSensitiveElement(el) && el.childNodes && el.childNodes.length) {\n each(el.childNodes, function (child) {\n if (isTextNode(child) && child.textContent) {\n elText += makeSafeText(child.textContent) ?? ''\n }\n })\n }\n\n return trim(elText)\n}\n\nexport function getEventTarget(e: Event): Element | null {\n // https://developer.mozilla.org/en-US/docs/Web/API/Event/target#Compatibility_notes\n if (isUndefined(e.target)) {\n return (e.srcElement as Element) || null\n } else {\n if ((e.target as HTMLElement)?.shadowRoot) {\n return (e.composedPath()[0] as Element) || null\n }\n return (e.target as Element) || null\n }\n}\n\nexport const autocaptureCompatibleElements = ['a', 'button', 'form', 'input', 'select', 'textarea', 'label']\n\n/*\n if there is no config, then all elements are allowed\n if there is a config, and there is an allow list, then only elements in the allow list are allowed\n assumes that some other code is checking this element's parents\n */\nfunction checkIfElementTreePassesElementAllowList(\n elements: Element[],\n autocaptureConfig: AutocaptureConfig | undefined\n): boolean {\n const allowlist = autocaptureConfig?.element_allowlist\n if (isUndefined(allowlist)) {\n // everything is allowed, when there is no allow list\n return true\n }\n\n // check each element in the tree\n // if any of the elements are in the allow list, then the tree is allowed\n for (const el of elements) {\n if (allowlist.some((elementType) => el.tagName.toLowerCase() === elementType)) {\n return true\n }\n }\n\n // otherwise there is an allow list and this element tree didn't match it\n return false\n}\n\n/*\n if there is no selector list (i.e. it is undefined), then any elements matches\n if there is an empty list, then no elements match\n if there is a selector list, then check it against each element provided\n */\nfunction checkIfElementsMatchCSSSelector(elements: Element[], selectorList: string[] | undefined): boolean {\n if (isUndefined(selectorList)) {\n // everything is allowed, when there is no selector list\n return true\n }\n\n for (const el of elements) {\n if (selectorList.some((selector) => el.matches(selector))) {\n return true\n }\n }\n\n return false\n}\n\nexport function getParentElement(curEl: Element): Element | false {\n const parentNode = curEl.parentNode\n if (!parentNode || !isElementNode(parentNode)) return false\n return parentNode\n}\n\nconst DEFAULT_CONTENT_IGNORELIST = ['next', 'previous', 'prev', '>', '<']\nconst MAX_CONTENT_IGNORELIST_ENTRIES = 10\n\ninterface ElementWithText {\n safeText: string\n ariaLabel: string\n}\n\nfunction shouldIgnoreByContent(\n contentIgnorelist: boolean | string[] | undefined,\n elementsWithText: ElementWithText[]\n): boolean {\n if (contentIgnorelist === false || isUndefined(contentIgnorelist)) {\n return false\n }\n\n let keywords: string[]\n if (contentIgnorelist === true) {\n keywords = DEFAULT_CONTENT_IGNORELIST\n } else if (isArray(contentIgnorelist)) {\n if (contentIgnorelist.length > MAX_CONTENT_IGNORELIST_ENTRIES) {\n logger.error(\n `[PostHog] content_ignorelist array cannot exceed ${MAX_CONTENT_IGNORELIST_ENTRIES} items. Use css_selector_ignorelist for more complex matching.`\n )\n return false\n }\n keywords = contentIgnorelist.map((k) => k.toLowerCase())\n } else {\n return false\n }\n\n return elementsWithText.some(({ safeText, ariaLabel }) => {\n return keywords.some((keyword) => safeText.includes(keyword) || ariaLabel.includes(keyword))\n })\n}\n\n// autocapture check will already filter for ph-no-capture,\n// but we include it here to protect against future changes accidentally removing that check\nconst DEFAULT_RAGE_CLICK_IGNORE_LIST = ['.ph-no-rageclick', '.ph-no-capture']\nexport function shouldCaptureRageclick(el: Element | null, _config: PostHogConfig['rageclick']) {\n if (!window || cannotCheckForAutocapture(el)) {\n return false\n }\n\n let selectorIgnoreList: string[] | boolean\n let contentIgnorelist: boolean | string[] | undefined\n if (isBoolean(_config)) {\n selectorIgnoreList = _config ? DEFAULT_RAGE_CLICK_IGNORE_LIST : false\n // For backward compatibility, don't enable content filtering for rageclick: true\n contentIgnorelist = undefined\n } else {\n selectorIgnoreList = _config?.css_selector_ignorelist ?? DEFAULT_RAGE_CLICK_IGNORE_LIST\n contentIgnorelist = _config?.content_ignorelist\n }\n\n if (selectorIgnoreList === false) {\n return false\n }\n\n // Traverse DOM once and cache element data to avoid redundant calls to getSafeText\n const { targetElementList } = getElementAndParentsForElement(el, false)\n const elementsWithText: ElementWithText[] = targetElementList.map((element) => ({\n safeText: getSafeText(element).toLowerCase(),\n ariaLabel: element.getAttribute('aria-label')?.toLowerCase().trim() || '',\n }))\n\n if (shouldIgnoreByContent(contentIgnorelist, elementsWithText)) {\n return false\n }\n\n // we don't capture if we match the ignore list\n return !checkIfElementsMatchCSSSelector(targetElementList, selectorIgnoreList)\n}\n\nconst cannotCheckForAutocapture = (el: Element | null) => {\n return !el || isTag(el, 'html') || !isElementNode(el)\n}\n\nconst getElementAndParentsForElement = (el: Element, captureOnAnyElement: false | true | undefined) => {\n if (!window || cannotCheckForAutocapture(el)) {\n return { parentIsUsefulElement: false, targetElementList: [] }\n }\n\n let parentIsUsefulElement = false\n const targetElementList: Element[] = [el]\n let curEl: Element = el\n while (curEl.parentNode && !isTag(curEl, 'body')) {\n // If element is a shadow root, we skip it\n if (isDocumentFragment(curEl.parentNode)) {\n targetElementList.push((curEl.parentNode as any).host)\n curEl = (curEl.parentNode as any).host\n continue\n }\n const parentNode = getParentElement(curEl)\n if (!parentNode) break\n if (captureOnAnyElement || autocaptureCompatibleElements.indexOf(parentNode.tagName.toLowerCase()) > -1) {\n parentIsUsefulElement = true\n } else {\n const compStyles = window.getComputedStyle(parentNode)\n if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer') {\n parentIsUsefulElement = true\n }\n }\n\n targetElementList.push(parentNode)\n curEl = parentNode\n }\n return { parentIsUsefulElement, targetElementList }\n}\n\n/*\n * Check whether a DOM event should be \"captured\" or if it may contain sensitive data\n * using a variety of heuristics.\n * @param {Element} el - element to check\n * @param {Event} event - event to check\n * @param {Object} autocaptureConfig - autocapture config\n * @param {boolean} captureOnAnyElement - whether to capture on any element, clipboard autocapture doesn't restrict to \"clickable\" elements\n * @param {string[]} allowedEventTypes - event types to capture, normally just 'click', but some autocapture types react to different events, some elements have fixed events (e.g., form has \"submit\")\n * @returns {boolean} whether the event should be captured\n */\nexport function shouldCaptureDomEvent(\n el: Element,\n event: Event,\n autocaptureConfig: AutocaptureConfig | undefined = undefined,\n captureOnAnyElement?: boolean,\n allowedEventTypes?: string[]\n): boolean {\n if (!window || cannotCheckForAutocapture(el)) {\n return false\n }\n\n if (autocaptureConfig?.url_allowlist) {\n // if the current URL is not in the allow list, don't capture\n if (!checkForURLMatches(autocaptureConfig.url_allowlist)) {\n return false\n }\n }\n\n if (autocaptureConfig?.url_ignorelist) {\n // if the current URL is in the ignore list, don't capture\n if (checkForURLMatches(autocaptureConfig.url_ignorelist)) {\n return false\n }\n }\n\n if (autocaptureConfig?.dom_event_allowlist) {\n const allowlist = autocaptureConfig.dom_event_allowlist\n if (allowlist && !allowlist.some((eventType) => event.type === eventType)) {\n return false\n }\n }\n\n const { parentIsUsefulElement, targetElementList } = getElementAndParentsForElement(el, captureOnAnyElement)\n\n if (!checkIfElementTreePassesElementAllowList(targetElementList, autocaptureConfig)) {\n return false\n }\n\n if (!checkIfElementsMatchCSSSelector(targetElementList, autocaptureConfig?.css_selector_allowlist)) {\n return false\n }\n\n const compStyles = window.getComputedStyle(el)\n if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer' && event.type === 'click') {\n return true\n }\n\n const tag = el.tagName.toLowerCase()\n switch (tag) {\n case 'html':\n return false\n case 'form':\n return (allowedEventTypes || ['submit']).indexOf(event.type) >= 0\n case 'input':\n case 'select':\n case 'textarea':\n return (allowedEventTypes || ['change', 'click']).indexOf(event.type) >= 0\n default:\n if (parentIsUsefulElement) return (allowedEventTypes || ['click']).indexOf(event.type) >= 0\n return (\n (allowedEventTypes || ['click']).indexOf(event.type) >= 0 &&\n (autocaptureCompatibleElements.indexOf(tag) > -1 || el.getAttribute('contenteditable') === 'true')\n )\n }\n}\n\n/*\n * Check whether a DOM element should be \"captured\" or if it may contain sensitive data\n * using a variety of heuristics.\n * @param {Element} el - element to check\n * @returns {boolean} whether the element should be captured\n */\nexport function shouldCaptureElement(el: Element): boolean {\n for (let curEl = el; curEl.parentNode && !isTag(curEl, 'body'); curEl = curEl.parentNode as Element) {\n const classes = getClassNames(curEl)\n if (includes(classes, 'ph-sensitive') || includes(classes, 'ph-no-capture')) {\n return false\n }\n }\n\n if (includes(getClassNames(el), 'ph-include')) {\n return true\n }\n\n // don't include hidden or password fields\n const type = (el as HTMLInputElement).type || ''\n if (isString(type)) {\n // it's possible for el.type to be a DOM element if el is a form with a child input[name=\"type\"]\n switch (type.toLowerCase()) {\n case 'hidden':\n return false\n case 'password':\n return false\n }\n }\n\n // filter out data from fields that look like sensitive fields\n const name = (el as HTMLInputElement).name || el.id || ''\n // See https://github.com/posthog/posthog-js/issues/165\n // Under specific circumstances a bug caused .replace to be called on a DOM element\n // instead of a string, removing the element from the page. Ensure this issue is mitigated.\n if (isString(name)) {\n // it's possible for el.name or el.id to be a DOM element if el is a form with a child input[name=\"name\"]\n const sensitiveNameRegex =\n /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i\n if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {\n return false\n }\n }\n\n return true\n}\n\n/*\n * Check whether a DOM element is 'sensitive' and we should only capture limited data\n * @param {Element} el - element to check\n * @returns {boolean} whether the element should be captured\n */\nexport function isSensitiveElement(el: Element): boolean {\n // don't send data from inputs or similar elements since there will always be\n // a risk of clientside javascript placing sensitive data in attributes\n const allowedInputTypes = ['button', 'checkbox', 'submit', 'reset']\n if (\n (isTag(el, 'input') && !allowedInputTypes.includes((el as HTMLInputElement).type)) ||\n isTag(el, 'select') ||\n isTag(el, 'textarea') ||\n el.getAttribute('contenteditable') === 'true'\n ) {\n return true\n }\n return false\n}\n\n// Define the core pattern for matching credit card numbers\nconst coreCCPattern = `(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})`\n// Create the Anchored version of the regex by adding '^' at the start and '$' at the end\nconst anchoredCCRegex = new RegExp(`^(?:${coreCCPattern})$`)\n// The Unanchored version is essentially the core pattern, usable as is for partial matches\nconst unanchoredCCRegex = new RegExp(coreCCPattern)\n\n// Define the core pattern for matching SSNs with optional dashes\nconst coreSSNPattern = `\\\\d{3}-?\\\\d{2}-?\\\\d{4}`\n// Create the Anchored version of the regex by adding '^' at the start and '$' at the end\nconst anchoredSSNRegex = new RegExp(`^(${coreSSNPattern})$`)\n// The Unanchored version is essentially the core pattern itself, usable for partial matches\nconst unanchoredSSNRegex = new RegExp(`(${coreSSNPattern})`)\n\n/*\n * Check whether a string value should be \"captured\" or if it may contain sensitive data\n * using a variety of heuristics.\n * @param {string} value - string value to check\n * @param {boolean} anchorRegexes - whether to anchor the regexes to the start and end of the string\n * @returns {boolean} whether the element should be captured\n */\nexport function shouldCaptureValue(value: string, anchorRegexes = true): boolean {\n if (isNullish(value)) {\n return false\n }\n\n if (isString(value)) {\n value = trim(value)\n\n // check to see if input value looks like a credit card number\n // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html\n const ccRegex = anchorRegexes ? anchoredCCRegex : unanchoredCCRegex\n if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {\n return false\n }\n\n // check to see if input value looks like a social security number\n const ssnRegex = anchorRegexes ? anchoredSSNRegex : unanchoredSSNRegex\n if (ssnRegex.test(value)) {\n return false\n }\n }\n\n return true\n}\n\n/*\n * Check whether an attribute name is an Angular style attr (either _ngcontent or _nghost)\n * These update on each build and lead to noise in the element chain\n * More details on the attributes here: https://angular.io/guide/view-encapsulation\n * @param {string} attributeName - string value to check\n * @returns {boolean} whether the element is an angular tag\n */\nexport function isAngularStyleAttr(attributeName: string): boolean {\n if (isString(attributeName)) {\n return attributeName.substring(0, 10) === '_ngcontent' || attributeName.substring(0, 7) === '_nghost'\n }\n return false\n}\n\n/*\n * Iterate through children of a target element looking for span tags\n * and return the text content of the span tags, separated by spaces,\n * along with the direct text content of the target element\n * @param {Element} target - element to check\n * @returns {string} text content of the target element and its child span tags\n */\nexport function getDirectAndNestedSpanText(target: Element): string {\n let text = getSafeText(target)\n text = `${text} ${getNestedSpanText(target)}`.trim()\n return shouldCaptureValue(text) ? text : ''\n}\n\n/*\n * Iterate through children of a target element looking for span tags\n * and return the text content of the span tags, separated by spaces\n * @param {Element} target - element to check\n * @returns {string} text content of span tags\n */\nexport function getNestedSpanText(target: Element): string {\n let text = ''\n if (target && target.childNodes && target.childNodes.length) {\n each(target.childNodes, function (child) {\n if (child && child.tagName?.toLowerCase() === 'span') {\n try {\n const spanText = getSafeText(child)\n text = `${text} ${spanText}`.trim()\n\n if (child.childNodes && child.childNodes.length) {\n text = `${text} ${getNestedSpanText(child)}`.trim()\n }\n } catch (e) {\n logger.error('[AutoCapture]', e)\n }\n }\n })\n }\n return text\n}\n\n/*\nBack in the day storing events in Postgres we use Elements for autocapture events.\nNow we're using elements_chain. We used to do this parsing/processing during ingestion.\nThis code is just copied over from ingestion, but we should optimize it\nto create elements_chain string directly.\n*/\nexport function getElementsChainString(elements: Properties[]): string {\n return elementsToString(extractElements(elements))\n}\n\n// This interface is called 'Element' in plugin-scaffold https://github.com/PostHog/plugin-scaffold/blob/b07d3b879796ecc7e22deb71bf627694ba05386b/src/types.ts#L200\n// However 'Element' is a DOM Element when run in the browser, so we have to rename it\ninterface PHElement {\n text?: string\n tag_name?: string\n href?: string\n attr_id?: string\n attr_class?: string[]\n nth_child?: number\n nth_of_type?: number\n attributes?: Record\n event_id?: number\n order?: number\n group_id?: number\n}\n\nfunction escapeQuotes(input: string): string {\n return input.replace(/\"|\\\\\"/g, '\\\\\"')\n}\n\nfunction elementsToString(elements: PHElement[]): string {\n const ret = elements.map((element) => {\n let el_string = ''\n if (element.tag_name) {\n el_string += element.tag_name\n }\n if (element.attr_class) {\n element.attr_class.sort()\n for (const single_class of element.attr_class) {\n el_string += `.${single_class.replace(/\"/g, '')}`\n }\n }\n const attributes: Record = {\n ...(element.text ? { text: element.text } : {}),\n 'nth-child': element.nth_child ?? 0,\n 'nth-of-type': element.nth_of_type ?? 0,\n ...(element.href ? { href: element.href } : {}),\n ...(element.attr_id ? { attr_id: element.attr_id } : {}),\n ...element.attributes,\n }\n const sortedAttributes: Record = {}\n entries(attributes)\n .sort(([a], [b]) => a.localeCompare(b))\n .forEach(\n ([key, value]) => (sortedAttributes[escapeQuotes(key.toString())] = escapeQuotes(value.toString()))\n )\n el_string += ':'\n el_string += entries(sortedAttributes)\n .map(([key, value]) => `${key}=\"${value}\"`)\n .join('')\n return el_string\n })\n return ret.join(';')\n}\n\nfunction extractElements(elements: Properties[]): PHElement[] {\n return elements.map((el) => {\n const response = {\n text: el['$el_text']?.slice(0, 400),\n tag_name: el['tag_name'],\n href: el['attr__href']?.slice(0, 2048),\n attr_class: extractAttrClass(el),\n attr_id: el['attr__id'],\n nth_child: el['nth_child'],\n nth_of_type: el['nth_of_type'],\n attributes: {} as { [id: string]: any },\n }\n\n entries(el)\n .filter(([key]) => key.indexOf('attr__') === 0)\n .forEach(([key, value]) => (response.attributes[key] = value))\n return response\n })\n}\n\nfunction extractAttrClass(el: Properties): PHElement['attr_class'] {\n const attr_class = el['attr__class']\n if (!attr_class) {\n return undefined\n } else if (isArray(attr_class)) {\n return attr_class\n } else {\n return splitClassString(attr_class)\n }\n}\n", "// Naive rage click implementation: If mouse has not moved further than thresholdPx\n// over clickCount clicks with max timeoutMs between clicks, it's\n// counted as a rage click\n\nimport { isObject } from '@posthog/core'\nimport { RageclickConfig } from '../types'\n\nconst DEFAULT_THRESHOLD_PX = 30\nconst DEFAULT_TIMEOUT_MS = 1000\nconst DEFAULT_CLICK_COUNT = 3\n\nexport default class RageClick {\n clicks: { x: number; y: number; timestamp: number }[]\n\n thresholdPx: number\n timeoutMs: number\n clickCount: number\n disabled: boolean\n\n constructor(rageclickConfig: RageclickConfig | boolean) {\n this.disabled = rageclickConfig === false\n const conf = isObject(rageclickConfig) ? rageclickConfig : {}\n\n this.thresholdPx = conf.threshold_px || DEFAULT_THRESHOLD_PX\n this.timeoutMs = conf.timeout_ms || DEFAULT_TIMEOUT_MS\n this.clickCount = conf.click_count || DEFAULT_CLICK_COUNT\n\n this.clicks = []\n }\n\n isRageClick(x: number, y: number, timestamp: number): boolean {\n if (this.disabled) {\n return false\n }\n\n const lastClick = this.clicks[this.clicks.length - 1]\n if (\n lastClick &&\n Math.abs(x - lastClick.x) + Math.abs(y - lastClick.y) < this.thresholdPx &&\n timestamp - lastClick.timestamp < this.timeoutMs\n ) {\n this.clicks.push({ x, y, timestamp })\n\n if (this.clicks.length === this.clickCount) {\n return true\n }\n } else {\n this.clicks = [{ x, y, timestamp }]\n }\n\n return false\n }\n}\n", "import { addEventListener, each, extend } from './utils'\nimport {\n autocaptureCompatibleElements,\n getClassNames,\n getDirectAndNestedSpanText,\n getElementsChainString,\n getEventTarget,\n getSafeText,\n isAngularStyleAttr,\n isSensitiveElement,\n makeSafeText,\n shouldCaptureDomEvent,\n shouldCaptureElement,\n shouldCaptureRageclick,\n shouldCaptureValue,\n splitClassString,\n} from './autocapture-utils'\n\nimport RageClick from './extensions/rageclick'\nimport { AutocaptureConfig, EventName, Properties, RemoteConfig } from './types'\nimport { PostHog } from './posthog-core'\nimport { AUTOCAPTURE_DISABLED_SERVER_SIDE } from './constants'\n\nimport { isBoolean, isFunction, isNull, isObject } from '@posthog/core'\nimport { createLogger } from './utils/logger'\nimport { document, window } from './utils/globals'\nimport { convertToURL } from './utils/request-utils'\nimport { isDocumentFragment, isElementNode, isTag, isTextNode } from './utils/element-utils'\nimport { includes } from '@posthog/core'\nimport type { Extension } from './extensions/types'\n\nconst COPY_AUTOCAPTURE_EVENT = '$copy_autocapture'\n\nconst logger = createLogger('[AutoCapture]')\n\nfunction limitText(length: number, text: string): string {\n if (text.length > length) {\n return text.slice(0, length) + '...'\n }\n return text\n}\n\nexport function getAugmentPropertiesFromElement(elem: Element): Properties {\n const shouldCaptureEl = shouldCaptureElement(elem)\n if (!shouldCaptureEl) {\n return {}\n }\n\n const props: Properties = {}\n\n each(elem.attributes, function (attr: Attr) {\n if (attr.name && attr.name.indexOf('data-ph-capture-attribute') === 0) {\n const propertyKey = attr.name.replace('data-ph-capture-attribute-', '')\n const propertyValue = attr.value\n if (propertyKey && propertyValue && shouldCaptureValue(propertyValue)) {\n props[propertyKey] = propertyValue\n }\n }\n })\n\n return props\n}\n\nexport function previousElementSibling(el: Element): Element | null {\n if (el.previousElementSibling) {\n return el.previousElementSibling\n }\n let _el: Element | null = el\n do {\n _el = _el.previousSibling as Element | null // resolves to ChildNode->Node, which is Element's parent class\n } while (_el && !isElementNode(_el))\n return _el\n}\n\nexport function getDefaultProperties(eventType: string): Properties {\n return {\n $event_type: eventType,\n $ce_version: 1,\n }\n}\n\nexport function getPropertiesFromElement(\n elem: Element,\n maskAllAttributes: boolean,\n maskText: boolean,\n elementAttributeIgnorelist: string[] | undefined\n): Properties {\n const tag_name = elem.tagName.toLowerCase()\n const props: Properties = {\n tag_name: tag_name,\n }\n if (autocaptureCompatibleElements.indexOf(tag_name) > -1 && !maskText) {\n if (tag_name.toLowerCase() === 'a' || tag_name.toLowerCase() === 'button') {\n props['$el_text'] = limitText(1024, getDirectAndNestedSpanText(elem))\n } else {\n props['$el_text'] = limitText(1024, getSafeText(elem))\n }\n }\n\n const classes = getClassNames(elem)\n if (classes.length > 0)\n props['classes'] = classes.filter(function (c) {\n return c !== ''\n })\n\n // capture the deny list here because this not-a-class class makes it tricky to use this.config in the function below\n each(elem.attributes, function (attr: Attr) {\n // Only capture attributes we know are safe\n if (isSensitiveElement(elem) && ['name', 'id', 'class', 'aria-label'].indexOf(attr.name) === -1) return\n\n if (elementAttributeIgnorelist?.includes(attr.name)) return\n\n if (!maskAllAttributes && shouldCaptureValue(attr.value) && !isAngularStyleAttr(attr.name)) {\n let value = attr.value\n if (attr.name === 'class') {\n // html attributes can _technically_ contain linebreaks,\n // but we're very intolerant of them in the class string,\n // so we strip them.\n value = splitClassString(value).join(' ')\n }\n props['attr__' + attr.name] = limitText(1024, value)\n }\n })\n\n let nthChild = 1\n let nthOfType = 1\n let currentElem: Element | null = elem\n while ((currentElem = previousElementSibling(currentElem))) {\n // eslint-disable-line no-cond-assign\n nthChild++\n if (currentElem.tagName === elem.tagName) {\n nthOfType++\n }\n }\n props['nth_child'] = nthChild\n props['nth_of_type'] = nthOfType\n\n return props\n}\n\nexport function autocapturePropertiesForElement(\n target: Element,\n {\n e,\n maskAllElementAttributes,\n maskAllText,\n elementAttributeIgnoreList,\n elementsChainAsString,\n }: {\n e: Event\n maskAllElementAttributes: boolean\n maskAllText: boolean\n elementAttributeIgnoreList?: string[] | undefined\n elementsChainAsString: boolean\n }\n): { props: Properties; explicitNoCapture?: boolean } {\n const targetElementList = [target]\n let curEl = target\n while (curEl.parentNode && !isTag(curEl, 'body')) {\n if (isDocumentFragment(curEl.parentNode)) {\n targetElementList.push((curEl.parentNode as any).host)\n curEl = (curEl.parentNode as any).host\n continue\n }\n targetElementList.push(curEl.parentNode as Element)\n curEl = curEl.parentNode as Element\n }\n\n const elementsJson: Properties[] = []\n const autocaptureAugmentProperties: Properties = {}\n let href: string | false = false\n let explicitNoCapture = false\n\n each(targetElementList, (el) => {\n const shouldCaptureEl = shouldCaptureElement(el)\n\n // if the element or a parent element is an anchor tag\n // include the href as a property\n if (el.tagName.toLowerCase() === 'a') {\n href = el.getAttribute('href')\n href = shouldCaptureEl && href && shouldCaptureValue(href) && href\n }\n\n // allow users to programmatically prevent capturing of elements by adding class 'ph-no-capture'\n const classes = getClassNames(el)\n if (includes(classes, 'ph-no-capture')) {\n explicitNoCapture = true\n }\n\n elementsJson.push(\n getPropertiesFromElement(el, maskAllElementAttributes, maskAllText, elementAttributeIgnoreList)\n )\n\n const augmentProperties = getAugmentPropertiesFromElement(el)\n extend(autocaptureAugmentProperties, augmentProperties)\n })\n\n if (explicitNoCapture) {\n return { props: {}, explicitNoCapture }\n }\n\n if (!maskAllText) {\n // if the element is a button or anchor tag get the span text from any\n // children and include it as/with the text property on the parent element\n if (target.tagName.toLowerCase() === 'a' || target.tagName.toLowerCase() === 'button') {\n elementsJson[0]['$el_text'] = getDirectAndNestedSpanText(target)\n } else {\n elementsJson[0]['$el_text'] = getSafeText(target)\n }\n }\n\n let externalHref: string | undefined\n if (href) {\n elementsJson[0]['attr__href'] = href\n const hrefHost = convertToURL(href)?.host\n const locationHost = window?.location?.host\n if (hrefHost && locationHost && hrefHost !== locationHost) {\n externalHref = href\n }\n }\n\n const props = extend(\n getDefaultProperties(e.type),\n // Sending \"$elements\" is deprecated. Only one client on US cloud uses this.\n !elementsChainAsString ? { $elements: elementsJson } : {},\n // Always send $elements_chain, as it's needed downstream in site app filtering\n { $elements_chain: getElementsChainString(elementsJson) },\n elementsJson[0]?.['$el_text'] ? { $el_text: elementsJson[0]?.['$el_text'] } : {},\n externalHref && e.type === 'click' ? { $external_click_url: externalHref } : {},\n autocaptureAugmentProperties\n )\n\n return { props }\n}\n\nexport class Autocapture implements Extension {\n instance: PostHog\n _initialized: boolean = false\n _isDisabledServerSide: boolean | null = null\n _elementSelectors: Set | null\n rageclicks: RageClick\n _elementsChainAsString = false\n\n constructor(instance: PostHog) {\n this.instance = instance\n this.rageclicks = new RageClick(instance.config.rageclick)\n this._elementSelectors = null\n }\n\n initialize() {\n this.startIfEnabled()\n }\n\n private get _config(): AutocaptureConfig {\n const config = isObject(this.instance.config.autocapture) ? this.instance.config.autocapture : {}\n // precompile the regex\n config.url_allowlist = config.url_allowlist?.map((url) => new RegExp(url))\n config.url_ignorelist = config.url_ignorelist?.map((url) => new RegExp(url))\n return config\n }\n\n _addDomEventHandlers(): void {\n if (!this.isBrowserSupported()) {\n logger.info('Disabling Automatic Event Collection because this browser is not supported')\n return\n }\n\n if (!window || !document) {\n return\n }\n\n const handler = (e: Event) => {\n e = e || window?.event\n try {\n this._captureEvent(e)\n } catch (error) {\n logger.error('Failed to capture event', error)\n }\n }\n\n addEventListener(document, 'submit', handler, { capture: true })\n addEventListener(document, 'change', handler, { capture: true })\n addEventListener(document, 'click', handler, { capture: true })\n\n if (this._config.capture_copied_text) {\n const copiedTextHandler = (e: Event) => {\n e = e || window?.event\n this._captureEvent(e, COPY_AUTOCAPTURE_EVENT)\n }\n\n addEventListener(document, 'copy', copiedTextHandler, { capture: true })\n addEventListener(document, 'cut', copiedTextHandler, { capture: true })\n }\n }\n\n public startIfEnabled() {\n if (this.isEnabled && !this._initialized) {\n this._addDomEventHandlers()\n this._initialized = true\n }\n }\n\n public onRemoteConfig(response: RemoteConfig) {\n if (response.elementsChainAsString) {\n this._elementsChainAsString = response.elementsChainAsString\n }\n\n // NOTE: Unlike other extensions (heatmaps, web-vitals, etc.), we intentionally\n // DO NOT guard against missing autocapture_opt_out key here. Autocapture uses\n // a \"wait for server, then enable unless explicitly opted out\" model:\n // - Before remote config: autocapture disabled (isEnabled returns false)\n // - After remote config: enabled unless autocapture_opt_out is explicitly true\n // Missing/undefined key → !!undefined = false → autocapture enabled\n // This is intentional and different from opt-in features like heatmaps.\n if (this.instance.persistence) {\n this.instance.persistence.register({\n [AUTOCAPTURE_DISABLED_SERVER_SIDE]: !!response['autocapture_opt_out'],\n })\n }\n // store this in-memory in case persistence is disabled\n this._isDisabledServerSide = !!response['autocapture_opt_out']\n this.startIfEnabled()\n }\n\n public setElementSelectors(selectors: Set): void {\n this._elementSelectors = selectors\n }\n\n public getElementSelectors(element: Element | null): string[] | null {\n const elementSelectors: string[] = []\n\n this._elementSelectors?.forEach((selector) => {\n const matchedElements = document?.querySelectorAll(selector)\n matchedElements?.forEach((matchedElement: Element) => {\n if (element === matchedElement) {\n elementSelectors.push(selector)\n }\n })\n })\n\n return elementSelectors\n }\n\n public get isEnabled(): boolean {\n const persistedServerDisabled = this.instance.persistence?.props[AUTOCAPTURE_DISABLED_SERVER_SIDE]\n const memoryDisabled = this._isDisabledServerSide\n\n if (isNull(memoryDisabled) && !isBoolean(persistedServerDisabled) && !this.instance._shouldDisableFlags()) {\n // We only enable if we know that the server has not disabled it (unless /flags is disabled)\n return false\n }\n\n const disabledServer = this._isDisabledServerSide ?? !!persistedServerDisabled\n const disabledClient = !this.instance.config.autocapture\n return !disabledClient && !disabledServer\n }\n\n private _captureEvent(e: Event, eventName: EventName = '$autocapture'): boolean | void {\n if (!this.isEnabled) {\n return\n }\n\n /*** Don't mess with this code without running IE8 tests on it ***/\n let target = getEventTarget(e)\n if (isTextNode(target)) {\n // defeat Safari bug (see: http://www.quirksmode.org/js/events_properties.html)\n target = (target.parentNode || null) as Element | null\n }\n\n if (eventName === '$autocapture' && e.type === 'click' && e instanceof MouseEvent) {\n if (\n !!this.instance.config.rageclick &&\n this.rageclicks?.isRageClick(e.clientX, e.clientY, e.timeStamp || new Date().getTime())\n ) {\n if (shouldCaptureRageclick(target, this.instance.config.rageclick)) {\n this._captureEvent(e, '$rageclick')\n }\n }\n }\n\n const isCopyAutocapture = eventName === COPY_AUTOCAPTURE_EVENT\n if (\n target &&\n shouldCaptureDomEvent(\n target,\n e,\n this._config,\n // mostly this method cares about the target element, but in the case of copy events,\n // we want some of the work this check does without insisting on the target element's type\n isCopyAutocapture,\n // we also don't want to restrict copy checks to clicks,\n // so we pass that knowledge in here, rather than add the logic inside the check\n isCopyAutocapture ? ['copy', 'cut'] : undefined\n )\n ) {\n const { props, explicitNoCapture } = autocapturePropertiesForElement(target, {\n e,\n maskAllElementAttributes: this.instance.config.mask_all_element_attributes,\n maskAllText: this.instance.config.mask_all_text,\n elementAttributeIgnoreList: this._config.element_attribute_ignorelist,\n elementsChainAsString: this._elementsChainAsString,\n })\n\n if (explicitNoCapture) {\n return false\n }\n\n const elementSelectors = this.getElementSelectors(target)\n if (elementSelectors && elementSelectors.length > 0) {\n props['$element_selectors'] = elementSelectors\n }\n\n if (eventName === COPY_AUTOCAPTURE_EVENT) {\n // you can't read the data from the clipboard event,\n // but you can guess that you can read it from the window's current selection\n const selectedContent = makeSafeText(window?.getSelection()?.toString())\n const clipType = (e as ClipboardEvent).type || 'clipboard'\n if (!selectedContent) {\n return false\n }\n props['$selected_content'] = selectedContent\n props['$copy_type'] = clipType\n }\n\n this.instance.capture(eventName, props)\n return true\n }\n }\n\n isBrowserSupported(): boolean {\n return isFunction(document?.querySelectorAll)\n }\n}\n", "import { assignableWindow, window } from '../../utils/globals'\nimport { PostHog } from '../../posthog-core'\nimport { ExceptionAutoCaptureConfig, RemoteConfig } from '../../types'\n\nimport { createLogger } from '../../utils/logger'\nimport { EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE } from '../../constants'\nimport { isUndefined, BucketedRateLimiter, isObject } from '@posthog/core'\nimport { ErrorTracking } from '@posthog/core'\n\nconst logger = createLogger('[ExceptionAutocapture]')\n\nexport class ExceptionObserver {\n private _instance: PostHog\n private _rateLimiter: BucketedRateLimiter\n private _remoteEnabled: boolean | undefined\n private _config: Required\n private _unwrapOnError: (() => void) | undefined\n private _unwrapUnhandledRejection: (() => void) | undefined\n private _unwrapConsoleError: (() => void) | undefined\n\n constructor(instance: PostHog) {\n this._instance = instance\n this._remoteEnabled = !!this._instance.persistence?.props[EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE]\n\n // by default captures ten exceptions before rate limiting by exception type\n // refills at a rate of one token / 10 second period\n // e.g. will capture 1 exception rate limited exception every 10 seconds until burst ends\n this._rateLimiter = new BucketedRateLimiter({\n refillRate: this._instance.config.error_tracking.__exceptionRateLimiterRefillRate ?? 1,\n bucketSize: this._instance.config.error_tracking.__exceptionRateLimiterBucketSize ?? 10,\n refillInterval: 10000, // ten seconds in milliseconds,\n _logger: logger,\n })\n\n this._config = this._requiredConfig()\n this.startIfEnabledOrStop()\n }\n\n private _requiredConfig(): Required {\n const providedConfig = this._instance.config.capture_exceptions\n let config = {\n capture_unhandled_errors: false,\n capture_unhandled_rejections: false,\n capture_console_errors: false,\n }\n\n if (isObject(providedConfig)) {\n config = { ...config, ...providedConfig }\n } else if (isUndefined(providedConfig) ? this._remoteEnabled : providedConfig) {\n config = { ...config, capture_unhandled_errors: true, capture_unhandled_rejections: true }\n }\n\n return config\n }\n\n public get isEnabled(): boolean {\n return (\n this._config.capture_console_errors ||\n this._config.capture_unhandled_errors ||\n this._config.capture_unhandled_rejections\n )\n }\n\n startIfEnabledOrStop(): void {\n if (this.isEnabled) {\n logger.info('enabled')\n this._stopCapturing()\n this._loadScript(this._startCapturing)\n } else {\n this._stopCapturing()\n }\n }\n\n private _loadScript(cb: () => void): void {\n if (assignableWindow.__PosthogExtensions__?.errorWrappingFunctions) {\n // already loaded\n cb()\n }\n\n assignableWindow.__PosthogExtensions__?.loadExternalDependency?.(\n this._instance,\n 'exception-autocapture',\n (err) => {\n if (err) {\n return logger.error('failed to load script', err)\n }\n cb()\n }\n )\n }\n\n private _startCapturing = () => {\n if (!window || !this.isEnabled || !assignableWindow.__PosthogExtensions__?.errorWrappingFunctions) {\n return\n }\n\n const wrapOnError = assignableWindow.__PosthogExtensions__.errorWrappingFunctions.wrapOnError\n const wrapUnhandledRejection =\n assignableWindow.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection\n const wrapConsoleError = assignableWindow.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError\n\n try {\n if (!this._unwrapOnError && this._config.capture_unhandled_errors) {\n this._unwrapOnError = wrapOnError(this.captureException.bind(this))\n }\n if (!this._unwrapUnhandledRejection && this._config.capture_unhandled_rejections) {\n this._unwrapUnhandledRejection = wrapUnhandledRejection(this.captureException.bind(this))\n }\n if (!this._unwrapConsoleError && this._config.capture_console_errors) {\n this._unwrapConsoleError = wrapConsoleError(this.captureException.bind(this))\n }\n } catch (e) {\n logger.error('failed to start', e)\n this._stopCapturing()\n }\n }\n\n private _stopCapturing() {\n this._unwrapOnError?.()\n this._unwrapOnError = undefined\n\n this._unwrapUnhandledRejection?.()\n this._unwrapUnhandledRejection = undefined\n\n this._unwrapConsoleError?.()\n this._unwrapConsoleError = undefined\n }\n\n onRemoteConfig(response: RemoteConfig) {\n if (!('autocaptureExceptions' in response)) {\n return\n }\n\n const autocaptureExceptionsResponse = response.autocaptureExceptions\n\n // store this in-memory in case persistence is disabled\n this._remoteEnabled = !!autocaptureExceptionsResponse || false\n\n if (this._instance.persistence) {\n this._instance.persistence.register({\n [EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE]: this._remoteEnabled,\n })\n }\n\n this._config = this._requiredConfig()\n this.startIfEnabledOrStop()\n }\n\n onConfigChange() {\n this._config = this._requiredConfig()\n }\n\n captureException(errorProperties: ErrorTracking.ErrorProperties) {\n const exceptionType = errorProperties?.$exception_list?.[0]?.type ?? 'Exception'\n const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType)\n\n if (isRateLimited) {\n logger.info('Skipping exception capture because of client rate limiting.', {\n exception: exceptionType,\n })\n return\n }\n\n this._instance.exceptions?.sendExceptionEvent(errorProperties)\n }\n}\n", "// import { patch } from 'rrweb/typings/utils'\n// copied from https://github.com/rrweb-io/rrweb/blob/8aea5b00a4dfe5a6f59bd2ae72bb624f45e51e81/packages/rrweb/src/utils.ts#L129\n// which was copied from https://github.com/getsentry/sentry-javascript/blob/b2109071975af8bf0316d3b5b38f519bdaf5dc15/packages/utils/src/object.ts\nimport { isFunction } from '@posthog/core'\n\nexport function patch(\n source: { [key: string]: any },\n name: string,\n replacement: (...args: unknown[]) => unknown\n): () => void {\n try {\n if (!(name in source)) {\n return () => {\n //\n }\n }\n\n const original = source[name] as () => unknown\n const wrapped = replacement(original)\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 (isFunction(wrapped)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n wrapped.prototype = wrapped.prototype || {}\n Object.defineProperties(wrapped, {\n __posthog_wrapped__: {\n enumerable: false,\n value: true,\n },\n })\n }\n\n source[name] = wrapped\n\n return () => {\n source[name] = original\n }\n } catch {\n return () => {\n //\n }\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\n}\n", "import { PostHog } from '../posthog-core'\nimport { assignableWindow } from '../utils/globals'\nimport { createLogger } from '../utils/logger'\nimport { isUndefined } from '@posthog/core'\nimport type { Extension } from './types'\n\nconst logger = createLogger('[TracingHeaders]')\n\nexport class TracingHeaders implements Extension {\n private _restoreXHRPatch: (() => void) | undefined = undefined\n private _restoreFetchPatch: (() => void) | undefined = undefined\n\n constructor(private readonly _instance: PostHog) {}\n\n initialize() {\n this.startIfEnabledOrStop()\n }\n\n private _loadScript(cb: () => void): void {\n if (assignableWindow.__PosthogExtensions__?.tracingHeadersPatchFns) {\n // already loaded\n cb()\n }\n\n assignableWindow.__PosthogExtensions__?.loadExternalDependency?.(this._instance, 'tracing-headers', (err) => {\n if (err) {\n return logger.error('failed to load script', err)\n }\n cb()\n })\n }\n public startIfEnabledOrStop() {\n if (this._instance.config.__add_tracing_headers) {\n this._loadScript(this._startCapturing)\n } else {\n this._restoreXHRPatch?.()\n this._restoreFetchPatch?.()\n // we don't want to call these twice so we reset them\n this._restoreXHRPatch = undefined\n this._restoreFetchPatch = undefined\n }\n }\n\n private _startCapturing = () => {\n if (isUndefined(this._restoreXHRPatch)) {\n assignableWindow.__PosthogExtensions__?.tracingHeadersPatchFns?._patchXHR(\n this._instance.config.__add_tracing_headers || [],\n this._instance.get_distinct_id(),\n this._instance.sessionManager\n )\n }\n if (isUndefined(this._restoreFetchPatch)) {\n assignableWindow.__PosthogExtensions__?.tracingHeadersPatchFns?._patchFetch(\n this._instance.config.__add_tracing_headers || [],\n this._instance.get_distinct_id(),\n this._instance.sessionManager\n )\n }\n }\n}\n", "import { PostHog } from '../../posthog-core'\nimport { PostHogConfig, RemoteConfig, SupportedWebVitalsMetrics } from '../../types'\nimport { createLogger } from '../../utils/logger'\nimport { isBoolean, isNullish, isNumber, isUndefined, isObject } from '@posthog/core'\nimport { WEB_VITALS_ALLOWED_METRICS, WEB_VITALS_ENABLED_SERVER_SIDE } from '../../constants'\nimport { assignableWindow, window, location } from '../../utils/globals'\nimport { maskQueryParams } from '../../utils/request-utils'\nimport { PERSONAL_DATA_CAMPAIGN_PARAMS, MASKED } from '../../utils/event-utils'\n\nconst logger = createLogger('[Web Vitals]')\n\ntype WebVitalsMetricCallback = (metric: any) => void\n\nexport const DEFAULT_FLUSH_TO_CAPTURE_TIMEOUT_MILLISECONDS = 5000\nconst ONE_MINUTE_IN_MILLIS = 60 * 1000\nexport const FIFTEEN_MINUTES_IN_MILLIS = 15 * ONE_MINUTE_IN_MILLIS\n\ntype WebVitalsEventBuffer = { url: string | undefined; metrics: any[]; firstMetricTimestamp: number | undefined }\n\nexport class WebVitalsAutocapture {\n private _enabledServerSide: boolean = false\n private _initialized = false\n\n private _buffer: WebVitalsEventBuffer = { url: undefined, metrics: [], firstMetricTimestamp: undefined }\n private _delayedFlushTimer: ReturnType | undefined\n\n constructor(private readonly _instance: PostHog) {\n this._enabledServerSide = !!this._instance.persistence?.props[WEB_VITALS_ENABLED_SERVER_SIDE]\n\n this.startIfEnabled()\n }\n\n /** Shorthand for performance config to reduce bundle size */\n private get _perfConfig(): PostHogConfig['capture_performance'] {\n return this._instance.config.capture_performance\n }\n\n public get allowedMetrics(): SupportedWebVitalsMetrics[] {\n const clientConfigMetricAllowList: SupportedWebVitalsMetrics[] | undefined = isObject(this._perfConfig)\n ? this._perfConfig?.web_vitals_allowed_metrics\n : undefined\n return !isNullish(clientConfigMetricAllowList)\n ? clientConfigMetricAllowList\n : this._instance.persistence?.props[WEB_VITALS_ALLOWED_METRICS] || ['CLS', 'FCP', 'INP', 'LCP']\n }\n\n public get flushToCaptureTimeoutMs(): number {\n const clientConfig: number | undefined = isObject(this._perfConfig)\n ? this._perfConfig.web_vitals_delayed_flush_ms\n : undefined\n return clientConfig || DEFAULT_FLUSH_TO_CAPTURE_TIMEOUT_MILLISECONDS\n }\n\n public get useAttribution(): boolean {\n const clientConfig: boolean | undefined = isObject(this._perfConfig)\n ? this._perfConfig.web_vitals_attribution\n : undefined\n return clientConfig ?? false\n }\n\n public get _maxAllowedValue(): number {\n const configured =\n isObject(this._perfConfig) && isNumber(this._perfConfig.__web_vitals_max_value)\n ? this._perfConfig.__web_vitals_max_value\n : FIFTEEN_MINUTES_IN_MILLIS\n // you can set to 0 to disable the check or any value over ten seconds\n // 1 milli to 1 minute will be set to 15 minutes, cos that would be a silly low maximum\n return 0 < configured && configured <= ONE_MINUTE_IN_MILLIS ? FIFTEEN_MINUTES_IN_MILLIS : configured\n }\n\n public get isEnabled(): boolean {\n // Always disable web vitals if we're not on http or https\n const protocol = location?.protocol\n if (protocol !== 'http:' && protocol !== 'https:') {\n logger.info('Web Vitals are disabled on non-http/https protocols')\n return false\n }\n\n // Otherwise, check config\n const clientConfig = isObject(this._perfConfig)\n ? this._perfConfig.web_vitals\n : isBoolean(this._perfConfig)\n ? this._perfConfig\n : undefined\n return isBoolean(clientConfig) ? clientConfig : this._enabledServerSide\n }\n\n public startIfEnabled(): void {\n if (this.isEnabled && !this._initialized) {\n logger.info('enabled, starting...')\n this._loadScript(this._startCapturing)\n }\n }\n\n public onRemoteConfig(response: RemoteConfig) {\n if (!('capturePerformance' in response)) {\n return\n }\n\n const webVitalsOptIn = isObject(response.capturePerformance) && !!response.capturePerformance.web_vitals\n\n const allowedMetrics = isObject(response.capturePerformance)\n ? response.capturePerformance.web_vitals_allowed_metrics\n : undefined\n\n if (this._instance.persistence) {\n this._instance.persistence.register({\n [WEB_VITALS_ENABLED_SERVER_SIDE]: webVitalsOptIn,\n })\n\n this._instance.persistence.register({\n [WEB_VITALS_ALLOWED_METRICS]: allowedMetrics,\n })\n }\n // store this in-memory in case persistence is disabled\n this._enabledServerSide = webVitalsOptIn\n\n this.startIfEnabled()\n }\n\n private _loadScript(cb: () => void): void {\n if (assignableWindow.__PosthogExtensions__?.postHogWebVitalsCallbacks) {\n // already loaded\n cb()\n return\n }\n\n const kind = this.useAttribution ? 'web-vitals-with-attribution' : 'web-vitals'\n\n assignableWindow.__PosthogExtensions__?.loadExternalDependency?.(this._instance, kind, (err) => {\n if (err) {\n logger.error('failed to load script', err)\n return\n }\n\n cb()\n })\n }\n\n private _currentURL(): string | undefined {\n const href = window ? window.location.href : undefined\n if (!href) {\n logger.error('Could not determine current URL')\n return undefined\n }\n\n // mask url query params\n const maskPersonalDataProperties = this._instance.config.mask_personal_data_properties\n const customPersonalDataProperties = this._instance.config.custom_personal_data_properties\n\n const paramsToMask = maskPersonalDataProperties\n ? [...PERSONAL_DATA_CAMPAIGN_PARAMS, ...(customPersonalDataProperties || [])]\n : []\n\n return maskQueryParams(href, paramsToMask, MASKED)\n }\n\n private _flushToCapture = () => {\n clearTimeout(this._delayedFlushTimer)\n if (this._buffer.metrics.length === 0) {\n return\n }\n\n this._instance.capture(\n '$web_vitals',\n this._buffer.metrics.reduce(\n (acc, metric) => ({\n ...acc,\n // the entire event so we can use it in the future e.g. includes google's rating\n [`$web_vitals_${metric.name}_event`]: { ...metric },\n [`$web_vitals_${metric.name}_value`]: metric.value,\n }),\n {}\n )\n )\n this._buffer = { url: undefined, metrics: [], firstMetricTimestamp: undefined }\n }\n\n private _addToBuffer = (metric: any) => {\n const sessionIds = this._instance.sessionManager?.checkAndGetSessionAndWindowId(true)\n if (isUndefined(sessionIds)) {\n logger.error('Could not read session ID. Dropping metrics!')\n return\n }\n\n this._buffer = this._buffer || { url: undefined, metrics: [], firstMetricTimestamp: undefined }\n\n const $currentUrl = this._currentURL()\n if (isUndefined($currentUrl)) {\n return\n }\n\n if (isNullish(metric?.name) || isNullish(metric?.value)) {\n logger.error('Invalid metric received', metric)\n return\n }\n\n // we observe some very large values sometimes, we'll ignore them\n // since the likelihood of LCP > 1 hour being correct is very low\n if (this._maxAllowedValue && metric.value >= this._maxAllowedValue) {\n logger.error('Ignoring metric with value >= ' + this._maxAllowedValue, metric)\n return\n }\n\n const urlHasChanged = this._buffer.url !== $currentUrl\n\n if (urlHasChanged) {\n // we need to send what we have\n this._flushToCapture()\n\n // poor performance is >4s, we wait twice that time to send\n // this is in case we haven't received all metrics\n // we'll at least gather some\n this._delayedFlushTimer = setTimeout(this._flushToCapture, this.flushToCaptureTimeoutMs)\n }\n\n if (isUndefined(this._buffer.url)) {\n this._buffer.url = $currentUrl\n }\n\n this._buffer.firstMetricTimestamp = isUndefined(this._buffer.firstMetricTimestamp)\n ? Date.now()\n : this._buffer.firstMetricTimestamp\n\n if (metric.attribution && metric.attribution.interactionTargetElement) {\n // we don't want to send the entire element\n // they can be very large\n // TODO we could run this through autocapture code so that we get elements chain info\n // and can display the element in the UI\n metric.attribution.interactionTargetElement = undefined\n }\n\n this._buffer.metrics.push({\n ...metric,\n $current_url: $currentUrl,\n $session_id: sessionIds.sessionId,\n $window_id: sessionIds.windowId,\n timestamp: Date.now(),\n })\n\n if (this._buffer.metrics.length === this.allowedMetrics.length) {\n // we have all allowed metrics\n this._flushToCapture()\n }\n }\n\n private _startCapturing = () => {\n // IMPORTANT: web-vitals does not provide cleanup functions and warns against\n // calling functions more than once per page load. Each call creates new\n // PerformanceObservers that persist for the page lifetime.\n // See: https://github.com/GoogleChrome/web-vitals/issues/629\n if (this._initialized) {\n return\n }\n\n let onLCP: WebVitalsMetricCallback | undefined\n let onCLS: WebVitalsMetricCallback | undefined\n let onFCP: WebVitalsMetricCallback | undefined\n let onINP: WebVitalsMetricCallback | undefined\n\n const posthogExtensions = assignableWindow.__PosthogExtensions__\n if (!isUndefined(posthogExtensions) && !isUndefined(posthogExtensions.postHogWebVitalsCallbacks)) {\n ;({ onLCP, onCLS, onFCP, onINP } = posthogExtensions.postHogWebVitalsCallbacks)\n }\n\n if (!onLCP || !onCLS || !onFCP || !onINP) {\n logger.error('web vitals callbacks not loaded - not starting')\n return\n }\n\n // register performance observers\n if (this.allowedMetrics.indexOf('LCP') > -1) {\n onLCP(this._addToBuffer.bind(this))\n }\n if (this.allowedMetrics.indexOf('CLS') > -1) {\n onCLS(this._addToBuffer.bind(this))\n }\n if (this.allowedMetrics.indexOf('FCP') > -1) {\n onFCP(this._addToBuffer.bind(this))\n }\n if (this.allowedMetrics.indexOf('INP') > -1) {\n onINP(this._addToBuffer.bind(this))\n }\n\n this._initialized = true\n }\n}\n", "import {\n SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION,\n SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION,\n SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX,\n SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX,\n} from '../../../constants'\nimport { PostHog } from '../../../posthog-core'\nimport { FlagVariant, RemoteConfig, SessionRecordingPersistedConfig, SessionRecordingUrlTrigger } from '../../../types'\nimport { isNullish, isBoolean, isString, isObject, isUndefined } from '@posthog/core'\nimport { window } from '../../../utils/globals'\nimport { logger } from '../../../utils/logger'\n\nexport const DISABLED = 'disabled'\nexport const SAMPLED = 'sampled'\nexport const ACTIVE = 'active'\nexport const BUFFERING = 'buffering'\nexport const PAUSED = 'paused'\nexport const LAZY_LOADING = 'lazy_loading'\nexport const AWAITING_CONFIG = 'awaiting_config'\nexport const MISSING_CONFIG = 'missing_config'\nexport const RRWEB_ERROR = 'rrweb_error'\n\nconst TRIGGER = 'trigger'\nexport const TRIGGER_ACTIVATED = TRIGGER + '_activated'\nexport const TRIGGER_PENDING = TRIGGER + '_pending'\nexport const TRIGGER_DISABLED = TRIGGER + '_' + DISABLED\n\nexport interface RecordingTriggersStatus {\n get receivedFlags(): boolean\n get isRecordingEnabled(): false | true | undefined\n get isSampled(): false | true | null\n get rrwebError(): boolean\n get urlTriggerMatching(): URLTriggerMatching\n get eventTriggerMatching(): EventTriggerMatching\n get linkedFlagMatching(): LinkedFlagMatching\n get sessionId(): string\n}\n\n/**\n * Extended interface for V2 trigger groups\n */\nexport interface RecordingTriggersStatusV2 extends RecordingTriggersStatus {\n get triggerGroupMatchers(): TriggerGroupMatching[]\n get triggerGroupSamplingResults(): Map // group id -> sampled decision\n get minimumDuration(): number | null\n}\n\nexport type TriggerType = 'url' | 'event'\n/* \ntriggers can have one of three statuses:\n * - trigger_activated: the trigger met conditions to start recording\n * - trigger_pending: the trigger is present, but the conditions are not yet met\n * - trigger_disabled: the trigger is not present\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst triggerStatuses = [TRIGGER_ACTIVATED, TRIGGER_PENDING, TRIGGER_DISABLED] as const\nexport type TriggerStatus = (typeof triggerStatuses)[number]\n\n/**\n * Session recording starts in buffering mode while waiting for \"flags response\".\n * Once the response is received, it might be disabled, active or sampled.\n * When \"sampled\" that means a sample rate is set, and the last time the session ID rotated\n * the sample rate determined this session should be sent to the server.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst sessionRecordingStatuses = [\n DISABLED,\n SAMPLED,\n ACTIVE,\n BUFFERING,\n PAUSED,\n LAZY_LOADING,\n AWAITING_CONFIG,\n MISSING_CONFIG,\n RRWEB_ERROR,\n] as const\nexport type SessionRecordingStatus = (typeof sessionRecordingStatuses)[number]\n\n// while we have both lazy and eager loaded replay we might get either type of config\ntype ReplayConfigType = RemoteConfig | SessionRecordingPersistedConfig\n\n// Type for trigger group matching config - subset of SessionRecordingPersistedConfig properties\ntype TriggerMatchingConfig = Pick<\n SessionRecordingPersistedConfig,\n 'urlTriggers' | 'urlBlocklist' | 'eventTriggers' | 'linkedFlag'\n>\n\nfunction sessionRecordingUrlTriggerMatches(\n url: string,\n triggers: SessionRecordingUrlTrigger[],\n compiledRegexCache?: Map\n) {\n return triggers.some((trigger) => {\n switch (trigger.matching) {\n case 'regex': {\n const regex = compiledRegexCache?.get(trigger.url) ?? new RegExp(trigger.url)\n return regex.test(url)\n }\n default:\n return false\n }\n })\n}\n\nexport interface TriggerStatusMatching {\n triggerStatus(sessionId: string): TriggerStatus\n stop(): void\n}\nexport class OrTriggerMatching implements TriggerStatusMatching {\n constructor(private readonly _matchers: TriggerStatusMatching[]) {}\n\n triggerStatus(sessionId: string): TriggerStatus {\n const statuses = this._matchers.map((m) => m.triggerStatus(sessionId))\n if (statuses.includes(TRIGGER_ACTIVATED)) {\n return TRIGGER_ACTIVATED\n }\n if (statuses.includes(TRIGGER_PENDING)) {\n return TRIGGER_PENDING\n }\n return TRIGGER_DISABLED\n }\n\n stop(): void {\n this._matchers.forEach((m) => m.stop())\n }\n}\n\nexport class AndTriggerMatching implements TriggerStatusMatching {\n constructor(private readonly _matchers: TriggerStatusMatching[]) {}\n\n triggerStatus(sessionId: string): TriggerStatus {\n const statuses = new Set()\n for (const matcher of this._matchers) {\n statuses.add(matcher.triggerStatus(sessionId))\n }\n\n // trigger_disabled means no config\n statuses.delete(TRIGGER_DISABLED)\n switch (statuses.size) {\n case 0:\n return TRIGGER_DISABLED\n case 1:\n return Array.from(statuses)[0]\n default:\n return TRIGGER_PENDING\n }\n }\n\n stop(): void {\n this._matchers.forEach((m) => m.stop())\n }\n}\n\nexport class PendingTriggerMatching implements TriggerStatusMatching {\n triggerStatus(): TriggerStatus {\n return TRIGGER_PENDING\n }\n\n stop(): void {\n // no-op\n }\n}\n\nexport class AlwaysActivatedTriggerMatching implements TriggerStatusMatching {\n triggerStatus(): TriggerStatus {\n return TRIGGER_ACTIVATED\n }\n\n stop(): void {\n // no-op\n }\n}\n\nconst isEagerLoadedConfig = (x: ReplayConfigType | TriggerMatchingConfig): x is RemoteConfig => {\n return 'sessionRecording' in x\n}\n\nexport class URLTriggerMatching implements TriggerStatusMatching {\n _urlTriggers: SessionRecordingUrlTrigger[] = []\n _urlBlocklist: SessionRecordingUrlTrigger[] = []\n\n private _compiledTriggerRegexes: Map = new Map()\n private _compiledBlocklistRegexes: Map = new Map()\n\n private _lastCheckedUrl: string = ''\n private _groupId?: string // Optional group ID for V2 per-group persistence\n\n urlBlocked: boolean = false\n\n constructor(\n private readonly _instance: PostHog,\n groupId?: string\n ) {\n this._groupId = groupId\n }\n\n onConfig(config: ReplayConfigType | TriggerMatchingConfig) {\n this._urlTriggers =\n (isEagerLoadedConfig(config)\n ? isObject(config.sessionRecording)\n ? config.sessionRecording?.urlTriggers\n : []\n : config?.urlTriggers) || []\n this._urlBlocklist =\n (isEagerLoadedConfig(config)\n ? isObject(config.sessionRecording)\n ? config.sessionRecording?.urlBlocklist\n : []\n : config?.urlBlocklist) || []\n\n this._compileRegexCache()\n }\n\n /**\n * Compiles and caches RegExp objects from URL triggers and blocklist.\n * This prevents recreating RegExp objects on every rrweb event\n */\n private _compileRegexCache(): void {\n this._compiledTriggerRegexes.clear()\n this._compiledBlocklistRegexes.clear()\n\n for (const trigger of this._urlTriggers) {\n if (trigger.matching === 'regex' && !this._compiledTriggerRegexes.has(trigger.url)) {\n try {\n this._compiledTriggerRegexes.set(trigger.url, new RegExp(trigger.url))\n } catch (e) {\n logger.error('Invalid URL trigger regex pattern:', trigger.url, e)\n }\n }\n }\n\n for (const trigger of this._urlBlocklist) {\n if (trigger.matching === 'regex' && !this._compiledBlocklistRegexes.has(trigger.url)) {\n try {\n this._compiledBlocklistRegexes.set(trigger.url, new RegExp(trigger.url))\n } catch (e) {\n logger.error('Invalid URL blocklist regex pattern:', trigger.url, e)\n }\n }\n }\n }\n\n /**\n * @deprecated Use onConfig instead\n */\n onRemoteConfig(response: RemoteConfig) {\n this.onConfig(response)\n }\n\n private _urlTriggerStatus(sessionId: string): TriggerStatus {\n if (this._urlTriggers.length === 0) {\n return TRIGGER_DISABLED\n }\n\n // V2: Use per-group persistence key if groupId is provided\n const persistenceKey = this._groupId\n ? SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX + this._groupId\n : SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION\n\n const currentTriggerSession = this._instance?.get_property(persistenceKey)\n return currentTriggerSession === sessionId ? TRIGGER_ACTIVATED : TRIGGER_PENDING\n }\n\n triggerStatus(sessionId: string): TriggerStatus {\n const urlTriggerStatus = this._urlTriggerStatus(sessionId)\n const eitherIsActivated = urlTriggerStatus === TRIGGER_ACTIVATED\n const eitherIsPending = urlTriggerStatus === TRIGGER_PENDING\n\n const result = eitherIsActivated ? TRIGGER_ACTIVATED : eitherIsPending ? TRIGGER_PENDING : TRIGGER_DISABLED\n this._instance.register_for_session({\n $sdk_debug_replay_url_trigger_status: result,\n })\n return result\n }\n\n /**\n * Check URL blocklist and pause/resume recording accordingly\n * This is separate from trigger checking and is used by both V1 and V2\n *\n * Performance optimization: Only checks when URL changes to avoid redundant regex matching\n */\n checkUrlBlocklist(onPause: () => void, onResume: () => void): void {\n if (typeof window === 'undefined' || !window.location.href) {\n return\n }\n\n const url = window.location.href\n\n // Performance optimization: Skip if URL hasn't changed since last check\n if (url === this._lastCheckedUrl) {\n return\n }\n this._lastCheckedUrl = url\n\n // Check blocklist and call onPause/onResume\n // Note: DON'T set this.urlBlocked here - let the callbacks (_pauseRecording/_resumeRecording) set it\n const wasBlocked = this.urlBlocked\n const isNowBlocked = sessionRecordingUrlTriggerMatches(url, this._urlBlocklist, this._compiledBlocklistRegexes)\n\n if (wasBlocked && isNowBlocked) {\n return\n }\n\n if (isNowBlocked && !wasBlocked) {\n onPause()\n } else if (!isNowBlocked && wasBlocked) {\n onResume()\n }\n }\n\n checkUrlTriggerConditions(\n onPause: () => void,\n onResume: () => void,\n onActivate: (triggerType: TriggerType, matchDetail?: string) => void,\n sessionId: string\n ) {\n if (typeof window === 'undefined' || !window.location.href) {\n return\n }\n\n const url = window.location.href\n\n // Performance optimization: Skip if URL hasn't changed since last check\n // This prevents redundant checks on every rrweb event\n if (url === this._lastCheckedUrl) {\n return\n }\n this._lastCheckedUrl = url\n\n // Check blocklist and call onPause/onResume\n // Note: DON'T set this.urlBlocked here - let the callbacks (_pauseRecording/_resumeRecording) set it\n const wasBlocked = this.urlBlocked\n const isNowBlocked = sessionRecordingUrlTriggerMatches(url, this._urlBlocklist, this._compiledBlocklistRegexes)\n\n if (isNowBlocked && !wasBlocked) {\n onPause()\n } else if (!isNowBlocked && wasBlocked) {\n onResume()\n }\n\n // Check URL triggers\n const isActivated = this._urlTriggerStatus(sessionId) === TRIGGER_ACTIVATED\n const urlMatches = sessionRecordingUrlTriggerMatches(url, this._urlTriggers, this._compiledTriggerRegexes)\n\n if (!isActivated && urlMatches) {\n onActivate('url', url)\n }\n }\n\n stop(): void {\n this._lastCheckedUrl = ''\n }\n}\n\nexport class LinkedFlagMatching implements TriggerStatusMatching {\n linkedFlag: string | FlagVariant | null = null\n linkedFlagSeen: boolean = false\n private _flagListenerCleanup: () => void = () => {}\n constructor(private readonly _instance: PostHog) {}\n\n triggerStatus(): TriggerStatus {\n let result = TRIGGER_PENDING\n if (isNullish(this.linkedFlag)) {\n result = TRIGGER_DISABLED\n }\n if (this.linkedFlagSeen) {\n result = TRIGGER_ACTIVATED\n }\n this._instance.register_for_session({\n $sdk_debug_replay_linked_flag_trigger_status: result,\n })\n return result\n }\n\n onConfig(\n config: ReplayConfigType | TriggerMatchingConfig,\n onStarted: (flag: string, variant: string | null) => void\n ) {\n this.linkedFlag =\n (isEagerLoadedConfig(config)\n ? isObject(config.sessionRecording)\n ? config.sessionRecording?.linkedFlag\n : null\n : config?.linkedFlag) || null\n\n if (!isNullish(this.linkedFlag) && !this.linkedFlagSeen) {\n const linkedFlag = isString(this.linkedFlag) ? this.linkedFlag : this.linkedFlag.flag\n const linkedVariant = isString(this.linkedFlag) ? null : this.linkedFlag.variant\n this._flagListenerCleanup = this._instance.onFeatureFlags((_flags, variants) => {\n const flagIsPresent = isObject(variants) && linkedFlag in variants\n let linkedFlagMatches = false\n if (flagIsPresent) {\n const variantForFlagKey = variants[linkedFlag]\n if (isBoolean(variantForFlagKey)) {\n linkedFlagMatches = variantForFlagKey === true\n } else if (linkedVariant) {\n linkedFlagMatches = variantForFlagKey === linkedVariant\n } else {\n // then this is a variant flag and we want to match any string\n linkedFlagMatches = !!variantForFlagKey\n }\n }\n this.linkedFlagSeen = linkedFlagMatches\n if (linkedFlagMatches) {\n onStarted(linkedFlag, linkedVariant)\n }\n })\n }\n }\n\n /**\n * @deprecated Use onConfig instead\n */\n onRemoteConfig(response: RemoteConfig, onStarted: (flag: string, variant: string | null) => void) {\n this.onConfig(response, onStarted)\n }\n\n stop(): void {\n this._flagListenerCleanup()\n }\n}\n\nexport class EventTriggerMatching implements TriggerStatusMatching {\n _eventTriggers: string[] = []\n private _groupId?: string // Optional group ID for V2 per-group persistence\n\n constructor(\n private readonly _instance: PostHog,\n groupId?: string\n ) {\n this._groupId = groupId\n }\n\n onConfig(config: ReplayConfigType | TriggerMatchingConfig) {\n // Handle both RemoteConfig (nested) and SessionRecordingPersistedConfig (flattened) structures\n this._eventTriggers =\n (isEagerLoadedConfig(config)\n ? isObject(config.sessionRecording)\n ? config.sessionRecording?.eventTriggers\n : []\n : config?.eventTriggers) || []\n }\n\n /**\n * @deprecated Use onConfig instead\n */\n onRemoteConfig(response: RemoteConfig) {\n this.onConfig(response)\n }\n\n private _eventTriggerStatus(sessionId: string): TriggerStatus {\n if (this._eventTriggers.length === 0) {\n return TRIGGER_DISABLED\n }\n\n // V2: Use per-group persistence key if groupId is provided\n const persistenceKey = this._groupId\n ? SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX + this._groupId\n : SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION\n\n const currentTriggerSession = this._instance?.get_property(persistenceKey)\n return currentTriggerSession === sessionId ? TRIGGER_ACTIVATED : TRIGGER_PENDING\n }\n\n triggerStatus(sessionId: string): TriggerStatus {\n const eventTriggerStatus = this._eventTriggerStatus(sessionId)\n const result =\n eventTriggerStatus === TRIGGER_ACTIVATED\n ? TRIGGER_ACTIVATED\n : eventTriggerStatus === TRIGGER_PENDING\n ? TRIGGER_PENDING\n : TRIGGER_DISABLED\n this._instance.register_for_session({\n $sdk_debug_replay_event_trigger_status: result,\n })\n return result\n }\n\n checkEventTriggerConditions(\n eventName: string,\n onActivate: (triggerType: TriggerType, matchDetail?: string) => void,\n sessionId: string\n ) {\n if (this._eventTriggers.length === 0) {\n return\n }\n\n const isActivated = this._eventTriggerStatus(sessionId) === TRIGGER_ACTIVATED\n const includes = this._eventTriggers.includes(eventName)\n if (!isActivated && includes) {\n onActivate('event', eventName)\n }\n }\n\n stop(): void {\n // no-op\n }\n}\n\n/**\n * V2 Trigger Group Matching - manages a single trigger group with its own conditions\n */\nexport class TriggerGroupMatching implements TriggerStatusMatching {\n private _urlTriggerMatching: URLTriggerMatching\n private _eventTriggerMatching: EventTriggerMatching\n private _linkedFlagMatching: LinkedFlagMatching\n private _combinedMatching: TriggerStatusMatching\n public readonly group: import('../../../types').SessionRecordingTriggerGroup\n\n constructor(\n private readonly _instance: PostHog,\n group: import('../../../types').SessionRecordingTriggerGroup,\n onFlagStarted: (flag: string, variant: string | null) => void\n ) {\n this.group = group\n // V2: Pass groupId to child matchers for per-group persistence\n this._urlTriggerMatching = new URLTriggerMatching(_instance, group.id)\n this._eventTriggerMatching = new EventTriggerMatching(_instance, group.id)\n this._linkedFlagMatching = new LinkedFlagMatching(_instance)\n\n // Check if all conditions are empty (no events, urls, or flags)\n const hasEvents = group.conditions.events && group.conditions.events.length > 0\n const hasUrls = group.conditions.urls && group.conditions.urls.length > 0\n const hasFlag = !!group.conditions.flag\n\n if (!hasEvents && !hasUrls && !hasFlag) {\n // Empty conditions = trigger immediately on session start\n this._combinedMatching = new AlwaysActivatedTriggerMatching()\n } else {\n // V2: Events arrive as objects {name, properties?} from the server.\n // Extract just the names — property filter evaluation is handled by the strategy.\n const eventNames = (group.conditions.events || []).map((e) => e.name)\n\n // Convert group config to the format expected by the individual matchers\n const config: TriggerMatchingConfig = {\n urlTriggers: group.conditions.urls || [],\n eventTriggers: eventNames,\n linkedFlag: group.conditions.flag || null,\n urlBlocklist: [],\n }\n\n this._urlTriggerMatching.onConfig(config)\n this._eventTriggerMatching.onConfig(config)\n this._linkedFlagMatching.onConfig(config, onFlagStarted)\n\n // Combine matchers based on the group's matchType\n const matchers = [this._eventTriggerMatching, this._urlTriggerMatching, this._linkedFlagMatching]\n this._combinedMatching =\n group.conditions.matchType === 'any'\n ? new OrTriggerMatching(matchers)\n : new AndTriggerMatching(matchers)\n }\n }\n\n triggerStatus(sessionId: string): TriggerStatus {\n return this._combinedMatching.triggerStatus(sessionId)\n }\n\n checkEventTriggerConditions(\n eventName: string,\n onActivate: (triggerType: TriggerType, matchDetail?: string) => void,\n sessionId: string\n ) {\n this._eventTriggerMatching.checkEventTriggerConditions(eventName, onActivate, sessionId)\n }\n\n checkUrlTriggerConditions(\n onPause: () => void,\n onResume: () => void,\n onActivate: (triggerType: TriggerType, matchDetail?: string) => void,\n sessionId: string\n ) {\n this._urlTriggerMatching.checkUrlTriggerConditions(onPause, onResume, onActivate, sessionId)\n }\n\n /**\n * V2: Activate this group's trigger and persist to group-specific key\n * This prevents cross-group contamination and survives page reloads\n */\n activateTrigger(triggerType: TriggerType, sessionId: string): void {\n const persistenceKey =\n triggerType === 'url'\n ? SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX + this.group.id\n : SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX + this.group.id\n\n this._instance.persistence?.register({\n [persistenceKey]: sessionId,\n })\n }\n\n stop(): void {\n this._urlTriggerMatching.stop()\n this._eventTriggerMatching.stop()\n this._linkedFlagMatching.stop()\n }\n}\n\n// we need a no-op matcher before we can lazy-load the other matches, since all matchers wait on remote config anyway\nexport function nullMatchSessionRecordingStatus(triggersStatus: RecordingTriggersStatus): SessionRecordingStatus {\n if (triggersStatus.rrwebError) {\n return RRWEB_ERROR\n }\n\n if (!triggersStatus.isRecordingEnabled) {\n return DISABLED\n }\n\n return BUFFERING\n}\n\nexport function anyMatchSessionRecordingStatus(triggersStatus: RecordingTriggersStatus): SessionRecordingStatus {\n if (triggersStatus.rrwebError) {\n return RRWEB_ERROR\n }\n\n if (!triggersStatus.receivedFlags) {\n return BUFFERING\n }\n\n if (!triggersStatus.isRecordingEnabled) {\n return DISABLED\n }\n\n if (triggersStatus.urlTriggerMatching.urlBlocked) {\n return PAUSED\n }\n\n const sampledActive = triggersStatus.isSampled === true\n const triggerMatches = new OrTriggerMatching([\n triggersStatus.eventTriggerMatching,\n triggersStatus.urlTriggerMatching,\n triggersStatus.linkedFlagMatching,\n ]).triggerStatus(triggersStatus.sessionId)\n\n if (sampledActive) {\n return SAMPLED\n }\n\n if (triggerMatches === TRIGGER_ACTIVATED) {\n return ACTIVE\n }\n\n if (triggerMatches === TRIGGER_PENDING) {\n // even if sampled active is false, we should still be buffering\n // since a pending trigger could override it\n return BUFFERING\n }\n\n // if sampling is set and the session is already decided to not be sampled\n // then we should never be active\n if (triggersStatus.isSampled === false) {\n return DISABLED\n }\n\n return ACTIVE\n}\n\nexport function allMatchSessionRecordingStatus(triggersStatus: RecordingTriggersStatus): SessionRecordingStatus {\n if (triggersStatus.rrwebError) {\n return RRWEB_ERROR\n }\n\n if (!triggersStatus.receivedFlags) {\n return BUFFERING\n }\n\n if (!triggersStatus.isRecordingEnabled) {\n return DISABLED\n }\n\n if (triggersStatus.urlTriggerMatching.urlBlocked) {\n return PAUSED\n }\n\n const andTriggerMatch = new AndTriggerMatching([\n triggersStatus.eventTriggerMatching,\n triggersStatus.urlTriggerMatching,\n triggersStatus.linkedFlagMatching,\n ])\n const currentTriggerStatus = andTriggerMatch.triggerStatus(triggersStatus.sessionId)\n const hasTriggersConfigured = currentTriggerStatus !== TRIGGER_DISABLED\n\n const hasSamplingConfigured = isBoolean(triggersStatus.isSampled)\n\n if (hasTriggersConfigured && currentTriggerStatus === TRIGGER_PENDING) {\n return BUFFERING\n }\n\n if (hasTriggersConfigured && currentTriggerStatus === TRIGGER_DISABLED) {\n return DISABLED\n }\n\n // sampling can't ever cause buffering, it's always determined right away or not configured\n if (hasSamplingConfigured && !triggersStatus.isSampled) {\n return DISABLED\n }\n\n // If sampling is configured and set to true, return sampled\n if (triggersStatus.isSampled === true) {\n return SAMPLED\n }\n\n return ACTIVE\n}\n\n/**\n * V2 Trigger Groups Status Matcher - implements union behavior:\n * 1. Evaluate ALL trigger groups\n * 2. For each matching group, check if its sample rate hits\n * 3. If ANY group's sample rate hits → record session\n */\nexport function triggerGroupsMatchSessionRecordingStatus(\n triggersStatus: RecordingTriggersStatusV2\n): SessionRecordingStatus {\n if (triggersStatus.rrwebError) {\n return RRWEB_ERROR\n }\n\n if (!triggersStatus.receivedFlags) {\n return BUFFERING\n }\n\n if (!triggersStatus.isRecordingEnabled) {\n return DISABLED\n }\n\n // Check if any URL is blocked (url blocklist is global, not per-group)\n if (triggersStatus.urlTriggerMatching.urlBlocked) {\n return PAUSED\n }\n\n const groupMatchers = triggersStatus.triggerGroupMatchers\n const samplingResults = triggersStatus.triggerGroupSamplingResults\n\n if (groupMatchers.length === 0) {\n // No V2 groups configured - should not happen, but treat as disabled\n return DISABLED\n }\n\n // Evaluate all groups to determine overall status\n let anyGroupPending = false\n let anyGroupSampled = false\n\n for (const matcher of groupMatchers) {\n const groupStatus = matcher.triggerStatus(triggersStatus.sessionId)\n\n if (groupStatus === TRIGGER_ACTIVATED) {\n // Check if this group's sample rate hit\n const groupId = matcher.group.id\n const samplingResult = samplingResults.get(groupId)\n\n if (isUndefined(samplingResult)) {\n logger.warn('[V2 Triggers] Group activated but no sampling decision found', { groupId })\n } else if (samplingResult === true) {\n anyGroupSampled = true\n }\n } else if (groupStatus === TRIGGER_PENDING) {\n anyGroupPending = true\n }\n }\n\n // Union behavior: if ANY group hit its sample rate, record\n if (anyGroupSampled) {\n return SAMPLED\n }\n\n // If any group is pending, keep buffering\n if (anyGroupPending) {\n return BUFFERING\n }\n\n // All groups are either disabled, conditions not met, or sampled out\n return DISABLED\n}\n", "import { PostHog } from '../../../posthog-core'\nimport {\n CaptureResult,\n SessionRecordingPersistedConfig,\n SessionRecordingTriggerGroup,\n SessionStartReason,\n} from '../../../types'\nimport {\n SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION,\n SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION,\n SESSION_RECORDING_IS_SAMPLED,\n SESSION_RECORDING_PAST_MINIMUM_DURATION,\n SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX,\n SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX,\n SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX,\n STORED_PERSON_PROPERTIES_KEY,\n} from '../../../constants'\nimport {\n EventTriggerMatching,\n LinkedFlagMatching,\n URLTriggerMatching,\n TriggerGroupMatching,\n SessionRecordingStatus,\n allMatchSessionRecordingStatus,\n anyMatchSessionRecordingStatus,\n triggerGroupsMatchSessionRecordingStatus,\n RecordingTriggersStatusV2,\n TriggerType,\n AndTriggerMatching,\n OrTriggerMatching,\n TriggerStatusMatching,\n TRIGGER_PENDING,\n} from './triggerMatching'\nimport { sampleOnProperty } from '../../sampling'\nimport { isBoolean, isNull, isNullish, isNumber } from '@posthog/core'\nimport { createLogger } from '../../../utils/logger'\nimport { matchTriggerPropertyFilters } from '../../../utils/property-utils'\n\nconst logger = createLogger('[SessionRecording]')\n\n/**\n * Shared context that strategies need to access from the recorder\n */\nexport interface RecordingStrategyContext {\n instance: PostHog\n sessionId: string\n isSampled: boolean | null\n rrwebError: boolean\n urlTriggerMatching: URLTriggerMatching\n eventTriggerMatching: EventTriggerMatching\n linkedFlagMatching: LinkedFlagMatching\n remoteConfig: SessionRecordingPersistedConfig | undefined\n}\n\n/**\n * Strategy interface for handling different recording trigger configurations\n */\nexport interface RecordingStrategy {\n /**\n * Initialize the strategy with remote config\n */\n onRemoteConfig(config: SessionRecordingPersistedConfig): void\n\n /**\n * Get the current recording status\n */\n getStatus(context: RecordingStrategyContext): SessionRecordingStatus\n\n /**\n * Get the minimum duration for this session (if any)\n */\n getMinimumDuration(sessionId: string): number | null\n\n /**\n * Check URL triggers on each navigation\n * Note: URL is read from window.location.href internally\n */\n checkUrlTriggers(\n sessionId: string,\n onPause: () => void,\n onResume: () => void,\n onActivate: (triggerType: TriggerType, matchDetail?: string) => void\n ): void\n\n /**\n * Setup event trigger listeners\n */\n setupEventTriggerListeners(\n onEvent: (callback: (event: CaptureResult) => void) => () => void,\n sessionId: string,\n onActivate: (triggerType: TriggerType, matchDetail?: string) => void\n ): (() => void) | undefined\n\n /**\n * Make sampling decisions for the session\n */\n makeSamplingDecisions(sessionId: string): void\n\n /**\n * Called after the initial buffer flush (performance optimization hook)\n */\n onFlushComplete(): void\n\n /**\n * Clean up persistence keys for conditional recording\n */\n clearConditionalRecordingPersistence(): void\n\n /**\n * Update session properties with active trigger information\n */\n updateActiveTriggers(sessionId: string): void\n\n /**\n * Check if triggers are in pending state (waiting for activation)\n */\n hasPendingTriggers(sessionId: string): boolean\n\n /**\n * Stop and cleanup the strategy\n */\n stop(): void\n}\n\n/**\n * V1 Strategy: Legacy trigger matching with global URL/Event/Flag triggers\n */\nexport class V1RecordingStrategy implements RecordingStrategy {\n private _triggerStatusMatcher: TriggerStatusMatching | undefined\n private _removeEventTriggerCaptureHook: (() => void) | undefined\n private _sampleRate: number | null = null\n private _recordingStatusFunction: typeof anyMatchSessionRecordingStatus = allMatchSessionRecordingStatus\n\n constructor(\n private readonly _instance: PostHog,\n private readonly _urlTriggerMatching: URLTriggerMatching,\n private readonly _eventTriggerMatching: EventTriggerMatching,\n private readonly _linkedFlagMatching: LinkedFlagMatching,\n private readonly _reportStarted: (reason: SessionStartReason, payload?: Record) => void,\n private readonly _tryTakeFullSnapshot: () => void\n ) {}\n\n onRemoteConfig(config: SessionRecordingPersistedConfig): void {\n this._sampleRate = isNumber(config.sampleRate) ? config.sampleRate : null\n\n // Setup trigger matching strategy (AND vs OR)\n if (config.triggerMatchType === 'any') {\n this._triggerStatusMatcher = new OrTriggerMatching([this._eventTriggerMatching, this._urlTriggerMatching])\n this._recordingStatusFunction = anyMatchSessionRecordingStatus\n } else {\n // either the setting is \"ALL\" or we default to the most restrictive\n this._triggerStatusMatcher = new AndTriggerMatching([this._eventTriggerMatching, this._urlTriggerMatching])\n this._recordingStatusFunction = allMatchSessionRecordingStatus\n }\n\n this._instance.register_for_session({\n $sdk_debug_replay_remote_trigger_matching_config: config.triggerMatchType,\n })\n\n this._urlTriggerMatching.onConfig(config)\n this._eventTriggerMatching.onConfig(config)\n\n this._linkedFlagMatching.onConfig(config, (flag, variant) => {\n this._reportStarted('linked_flag_matched', { flag, variant })\n })\n }\n\n getStatus(context: RecordingStrategyContext): SessionRecordingStatus {\n return this._recordingStatusFunction({\n receivedFlags: true,\n isRecordingEnabled: true,\n isSampled: context.isSampled,\n rrwebError: context.rrwebError,\n urlTriggerMatching: context.urlTriggerMatching,\n eventTriggerMatching: context.eventTriggerMatching,\n linkedFlagMatching: context.linkedFlagMatching,\n sessionId: context.sessionId,\n })\n }\n\n getMinimumDuration(sessionId: string): number | null {\n // V1: Minimum duration is global from config, doesn't need sessionId\n void sessionId\n const config = this._instance.get_property('$session_recording_remote_config') as\n | SessionRecordingPersistedConfig\n | undefined\n const duration = config?.minimumDurationMilliseconds\n return isNumber(duration) ? duration : null\n }\n\n checkUrlTriggers(\n sessionId: string,\n onPause: () => void,\n onResume: () => void,\n onActivate: (triggerType: TriggerType, matchDetail?: string) => void\n ): void {\n this._urlTriggerMatching.checkUrlTriggerConditions(onPause, onResume, onActivate, sessionId)\n }\n\n setupEventTriggerListeners(\n onEvent: (callback: (event: CaptureResult) => void) => () => void,\n sessionId: string,\n onActivate: (triggerType: TriggerType, matchDetail?: string) => void\n ): (() => void) | undefined {\n if (this._eventTriggerMatching._eventTriggers.length === 0 || !isNullish(this._removeEventTriggerCaptureHook)) {\n return undefined\n }\n\n this._removeEventTriggerCaptureHook = onEvent((event: CaptureResult) => {\n try {\n this._eventTriggerMatching.checkEventTriggerConditions(event.event, onActivate, sessionId)\n } catch (e) {\n logger.error('Could not activate event trigger', e)\n }\n })\n\n return this._removeEventTriggerCaptureHook\n }\n\n makeSamplingDecisions(sessionId: string): void {\n const currentSampleRate = this._sampleRate\n\n if (!isNumber(currentSampleRate)) {\n this._instance.persistence?.unregister(SESSION_RECORDING_IS_SAMPLED)\n return\n }\n\n const storedValue = this._instance.get_property(SESSION_RECORDING_IS_SAMPLED)\n\n // Parse stored decision:\n // - sessionId string = sampled in for that session\n // - false = sampled out (persistent across navigations in same session)\n // - undefined/null = no decision yet\n const storedIsSampled = storedValue === sessionId ? true : storedValue === false ? false : null\n\n // Make new decision only if:\n // 1. No stored decision exists (storedIsSampled is null/undefined), OR\n // 2. Session changed (stored sessionId doesn't match current)\n const sessionChanged = typeof storedValue === 'string' && storedValue !== sessionId\n const makeDecision = sessionChanged || !isBoolean(storedIsSampled)\n const shouldSample = makeDecision ? sampleOnProperty(sessionId, currentSampleRate) : storedIsSampled!\n\n if (makeDecision) {\n if (shouldSample) {\n this._reportStarted('sampled')\n } else {\n logger.warn(\n `Sample rate (${currentSampleRate}) has determined that this sessionId (${sessionId}) will not be sent to the server.`\n )\n }\n }\n\n this._instance.persistence?.register({\n [SESSION_RECORDING_IS_SAMPLED]: shouldSample ? sessionId : false,\n })\n }\n\n onFlushComplete(): void {\n // V1 doesn't use this optimization\n }\n\n clearConditionalRecordingPersistence(): void {\n this._instance.persistence?.unregister(SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION)\n this._instance.persistence?.unregister(SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION)\n this._instance.persistence?.unregister(SESSION_RECORDING_IS_SAMPLED)\n this._instance.persistence?.unregister(SESSION_RECORDING_PAST_MINIMUM_DURATION)\n }\n\n updateActiveTriggers(sessionId: string): void {\n void sessionId\n // V1 doesn't track active triggers in session properties\n }\n\n hasPendingTriggers(sessionId: string): boolean {\n return this._triggerStatusMatcher?.triggerStatus(sessionId) === TRIGGER_PENDING\n }\n\n stop(): void {\n this._removeEventTriggerCaptureHook?.()\n this._removeEventTriggerCaptureHook = undefined\n this._eventTriggerMatching.stop()\n this._urlTriggerMatching.stop()\n this._linkedFlagMatching.stop()\n }\n}\n\n/**\n * V2 Strategy: Trigger groups with per-group sampling and union behavior\n */\nexport class V2TriggerGroupStrategy implements RecordingStrategy {\n private _triggerGroupMatchers: TriggerGroupMatching[] = []\n private _triggerGroupSamplingResults: Map = new Map()\n private _hasCompletedInitialFlush: boolean = false\n private _removeEventTriggerCaptureHook: (() => void) | undefined\n\n constructor(\n private readonly _instance: PostHog,\n private readonly _urlTriggerMatching: URLTriggerMatching,\n private readonly _reportStarted: (reason: SessionStartReason, payload?: Record) => void,\n private readonly _tryAddCustomEvent: (tag: string, payload: any) => void\n ) {}\n\n onRemoteConfig(config: SessionRecordingPersistedConfig): void {\n if (!config.triggerGroups || config.triggerGroups.length === 0) {\n logger.warn('[V2Strategy] No trigger groups configured')\n return\n }\n\n // Setup trigger group matchers\n this._setupTriggerGroups(config.triggerGroups)\n\n this._instance.register_for_session({\n $sdk_debug_replay_remote_trigger_matching_config: 'v2_trigger_groups',\n $sdk_debug_replay_trigger_groups_count: config.triggerGroups.length,\n })\n\n // V2 needs URL blocklist (but not URL triggers)\n this._urlTriggerMatching.onConfig(config)\n }\n\n getStatus(context: RecordingStrategyContext): SessionRecordingStatus {\n return triggerGroupsMatchSessionRecordingStatus({\n receivedFlags: true,\n isRecordingEnabled: true,\n isSampled: context.isSampled,\n rrwebError: context.rrwebError,\n urlTriggerMatching: context.urlTriggerMatching,\n eventTriggerMatching: context.eventTriggerMatching,\n linkedFlagMatching: context.linkedFlagMatching,\n sessionId: context.sessionId,\n triggerGroupMatchers: this._triggerGroupMatchers,\n triggerGroupSamplingResults: this._triggerGroupSamplingResults,\n minimumDuration: this.getMinimumDuration(context.sessionId),\n } as RecordingTriggersStatusV2)\n }\n\n getMinimumDuration(sessionId: string): number | null {\n let lowestDuration: number | null = null\n\n for (const matcher of this._triggerGroupMatchers) {\n const groupStatus = matcher.triggerStatus(sessionId)\n\n // Only consider activated groups - pending groups haven't triggered yet\n if (groupStatus === 'trigger_activated') {\n const groupDuration = matcher.group.minDurationMs\n if (isNumber(groupDuration)) {\n if (isNull(lowestDuration) || groupDuration < lowestDuration) {\n lowestDuration = groupDuration\n }\n }\n }\n }\n\n return lowestDuration\n }\n\n checkUrlTriggers(\n sessionId: string,\n onPause: () => void,\n onResume: () => void,\n onActivate: (triggerType: TriggerType, matchDetail?: string) => void\n ): void {\n // V2 doesn't use the global onActivate callback - each group activates itself\n void onActivate\n\n // Check URL blocklist (global, not per-group)\n this._urlTriggerMatching.checkUrlBlocklist(onPause, onResume)\n\n // Check URL triggers for each group\n for (const matcher of this._triggerGroupMatchers) {\n matcher.checkUrlTriggerConditions(\n onPause,\n onResume,\n (triggerType) => {\n // Check group-level property filters before activating\n if (!this._checkGroupLevelProperties(matcher, undefined)) {\n return\n }\n\n matcher.activateTrigger(triggerType, sessionId)\n this.updateActiveTriggers(sessionId)\n },\n sessionId\n )\n }\n }\n\n setupEventTriggerListeners(\n onEvent: (callback: (event: CaptureResult) => void) => () => void,\n sessionId: string,\n onActivate: (triggerType: TriggerType, matchDetail?: string) => void\n ): (() => void) | undefined {\n // V2 doesn't use the global onActivate callback - each group activates itself\n void onActivate\n\n this._removeEventTriggerCaptureHook = onEvent((event: CaptureResult) => {\n // Performance optimization: Stop checking triggers after initial buffer flush\n if (this._hasCompletedInitialFlush) {\n logger.info('[SessionRecorder] Stopping trigger checks - initial buffer flushed')\n this._removeEventTriggerCaptureHook?.()\n this._removeEventTriggerCaptureHook = undefined\n return\n }\n\n try {\n // V2: Each group activates its own trigger with per-group persistence\n for (const matcher of this._triggerGroupMatchers) {\n matcher.checkEventTriggerConditions(\n event.event,\n (triggerType) => {\n // Check group-level property filters\n if (!this._checkGroupLevelProperties(matcher, event.properties)) {\n return\n }\n\n // Check per-event property filters.\n // A group may contain multiple entries for the same event name with\n // different property filters — e.g. \"purchase amount > 100\" OR\n // \"purchase by a VIP\". Treat same-name entries as a disjunction:\n // activate if *any* matching clause's filters pass. An entry with no\n // properties is treated as an unconditional match (matching V1).\n const matchedTriggers = (matcher.group.conditions.events || []).filter(\n (t) => t.name === event.event\n )\n const personProperties = this._instance.get_property(STORED_PERSON_PROPERTIES_KEY)\n const anyMatched = matchedTriggers.some(\n (t) =>\n !t.properties ||\n t.properties.length === 0 ||\n matchTriggerPropertyFilters(t.properties, event.properties, personProperties)\n )\n if (!anyMatched) {\n return\n }\n\n matcher.activateTrigger(triggerType, sessionId)\n this.updateActiveTriggers(sessionId)\n },\n sessionId\n )\n }\n } catch (e) {\n logger.error('Could not activate event trigger for trigger groups', e)\n }\n })\n\n return this._removeEventTriggerCaptureHook\n }\n\n makeSamplingDecisions(sessionId: string): void {\n for (const matcher of this._triggerGroupMatchers) {\n const group = matcher.group\n const groupId = group.id\n const sampleRate = group.sampleRate\n\n // Check if we have a stored decision for this group\n const storageKey = SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX + groupId\n const storedValue = this._instance.get_property(storageKey)\n\n // Parse stored decision:\n // - sessionId string = sampled in for that session\n // - false = sampled out (persistent across navigations in same session)\n // - undefined/null = no decision yet\n const storedDecision = storedValue === sessionId ? true : storedValue === false ? false : null\n\n // Make new decision only if:\n // 1. No stored decision exists (storedDecision is null/undefined), OR\n // 2. Session changed (stored sessionId doesn't match current)\n const sessionChanged = typeof storedValue === 'string' && storedValue !== sessionId\n const makeDecision = sessionChanged || !isBoolean(storedDecision)\n const shouldSample = makeDecision ? sampleOnProperty(sessionId + groupId, sampleRate) : storedDecision!\n\n if (makeDecision) {\n this._tryAddCustomEvent('triggerGroupSamplingDecisionMade', {\n group_id: groupId,\n group_name: group.name,\n sampleRate: sampleRate,\n isSampled: shouldSample,\n })\n }\n\n // Store the decision\n this._triggerGroupSamplingResults.set(groupId, shouldSample)\n this._instance.persistence?.register({\n [storageKey]: shouldSample ? sessionId : false,\n })\n }\n\n // After all sampling decisions, register which groups are actively recording\n this.updateActiveTriggers(sessionId)\n }\n\n onFlushComplete(): void {\n this._hasCompletedInitialFlush = true\n }\n\n clearConditionalRecordingPersistence(): void {\n this._instance.persistence?.unregister(SESSION_RECORDING_IS_SAMPLED)\n this._instance.persistence?.unregister(SESSION_RECORDING_PAST_MINIMUM_DURATION)\n\n // V2: Clear per-group trigger keys\n for (const matcher of this._triggerGroupMatchers) {\n const groupId = matcher.group.id\n this._instance.persistence?.unregister(SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX + groupId)\n this._instance.persistence?.unregister(SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX + groupId)\n this._instance.persistence?.unregister(SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX + groupId)\n }\n }\n\n updateActiveTriggers(sessionId: string): void {\n const recordingGroups: Array<{ id: string; name: string; matched: boolean; sampled: boolean }> = []\n\n for (const matcher of this._triggerGroupMatchers) {\n const group = matcher.group\n const groupId = group.id\n const triggerStatus = matcher.triggerStatus(sessionId)\n const isMatched = triggerStatus === 'trigger_activated'\n const isSampled = this._triggerGroupSamplingResults.get(groupId) === true\n\n if (isMatched) {\n recordingGroups.push({\n id: groupId,\n name: group.name,\n matched: true,\n sampled: isSampled,\n })\n }\n }\n\n this._instance.register_for_session({\n $sdk_debug_replay_matched_recording_trigger_groups: recordingGroups,\n })\n }\n\n hasPendingTriggers(sessionId: string): boolean {\n // V2: Check if any group has pending triggers\n for (const matcher of this._triggerGroupMatchers) {\n if (matcher.triggerStatus(sessionId) === TRIGGER_PENDING) {\n return true\n }\n }\n return false\n }\n\n stop(): void {\n this._removeEventTriggerCaptureHook?.()\n this._removeEventTriggerCaptureHook = undefined\n this._triggerGroupMatchers.forEach((matcher) => matcher.stop())\n this._triggerGroupMatchers = []\n this._triggerGroupSamplingResults.clear()\n this._urlTriggerMatching.stop()\n }\n\n private _checkGroupLevelProperties(\n matcher: TriggerGroupMatching,\n eventProperties: Record | undefined\n ): boolean {\n const groupProperties = matcher.group.conditions.properties\n if (!groupProperties || groupProperties.length === 0) {\n return true\n }\n const personProperties = this._instance.get_property(STORED_PERSON_PROPERTIES_KEY)\n return matchTriggerPropertyFilters(groupProperties, eventProperties, personProperties)\n }\n\n private _setupTriggerGroups(groups: SessionRecordingTriggerGroup[]) {\n // Clean up existing matchers\n this._triggerGroupMatchers.forEach((matcher) => matcher.stop())\n this._triggerGroupMatchers = []\n this._triggerGroupSamplingResults.clear()\n\n // Create a matcher for each group\n for (const group of groups) {\n const matcher = new TriggerGroupMatching(this._instance, group, (flag, variant) => {\n this._reportStarted('linked_flag_matched', {\n flag,\n variant,\n group_id: group.id,\n group_name: group.name,\n })\n })\n this._triggerGroupMatchers.push(matcher)\n }\n }\n}\n", "import type { recordOptions, rrwebRecord as rrwebRecordType } from '../types/rrweb'\nimport {\n type customEvent,\n EventType,\n eventWithTime,\n IncrementalSource,\n type listenerHandler,\n RecordPlugin,\n} from '../types/rrweb-types'\nimport { buildNetworkRequestOptions } from './config'\nimport {\n ACTIVE,\n BUFFERING,\n DISABLED,\n EventTriggerMatching,\n LinkedFlagMatching,\n PAUSED,\n SessionRecordingStatus,\n TriggerType,\n URLTriggerMatching,\n} from './triggerMatching'\nimport {\n estimateCompressedEventSize,\n estimateSize,\n INCREMENTAL_SNAPSHOT_EVENT_TYPE,\n truncateLargeConsoleLogs,\n} from './sessionrecording-utils'\nimport { gzipSync, strFromU8, strToU8 } from 'fflate'\nimport { assignableWindow, LazyLoadedSessionRecordingInterface, window, document } from '../../../utils/globals'\nimport { addEventListener } from '../../../utils'\nimport { MutationThrottler } from './mutation-throttler'\nimport { createLogger } from '../../../utils/logger'\nimport {\n clampToRange,\n isArray,\n isBoolean,\n isFunction,\n isNull,\n isNullish,\n isNumber,\n isObject,\n isString,\n isUndefined,\n} from '@posthog/core'\nimport {\n SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP,\n SESSION_RECORDING_IS_SAMPLED,\n SESSION_RECORDING_OVERRIDE_SAMPLING,\n SESSION_RECORDING_OVERRIDE_LINKED_FLAG,\n SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER,\n SESSION_RECORDING_OVERRIDE_URL_TRIGGER,\n SESSION_RECORDING_PAST_MINIMUM_DURATION,\n SESSION_RECORDING_REMOTE_CONFIG,\n SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION,\n SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION,\n} from '../../../constants'\nimport { PostHog } from '../../../posthog-core'\nimport {\n NetworkRecordOptions,\n PerformanceCaptureConfig,\n Properties,\n SessionIdChangedCallback,\n SessionRecordingOptions,\n SessionRecordingPersistedConfig,\n SessionStartReason,\n} from '../../../types'\nimport { isLocalhost } from '../../../utils/request-utils'\nimport Config from '../../../config'\nimport { FlushedSizeTracker } from './flushed-size-tracker'\nimport {\n RecordingStrategy,\n V1RecordingStrategy,\n V2TriggerGroupStrategy,\n RecordingStrategyContext,\n} from './recording-strategies'\n\nconst BASE_ENDPOINT = '/s/'\nconst DEFAULT_CANVAS_QUALITY = 0.4\nconst DEFAULT_CANVAS_FPS = 4\nconst MAX_CANVAS_FPS = 12\nconst MAX_CANVAS_QUALITY = 1\nconst TWO_SECONDS = 2000\nconst ONE_KB = 1024\n\nconst ONE_MINUTE = 1000 * 60\nconst FIVE_MINUTES = ONE_MINUTE * 5\nconst ONE_HOUR = ONE_MINUTE * 60\n\n/**\n * Extracts the network_timing value from a capturePerformance config.\n * Returns `true`/`false` if explicitly set, or `undefined` if not specified.\n */\nfunction networkTimingFromConfig(config: boolean | PerformanceCaptureConfig | undefined): boolean | undefined {\n return isObject(config) ? config.network_timing : config\n}\n\nexport const RECORDING_IDLE_THRESHOLD_MS = FIVE_MINUTES\nexport const RECORDING_REMOTE_CONFIG_TTL_MS = ONE_HOUR\nexport const RECORDING_MAX_EVENT_SIZE = ONE_KB * ONE_KB * 0.9 // ~1mb (with some wiggle room)\nexport const RECORDING_BUFFER_TIMEOUT = 2000 // 2 seconds\nexport const SESSION_RECORDING_BATCH_KEY = 'recordings'\n\nconst LOGGER_PREFIX = '[SessionRecording]'\nconst logger = createLogger(LOGGER_PREFIX)\n\ninterface QueuedRRWebEvent {\n rrwebMethod: () => void\n attempt: number\n // the timestamp this was first put into this queue\n enqueuedAt: number\n}\n\ninterface SessionIdlePayload {\n eventTimestamp: number\n lastActivityTimestamp: number\n threshold: number\n bufferLength: number\n bufferSize: number\n}\n\nexport interface SnapshotBuffer {\n size: number\n data: any[]\n sizes: number[]\n sessionId: string\n windowId: string\n}\n\nconst ACTIVE_SOURCES: IncrementalSource[] = [\n IncrementalSource.MouseMove,\n IncrementalSource.MouseInteraction,\n IncrementalSource.Scroll,\n IncrementalSource.ViewportResize,\n IncrementalSource.Input,\n IncrementalSource.TouchMove,\n IncrementalSource.MediaInteraction,\n IncrementalSource.Drag,\n]\n\nconst newQueuedEvent = (rrwebMethod: () => void): QueuedRRWebEvent => ({\n rrwebMethod,\n enqueuedAt: Date.now(),\n attempt: 1,\n})\n\nfunction getRRWeb() {\n return assignableWindow?.__PosthogExtensions__?.rrweb\n}\n\nfunction getRRWebRecord(): rrwebRecordType | undefined {\n return getRRWeb()?.record\n}\n\nexport type compressedFullSnapshotEvent = {\n type: typeof EventType.FullSnapshot\n data: string\n}\n\nexport type compressedIncrementalSnapshotEvent = {\n type: typeof EventType.IncrementalSnapshot\n data: {\n source: IncrementalSource\n texts: string\n attributes: string\n removes: string\n adds: string\n }\n}\n\nexport type compressedIncrementalStyleSnapshotEvent = {\n type: typeof EventType.IncrementalSnapshot\n data: {\n source: typeof IncrementalSource.StyleSheetRule\n id?: number\n styleId?: number\n replace?: string\n replaceSync?: string\n adds?: string\n removes?: string\n }\n}\n\nexport type compressedEvent =\n | compressedIncrementalStyleSnapshotEvent\n | compressedFullSnapshotEvent\n | compressedIncrementalSnapshotEvent\nexport type compressedEventWithTime = compressedEvent & {\n timestamp: number\n delay?: number\n // marker for compression version\n cv: '2024-10'\n}\n\nfunction gzipToString(data: unknown): string {\n return strFromU8(gzipSync(strToU8(JSON.stringify(data))), true)\n}\n\nlet _gzippedEmptyArray: string | undefined\n\nfunction gzipField(data: unknown): string {\n if (isArray(data) && data.length === 0) {\n _gzippedEmptyArray = _gzippedEmptyArray ?? gzipToString([])\n return _gzippedEmptyArray\n }\n return gzipToString(data)\n}\n\n/**\n * rrweb's packer takes an event and returns a string or the reverse on `unpack`.\n * but we want to be able to inspect metadata during ingestion.\n * and don't want to compress the entire event,\n * so we have a custom packer that only compresses part of some events\n *\n * returns the compressed event and its estimated JSON size,\n * avoiding a redundant JSON.stringify for size estimation\n */\nfunction compressEvent(event: eventWithTime): { event: eventWithTime | compressedEventWithTime; size: number } {\n try {\n if (event.type === EventType.FullSnapshot) {\n const compressed = {\n ...event,\n data: gzipToString(event.data),\n cv: '2024-10' as const,\n }\n return { event: compressed, size: estimateCompressedEventSize(compressed) }\n }\n if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.Mutation) {\n const compressed = {\n ...event,\n cv: '2024-10' as const,\n data: {\n ...event.data,\n texts: gzipField(event.data.texts),\n attributes: gzipField(event.data.attributes),\n removes: gzipField(event.data.removes),\n adds: gzipField(event.data.adds),\n },\n }\n return { event: compressed, size: estimateCompressedEventSize(compressed) }\n }\n if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.StyleSheetRule) {\n const compressed = {\n ...event,\n cv: '2024-10' as const,\n data: {\n ...event.data,\n adds: event.data.adds ? gzipToString(event.data.adds) : undefined,\n removes: event.data.removes ? gzipToString(event.data.removes) : undefined,\n },\n }\n return { event: compressed, size: estimateCompressedEventSize(compressed) }\n }\n } catch (e) {\n logger.error('could not compress event - will use uncompressed event', e)\n }\n return { event, size: estimateSize(event) }\n}\n\nfunction isCustomEvent(e: eventWithTime, tag: string): e is eventWithTime & customEvent {\n return e.type === EventType.Custom && e.data.tag === tag\n}\n\nfunction isSessionIdleEvent(e: eventWithTime): e is eventWithTime & customEvent {\n return isCustomEvent(e, 'sessionIdle')\n}\n\ntype SessionEndingPayload = {\n lastActivityTimestamp?: number\n currentSessionId?: string\n currentWindowId?: string\n}\n\nfunction isSessionEndingEvent(e: eventWithTime): e is eventWithTime & customEvent {\n return isCustomEvent(e, '$session_ending')\n}\n\nfunction getSessionEndingPayload(e: eventWithTime): SessionEndingPayload | null {\n return isSessionEndingEvent(e) ? (e.data.payload as SessionEndingPayload) : null\n}\n\ntype SessionStartingPayload = {\n lastActivityTimestamp?: number\n nextSessionId?: string\n nextWindowId?: string\n}\n\nfunction isSessionStartingEvent(e: eventWithTime): e is eventWithTime & customEvent {\n return isCustomEvent(e, '$session_starting')\n}\n\nfunction getSessionStartingPayload(e: eventWithTime): SessionStartingPayload | null {\n return isSessionStartingEvent(e) ? (e.data.payload as SessionStartingPayload) : null\n}\n\nfunction isAllowedWhenIdle(e: eventWithTime): boolean {\n return isSessionIdleEvent(e) || isSessionEndingEvent(e) || isSessionStartingEvent(e)\n}\n\n/** When we put the recording into a paused state, we add a custom event.\n * However, in the paused state, events are dropped and never make it to the buffer,\n * so we need to manually let this one through */\nfunction isRecordingPausedEvent(e: eventWithTime) {\n return e.type === EventType.Custom && e.data.tag === 'recording paused'\n}\n\nexport const SEVEN_MEGABYTES = 1024 * 1024 * 7 * 0.9 // ~7mb (with some wiggle room)\n\n// recursively splits large buffers into smaller ones\n// uses a pretty high size limit to avoid splitting too much\nexport function splitBuffer(buffer: SnapshotBuffer, sizeLimit: number = SEVEN_MEGABYTES): SnapshotBuffer[] {\n if (buffer.size >= sizeLimit && buffer.data.length > 1) {\n const half = Math.floor(buffer.data.length / 2)\n const firstHalfSizes = buffer.sizes.slice(0, half)\n const secondHalfSizes = buffer.sizes.slice(half)\n return [\n splitBuffer({\n size: firstHalfSizes.reduce((a, b) => a + b, 0),\n data: buffer.data.slice(0, half),\n sizes: firstHalfSizes,\n sessionId: buffer.sessionId,\n windowId: buffer.windowId,\n }),\n splitBuffer({\n size: secondHalfSizes.reduce((a, b) => a + b, 0),\n data: buffer.data.slice(half),\n sizes: secondHalfSizes,\n sessionId: buffer.sessionId,\n windowId: buffer.windowId,\n }),\n ].flatMap((x) => x)\n } else {\n return [buffer]\n }\n}\n\nexport class LazyLoadedSessionRecording implements LazyLoadedSessionRecordingInterface {\n private _endpoint: string = BASE_ENDPOINT\n private _mutationThrottler?: MutationThrottler\n /**\n * Util to help developers working on this feature manually override\n */\n private _forceAllowLocalhostNetworkCapture = false\n private _stopRrweb: listenerHandler | undefined = undefined\n private _lastActivityTimestamp: number = Date.now()\n private _isActivatingTrigger: boolean = false\n /**\n * if pageview capture is disabled,\n * then we can manually track href changes\n */\n private _lastHref?: string\n /**\n * and a queue - that contains rrweb events that we want to send to rrweb, but rrweb wasn't able to accept them yet\n */\n private _queuedRRWebEvents: QueuedRRWebEvent[] = []\n private _isIdle: boolean | 'unknown' = 'unknown'\n private _rrwebError = false\n private _maxDepthExceeded = false\n\n private _linkedFlagMatching: LinkedFlagMatching\n private _urlTriggerMatching: URLTriggerMatching\n private _eventTriggerMatching: EventTriggerMatching\n // Strategy pattern: V1 vs V2 trigger logic\n private _strategy: RecordingStrategy | undefined\n private _fullSnapshotTimer?: ReturnType\n private _fullSnapshotTimestamps: Array<[string, number]> = []\n\n private _windowId: string\n private _sessionId: string\n get sessionId(): string {\n return this._sessionId\n }\n\n private _flushBufferTimer?: any\n // we have a buffer - that contains PostHog snapshot events ready to be sent to the server\n private _buffer: SnapshotBuffer\n\n private _removePageViewCaptureHook: (() => void) | undefined = undefined\n\n private _removeEventTriggerCaptureHook: (() => void) | undefined = undefined\n\n private _flushedSizeTracker: FlushedSizeTracker\n\n private get _sessionManager() {\n if (!this._instance.sessionManager) {\n throw new Error(LOGGER_PREFIX + ' must be started with a valid sessionManager.')\n }\n\n return this._instance.sessionManager\n }\n\n private get _sessionIdleThresholdMilliseconds(): number {\n return this._instance.config.session_recording.session_idle_threshold_ms || RECORDING_IDLE_THRESHOLD_MS\n }\n\n private get _isSampled(): boolean | null {\n const currentValue = this._instance.get_property(SESSION_RECORDING_IS_SAMPLED)\n // we store the session id when sampled so that we can detect session id changes\n // and `false` when not sampled\n // legacy SDKs stored `true` when sampled, but that is not tied to a session id\n // so we treat it as null (unknown) and will make a fresh decision\n if (currentValue === true) {\n return null\n }\n return currentValue === false ? false : isString(currentValue) ? currentValue === this.sessionId : null\n }\n\n private get _sampleRate(): number | null {\n const rate = this._remoteConfig?.sampleRate\n return isNumber(rate) ? rate : null\n }\n\n private get _minimumDuration(): number | null {\n return this._strategy?.getMinimumDuration(this.sessionId) ?? null\n }\n\n private _onSessionIdListener: (() => void) | undefined = undefined\n private _onSessionIdleResetForcedListener: (() => void) | undefined = undefined\n private _samplingSessionListener: (() => void) | undefined = undefined\n private _forceIdleSessionIdListener: (() => void) | undefined = undefined\n\n constructor(private readonly _instance: PostHog) {\n // we know there's a sessionManager, so don't need to start without a session id\n const { sessionId, windowId } = this._sessionManager.checkAndGetSessionAndWindowId()\n this._sessionId = sessionId\n this._windowId = windowId\n\n this._linkedFlagMatching = new LinkedFlagMatching(this._instance)\n this._urlTriggerMatching = new URLTriggerMatching(this._instance)\n this._eventTriggerMatching = new EventTriggerMatching(this._instance)\n\n this._buffer = this._clearBuffer()\n\n if (this._sessionIdleThresholdMilliseconds >= this._sessionManager.sessionTimeoutMs) {\n logger.warn(\n `session_idle_threshold_ms (${this._sessionIdleThresholdMilliseconds}) is greater than the session timeout (${this._sessionManager.sessionTimeoutMs}). Session will never be detected as idle`\n )\n }\n\n this._flushedSizeTracker = new FlushedSizeTracker(this._instance)\n }\n\n private get _masking():\n | Pick\n | undefined {\n const masking_server_side = this._remoteConfig?.masking\n const masking_client_side = {\n maskAllInputs: this._instance.config.session_recording?.maskAllInputs,\n maskTextSelector: this._instance.config.session_recording?.maskTextSelector,\n blockSelector: this._instance.config.session_recording?.blockSelector,\n }\n\n const maskAllInputs = masking_client_side?.maskAllInputs ?? masking_server_side?.maskAllInputs\n const maskTextSelector = masking_client_side?.maskTextSelector ?? masking_server_side?.maskTextSelector\n const blockSelector = masking_client_side?.blockSelector ?? masking_server_side?.blockSelector\n\n return !isUndefined(maskAllInputs) || !isUndefined(maskTextSelector) || !isUndefined(blockSelector)\n ? {\n maskAllInputs: maskAllInputs ?? true,\n maskTextSelector,\n blockSelector,\n }\n : undefined\n }\n\n private get _canvasRecording(): { enabled: boolean; fps: number; quality: number } {\n const canvasRecording_client_side = this._instance.config.session_recording.captureCanvas\n const canvasRecording_server_side = this._remoteConfig?.canvasRecording\n\n const enabled: boolean =\n canvasRecording_client_side?.recordCanvas ?? canvasRecording_server_side?.enabled ?? false\n const fps: number =\n canvasRecording_client_side?.canvasFps ?? canvasRecording_server_side?.fps ?? DEFAULT_CANVAS_FPS\n let quality: string | number =\n canvasRecording_client_side?.canvasQuality ?? canvasRecording_server_side?.quality ?? DEFAULT_CANVAS_QUALITY\n if (typeof quality === 'string') {\n const parsed = parseFloat(quality)\n quality = isNaN(parsed) ? 0.4 : parsed\n }\n\n return {\n enabled,\n fps: clampToRange(fps, 0, MAX_CANVAS_FPS, createLogger('canvas recording fps'), DEFAULT_CANVAS_FPS),\n quality: clampToRange(\n quality,\n 0,\n MAX_CANVAS_QUALITY,\n createLogger('canvas recording quality'),\n DEFAULT_CANVAS_QUALITY\n ),\n }\n }\n\n private get _isConsoleLogCaptureEnabled() {\n const enabled_server_side = !!this._remoteConfig?.consoleLogRecordingEnabled\n const enabled_client_side = this._instance.config.enable_recording_console_log\n return enabled_client_side ?? enabled_server_side\n }\n\n // network payload capture config has three parts\n // each can be configured server side or client side\n private get _networkPayloadCapture():\n | Pick\n | undefined {\n const networkPayloadCapture_server_side = this._remoteConfig?.networkPayloadCapture\n const networkPayloadCapture_client_side = {\n recordHeaders: this._instance.config.session_recording?.recordHeaders,\n recordBody: this._instance.config.session_recording?.recordBody,\n }\n const headersEnabled =\n networkPayloadCapture_client_side?.recordHeaders || networkPayloadCapture_server_side?.recordHeaders\n const bodyEnabled =\n networkPayloadCapture_client_side?.recordBody || networkPayloadCapture_server_side?.recordBody\n const clientNetworkTiming = networkTimingFromConfig(this._instance.config.capture_performance)\n const serverNetworkTiming = networkTimingFromConfig(networkPayloadCapture_server_side?.capturePerformance)\n const networkTimingEnabled = !!(isBoolean(clientNetworkTiming) ? clientNetworkTiming : serverNetworkTiming)\n\n return headersEnabled || bodyEnabled || networkTimingEnabled\n ? { recordHeaders: headersEnabled, recordBody: bodyEnabled, recordPerformance: networkTimingEnabled }\n : undefined\n }\n\n private _gatherRRWebPlugins() {\n const plugins: RecordPlugin[] = []\n\n const recordConsolePlugin = assignableWindow.__PosthogExtensions__?.rrwebPlugins?.getRecordConsolePlugin\n if (recordConsolePlugin && this._isConsoleLogCaptureEnabled) {\n plugins.push(recordConsolePlugin())\n }\n\n const networkPlugin = assignableWindow.__PosthogExtensions__?.rrwebPlugins?.getRecordNetworkPlugin\n if (!!this._networkPayloadCapture && isFunction(networkPlugin)) {\n const canRecordNetwork = !isLocalhost() || this._forceAllowLocalhostNetworkCapture\n\n if (canRecordNetwork) {\n plugins.push(\n networkPlugin(buildNetworkRequestOptions(this._instance.config, this._networkPayloadCapture))\n )\n } else {\n logger.info('NetworkCapture not started because we are on localhost.')\n }\n }\n\n return plugins\n }\n\n private _maskUrl(url: string): string | undefined {\n const userSessionRecordingOptions = this._instance.config.session_recording\n\n // userSessionRecordingOptions.maskNetworkRequestFn is deprecated, fallback to it\n if (userSessionRecordingOptions.maskCapturedNetworkRequestFn) {\n const result = userSessionRecordingOptions.maskCapturedNetworkRequestFn({\n name: url,\n } as any)\n // CapturedNetworkRequest uses 'name' for URL, but also check 'url' for compatibility\n return result?.name ?? (result as any)?.url\n }\n\n if (userSessionRecordingOptions.maskNetworkRequestFn) {\n const result = userSessionRecordingOptions.maskNetworkRequestFn({\n url,\n })\n return result?.url\n }\n\n return url\n }\n\n private _tryRRWebMethod(queuedRRWebEvent: QueuedRRWebEvent): boolean {\n try {\n queuedRRWebEvent.rrwebMethod()\n return true\n } catch (e) {\n // Sometimes a race can occur where the recorder is not fully started yet\n if (this._queuedRRWebEvents.length < 10) {\n this._queuedRRWebEvents.push({\n enqueuedAt: queuedRRWebEvent.enqueuedAt || Date.now(),\n attempt: queuedRRWebEvent.attempt + 1,\n rrwebMethod: queuedRRWebEvent.rrwebMethod,\n })\n } else {\n logger.warn('could not emit queued rrweb event.', e, queuedRRWebEvent)\n }\n\n return false\n }\n }\n\n private _tryAddCustomEvent(tag: string, payload: any): boolean {\n return this._tryRRWebMethod(newQueuedEvent(() => getRRWebRecord()!.addCustomEvent(tag, payload)))\n }\n\n private _pageViewFallBack() {\n try {\n if (this._instance.config.capture_pageview || !window) {\n return\n }\n // Strip hash parameters from URL since they often aren't helpful\n // Use URL constructor for proper parsing to handle edge cases\n // recording doesn't run in IE11, so we don't need compat here\n // eslint-disable-next-line compat/compat\n const url = new URL(window.location.href)\n const hrefWithoutHash = url.origin + url.pathname + url.search\n const currentUrl = this._maskUrl(hrefWithoutHash)\n if (this._lastHref !== currentUrl) {\n this._lastHref = currentUrl\n this._tryAddCustomEvent('$url_changed', { href: currentUrl })\n }\n } catch {\n // If URL processing fails, don't capture anything\n }\n }\n\n private _processQueuedEvents() {\n if (this._queuedRRWebEvents.length) {\n // if rrweb isn't ready to accept events earlier, then we queued them up.\n // now that `emit` has been called rrweb should be ready to accept them.\n // so, before we process this event, we try our queued events _once_ each\n // we don't want to risk queuing more things and never exiting this loop!\n // if they fail here, they'll be pushed into a new queue\n // and tried on the next loop.\n // there is a risk of this queue growing in an uncontrolled manner.\n // so its length is limited elsewhere\n // for now this is to help us ensure we can capture events that happen\n // and try to identify more about when it is failing\n const itemsToProcess = [...this._queuedRRWebEvents]\n this._queuedRRWebEvents = []\n itemsToProcess.forEach((queuedRRWebEvent) => {\n if (Date.now() - queuedRRWebEvent.enqueuedAt <= TWO_SECONDS) {\n this._tryRRWebMethod(queuedRRWebEvent)\n }\n })\n }\n }\n\n private _tryTakeFullSnapshot(): boolean {\n return this._tryRRWebMethod(newQueuedEvent(() => getRRWebRecord()!.takeFullSnapshot()))\n }\n\n private get _fullSnapshotIntervalMillis(): number {\n if (this._strategy?.hasPendingTriggers(this.sessionId) && !['sampled', 'active'].includes(this.status)) {\n return ONE_MINUTE\n }\n\n return this._instance.config.session_recording?.full_snapshot_interval_millis ?? FIVE_MINUTES\n }\n\n private _scheduleFullSnapshot(): void {\n if (this._fullSnapshotTimer) {\n clearInterval(this._fullSnapshotTimer)\n }\n // we don't schedule snapshots while idle\n if (this._isIdle === true) {\n return\n }\n\n const interval = this._fullSnapshotIntervalMillis\n if (!interval) {\n return\n }\n\n this._fullSnapshotTimer = setInterval(() => {\n this._tryTakeFullSnapshot()\n }, interval)\n }\n\n private _pauseRecording() {\n // we check _urlBlocked not status, since more than one thing can affect status\n if (this._urlTriggerMatching.urlBlocked) {\n return\n }\n\n // we can't flush the buffer here since someone might be starting on a blocked page.\n // and we need to be sure that we don't record that page,\n // so we might not get the below custom event, but events will report the paused status.\n // which will allow debugging of sessions that start on blocked pages\n this._urlTriggerMatching.urlBlocked = true\n\n // Clear the snapshot timer since we don't want new snapshots while paused\n clearInterval(this._fullSnapshotTimer)\n\n logger.info('recording paused due to URL blocker')\n this._tryAddCustomEvent('recording paused', { reason: 'url blocker' })\n }\n\n private _resumeRecording() {\n // we check _urlBlocked not status, since more than one thing can affect status\n if (!this._urlTriggerMatching.urlBlocked) {\n return\n }\n\n this._urlTriggerMatching.urlBlocked = false\n\n this._tryTakeFullSnapshot()\n this._scheduleFullSnapshot()\n\n this._tryAddCustomEvent('recording resumed', { reason: 'left blocked url' })\n logger.info('recording resumed')\n }\n\n private _activateTrigger(triggerType: TriggerType, matchDetail?: string) {\n // V1 only: V2 uses per-group activation and never calls this method\n // Prevent re-entry: if we're already activating a trigger, skip to avoid infinite recursion\n // This can happen when _reportStarted emits custom events that match the trigger condition\n if (this._isActivatingTrigger) {\n return\n }\n\n if (!this._strategy?.hasPendingTriggers(this.sessionId)) {\n return\n }\n\n this._isActivatingTrigger = true\n try {\n // V1: Write trigger activation to persistence\n // (V2 handles this per-group via TriggerGroupMatching.activateTrigger)\n const persistenceKey =\n triggerType === 'url'\n ? SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION\n : SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION\n\n this._instance.persistence?.register({\n [persistenceKey]: this.sessionId,\n })\n\n this._strategy?.updateActiveTriggers(this.sessionId)\n\n this._flushBuffer()\n this._reportStarted((triggerType + '_trigger_matched') as SessionStartReason, {\n [triggerType === 'url' ? 'matchedUrl' : 'matchedEvent']: matchDetail,\n })\n } finally {\n this._isActivatingTrigger = false\n }\n }\n\n get isStarted(): boolean {\n return !!this._stopRrweb\n }\n\n get _remoteConfig(): SessionRecordingPersistedConfig | undefined {\n const persistedConfig: any = this._instance.get_property(SESSION_RECORDING_REMOTE_CONFIG)\n if (!persistedConfig) {\n return undefined\n }\n const parsedConfig = isObject(persistedConfig) ? persistedConfig : JSON.parse(persistedConfig)\n\n // Only check TTL if recording hasn't started yet\n // Once started, trust the config until a hard page load\n if (!this.isStarted) {\n // default to now so that configs persisted by older SDK versions\n // (which never set cache_timestamp) are treated as fresh\n const cacheTimestamp = parsedConfig.cache_timestamp ?? Date.now()\n if (Date.now() - cacheTimestamp > RECORDING_REMOTE_CONFIG_TTL_MS) {\n logger.info('persisted remote config for session recording is stale and will be ignored', {\n cacheTimestamp,\n persistedConfig,\n })\n this._instance.persistence?.unregister(SESSION_RECORDING_REMOTE_CONFIG)\n return undefined\n }\n }\n\n return parsedConfig as SessionRecordingPersistedConfig\n }\n\n private _checkOverride(key: string, overrideFunction: () => void): void {\n const overrideFlag: boolean = this._instance.get_property(key) as boolean\n if (overrideFlag) {\n overrideFunction()\n\n // Clean up the override flag after applying it\n this._instance.persistence?.unregister(key)\n }\n }\n\n start(startReason?: SessionStartReason) {\n const config = this._remoteConfig\n if (!config) {\n logger.info('remote config must be stored in persistence before recording can start')\n return\n }\n\n // We want to ensure the sessionManager is reset if necessary on loading the recorder\n const { sessionId, windowId } = this._sessionManager.checkAndGetSessionAndWindowId()\n this._sessionId = sessionId\n this._windowId = windowId\n\n // Reset first full snapshot tracking for the new session\n this._instance.persistence?.unregister(SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP)\n\n if (config?.endpoint) {\n this._endpoint = config?.endpoint\n }\n\n // Initialize the appropriate strategy based on config version\n const isV2 = config?.version === 2 && config?.triggerGroups && config.triggerGroups.length > 0\n\n if (isV2) {\n this._strategy = new V2TriggerGroupStrategy(\n this._instance,\n this._urlTriggerMatching,\n this._reportStarted.bind(this),\n this._tryAddCustomEvent.bind(this)\n )\n } else {\n this._strategy = new V1RecordingStrategy(\n this._instance,\n this._urlTriggerMatching,\n this._eventTriggerMatching,\n this._linkedFlagMatching,\n this._reportStarted.bind(this),\n this._tryTakeFullSnapshot.bind(this)\n )\n }\n\n // Let the strategy configure itself\n this._strategy.onRemoteConfig(config)\n\n // Setup event trigger listeners via strategy\n this._removeEventTriggerCaptureHook?.()\n this._removeEventTriggerCaptureHook = this._strategy.setupEventTriggerListeners(\n this._instance.on.bind(this._instance, 'eventCaptured'),\n this.sessionId,\n (triggerType, matchDetail) => this._activateTrigger(triggerType, matchDetail)\n )\n\n this._checkOverride(SESSION_RECORDING_OVERRIDE_SAMPLING, () => {\n this.overrideSampling()\n })\n this._checkOverride(SESSION_RECORDING_OVERRIDE_LINKED_FLAG, () => {\n this.overrideLinkedFlag()\n })\n this._checkOverride(SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER, () => {\n this.overrideTrigger('event')\n })\n this._checkOverride(SESSION_RECORDING_OVERRIDE_URL_TRIGGER, () => {\n this.overrideTrigger('url')\n })\n\n // Let strategy make sampling decisions\n this._strategy.makeSamplingDecisions(this.sessionId)\n this._startRecorder()\n\n if (this._rrwebError) {\n return\n }\n\n // calling addEventListener multiple times is safe and will not add duplicates\n addEventListener(window, 'beforeunload', this._onBeforeUnload)\n addEventListener(window, 'offline', this._onOffline)\n addEventListener(window, 'online', this._onOnline)\n addEventListener(window, 'visibilitychange', this._onVisibilityChange)\n\n if (!this._onSessionIdListener) {\n this._onSessionIdListener = this._sessionManager.onSessionId(this._onSessionIdCallback)\n }\n\n if (!this._onSessionIdleResetForcedListener) {\n this._onSessionIdleResetForcedListener = this._sessionManager.on('forcedIdleReset', () => {\n // a session was forced to reset due to idle timeout and lack of activity\n this._clearConditionalRecordingPersistence()\n this._isIdle = 'unknown'\n this.stop()\n // then we want a session id listener to restart the recording when a new session starts\n this._forceIdleSessionIdListener = this._sessionManager.onSessionId(\n (sessionId, windowId, changeReason) => {\n // this should first unregister itself\n this._forceIdleSessionIdListener?.()\n this._forceIdleSessionIdListener = undefined\n this._onSessionIdCallback(sessionId, windowId, changeReason)\n }\n )\n })\n }\n\n if (isNullish(this._removePageViewCaptureHook)) {\n // :TRICKY: rrweb does not capture navigation within SPA-s, so hook into our $pageview events to get access to all events.\n // Dropping the initial event is fine (it's always captured by rrweb).\n this._removePageViewCaptureHook = this._instance.on('eventCaptured', (event) => {\n // If anything could go wrong here,\n // it has the potential to block the main loop,\n // so we catch all errors.\n try {\n if (event.event === '$pageview') {\n const href = event?.properties.$current_url ? this._maskUrl(event?.properties.$current_url) : ''\n if (!href) {\n return\n }\n this._tryAddCustomEvent('$pageview', { href })\n }\n } catch (e) {\n logger.error('Could not add $pageview to rrweb session', e)\n }\n })\n }\n\n if (this.status === ACTIVE) {\n this._reportStarted(startReason || 'recording_initialized')\n }\n }\n\n private _onSessionIdCallback: SessionIdChangedCallback = (sessionId, windowId, changeReason) => {\n if (!changeReason) return\n\n // Skip if session hasn't actually changed (callback might fire multiple times)\n if (sessionId === this._sessionId && windowId === this._windowId) {\n return\n }\n\n const wasLikelyReset = changeReason.noSessionId\n const shouldLinkSessions =\n !wasLikelyReset && (changeReason.activityTimeout || changeReason.sessionPastMaximumLength)\n\n // Capture old IDs before start() updates them\n const oldSessionId = this._sessionId\n const oldWindowId = this._windowId\n\n if (shouldLinkSessions) {\n this._tryAddCustomEvent('$session_ending', {\n currentSessionId: oldSessionId,\n currentWindowId: oldWindowId,\n nextSessionId: sessionId,\n nextWindowId: windowId,\n changeReason,\n // we'll need to correct the time of this if it's captured when idle\n // so we don't extend reported session time with a debug event\n lastActivityTimestamp: this._lastActivityTimestamp,\n flushed_size: this._flushedSizeTracker?.currentTrackedSize,\n })\n }\n\n // reset flushed size tracker after capturing the ending event\n if (this._flushedSizeTracker) {\n this._flushedSizeTracker.reset()\n }\n\n // Reset first full snapshot timestamp for the new session\n this._instance.persistence?.unregister(SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP)\n\n this._maxDepthExceeded = false\n getRRWeb()?.resetMaxDepthState?.()\n\n this._tryAddCustomEvent('$session_id_change', { sessionId, windowId, changeReason })\n\n this._clearConditionalRecordingPersistence()\n\n // When idle, _updateWindowAndSessionIds bails early and won't pick up the\n // session change, so we restart here. Otherwise it handles the restart after\n // this callback returns.\n if (this._isIdle === true) {\n this._isIdle = 'unknown'\n this.stop()\n this.start('session_id_changed')\n }\n\n if (shouldLinkSessions) {\n this._tryAddCustomEvent('$session_starting', {\n previousSessionId: oldSessionId,\n previousWindowId: oldWindowId,\n nextSessionId: sessionId,\n nextWindowId: windowId,\n changeReason,\n // we'll need to correct the time of this if it's captured when idle\n // so we don't extend reported session time with a debug event\n lastActivityTimestamp: this._lastActivityTimestamp,\n })\n }\n\n if (isNumber(this._sampleRate) && isNullish(this._samplingSessionListener)) {\n this._strategy?.makeSamplingDecisions(sessionId)\n }\n }\n\n private _teardown() {\n window?.removeEventListener('beforeunload', this._onBeforeUnload)\n window?.removeEventListener('offline', this._onOffline)\n window?.removeEventListener('online', this._onOnline)\n window?.removeEventListener('visibilitychange', this._onVisibilityChange)\n\n clearInterval(this._fullSnapshotTimer)\n this._clearFlushBufferTimer()\n\n this._removePageViewCaptureHook?.()\n this._removePageViewCaptureHook = undefined\n this._removeEventTriggerCaptureHook?.()\n this._removeEventTriggerCaptureHook = undefined\n this._onSessionIdListener?.()\n this._onSessionIdListener = undefined\n this._onSessionIdleResetForcedListener?.()\n this._onSessionIdleResetForcedListener = undefined\n this._samplingSessionListener?.()\n this._samplingSessionListener = undefined\n this._forceIdleSessionIdListener?.()\n this._forceIdleSessionIdListener = undefined\n\n this._strategy?.stop()\n\n this._mutationThrottler?.stop()\n\n // Clear any queued rrweb events to prevent memory leaks from closures\n this._queuedRRWebEvents = []\n\n this._stopRrweb?.()\n this._stopRrweb = undefined\n }\n\n stop() {\n this._flushBuffer()\n this._clearBuffer()\n this._teardown()\n logger.info('stopped')\n }\n\n discard() {\n this._clearBuffer()\n this._teardown()\n logger.info('discarded')\n }\n\n onRRwebEmit(rawEvent: eventWithTime) {\n this._processQueuedEvents()\n\n if (!rawEvent || !isObject(rawEvent)) {\n return\n }\n\n if (rawEvent.type === EventType.Meta) {\n const href = this._maskUrl(rawEvent.data.href)\n this._lastHref = href\n if (!href) {\n return\n }\n rawEvent.data.href = href\n } else {\n this._pageViewFallBack()\n }\n\n // Check if the URL matches any trigger patterns - delegate to strategy\n this._strategy?.checkUrlTriggers(\n this.sessionId,\n () => this._pauseRecording(),\n () => this._resumeRecording(),\n (triggerType, matchDetail) => this._activateTrigger(triggerType, matchDetail)\n )\n\n // always have to check if the URL is blocked really early,\n // or you risk getting stuck in a loop\n if (this._urlTriggerMatching.urlBlocked && !isRecordingPausedEvent(rawEvent)) {\n return\n }\n\n // we're processing a full snapshot, so we should reset the timer\n if (rawEvent.type === EventType.FullSnapshot) {\n this._scheduleFullSnapshot()\n // Full snapshots reset rrweb's node IDs, so clear any logged node tracking\n this._mutationThrottler?.reset()\n\n // Track the timestamp of the first full snapshot for this session\n // This helps us detect session rotation issues where incremental snapshots\n // are sent before the full snapshot\n this._instance.persistence?.register_once(\n {\n [SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP]: rawEvent.timestamp,\n },\n undefined\n )\n }\n\n // Clear the buffer if waiting for a trigger and only keep data from after the current full snapshot\n if (rawEvent.type === EventType.FullSnapshot && this._strategy?.hasPendingTriggers(this.sessionId)) {\n this._clearBufferBeforeMostRecentMeta()\n }\n\n const throttledEvent = this._mutationThrottler ? this._mutationThrottler.throttleMutations(rawEvent) : rawEvent\n\n if (!throttledEvent) {\n return\n }\n\n // TODO: Re-add ensureMaxMessageSize once we are confident in it\n const event = truncateLargeConsoleLogs(throttledEvent)\n\n // Session lifecycle events ($session_ending, $session_starting) carry their target session ID\n // in the payload. We must extract this BEFORE _updateWindowAndSessionIds runs, because that\n // method triggers checkAndGetSessionAndWindowId() which would update this._sessionId.\n // This is critical for $session_ending which must go to the OLD session, not the new one,\n // and for $session_starting which must go to the NEW session.\n const sessionEndingPayload = getSessionEndingPayload(event)\n const sessionStartingPayload = getSessionStartingPayload(event)\n\n if (sessionEndingPayload || sessionStartingPayload) {\n // Adjust timestamp from payload to avoid artificially extending session duration\n const payload = (sessionEndingPayload ?? sessionStartingPayload) as {\n lastActivityTimestamp?: number\n }\n if (payload?.lastActivityTimestamp) {\n event.timestamp = payload.lastActivityTimestamp\n }\n } else {\n this._updateWindowAndSessionIds(event)\n }\n\n if (rawEvent.type === EventType.FullSnapshot) {\n this._fullSnapshotTimestamps.push([this._sessionId, rawEvent.timestamp])\n if (this._fullSnapshotTimestamps.length > 6) {\n this._fullSnapshotTimestamps = this._fullSnapshotTimestamps.slice(-6)\n }\n }\n\n // Route lifecycle events using their payload IDs:\n // - $session_ending uses currentSessionId (the old session it's ending)\n // - $session_starting uses nextSessionId (the new session it's starting)\n // - All other events use the current session ID\n const targetSessionId =\n sessionEndingPayload?.currentSessionId ?? sessionStartingPayload?.nextSessionId ?? this._sessionId\n const targetWindowId =\n sessionEndingPayload?.currentWindowId ?? sessionStartingPayload?.nextWindowId ?? this._windowId\n\n // When in an idle state we keep recording but don't capture the events,\n // we don't want to return early if idle is 'unknown'\n if (this._isIdle === true && !isAllowedWhenIdle(event)) {\n return\n }\n\n if (isSessionIdleEvent(event)) {\n // session idle events have a timestamp when rrweb sees them\n // which can artificially lengthen a session\n // we know when we detected it based on the payload and can correct the timestamp\n const payload = event.data.payload as SessionIdlePayload\n if (payload) {\n const lastActivity = payload.lastActivityTimestamp\n const threshold = payload.threshold\n event.timestamp = lastActivity + threshold\n }\n }\n\n const { event: eventToSend, size } =\n (this._instance.config.session_recording.compress_events ?? true)\n ? compressEvent(event)\n : { event, size: estimateSize(event) }\n\n const properties = {\n $snapshot_bytes: size,\n $snapshot_data: eventToSend,\n $session_id: targetSessionId,\n $window_id: targetWindowId,\n }\n\n if (event.type === EventType.FullSnapshot && getRRWeb()?.wasMaxDepthReached?.()) {\n this._maxDepthExceeded = true\n }\n\n if (this.status === DISABLED) {\n this._clearBuffer()\n return\n }\n\n this._captureSnapshotBuffered(properties)\n }\n\n get status(): SessionRecordingStatus {\n if (!this._strategy) {\n return DISABLED\n }\n\n const context: RecordingStrategyContext = {\n instance: this._instance,\n sessionId: this.sessionId,\n isSampled: this._isSampled,\n rrwebError: this._rrwebError,\n urlTriggerMatching: this._urlTriggerMatching,\n eventTriggerMatching: this._eventTriggerMatching,\n linkedFlagMatching: this._linkedFlagMatching,\n remoteConfig: this._remoteConfig,\n }\n\n return this._strategy.getStatus(context)\n }\n\n log(message: string, level: 'log' | 'warn' | 'error' = 'log') {\n this._instance.sessionRecording?.onRRwebEmit({\n type: 6,\n data: {\n plugin: 'rrweb/console@1',\n payload: {\n level,\n trace: [],\n // Even though it is a string, we stringify it as that's what rrweb expects\n payload: [JSON.stringify(message)],\n },\n },\n timestamp: Date.now(),\n })\n }\n\n public overrideLinkedFlag() {\n this._linkedFlagMatching.linkedFlagSeen = true\n this._tryTakeFullSnapshot()\n this._reportStarted('linked_flag_overridden')\n }\n\n /**\n * this ignores the sampling config and (if other conditions are met) causes capture to start\n *\n * It is not usual to call this directly,\n * instead call `posthog.startSessionRecording({sampling: true})`\n * */\n public overrideSampling() {\n this._instance.persistence?.register({\n // short-circuits the `makeSamplingDecision` function in the session recording module\n [SESSION_RECORDING_IS_SAMPLED]: this.sessionId,\n })\n this._tryTakeFullSnapshot()\n this._reportStarted('sampling_overridden')\n }\n\n /**\n * this ignores the URL/Event trigger config and (if other conditions are met) causes capture to start\n *\n * It is not usual to call this directly,\n * instead call `posthog.startSessionRecording({trigger: 'url' | 'event'})`\n * */\n public overrideTrigger(triggerType: TriggerType) {\n this._activateTrigger(triggerType)\n }\n\n private _clearFlushBufferTimer() {\n if (this._flushBufferTimer) {\n clearTimeout(this._flushBufferTimer)\n this._flushBufferTimer = undefined\n }\n }\n\n private _flushBuffer(): SnapshotBuffer {\n this._clearFlushBufferTimer()\n\n const isBelowMinimumDuration = this._isBelowMinimumDuration()\n\n if (this.status === BUFFERING || this.status === PAUSED || this.status === DISABLED || isBelowMinimumDuration) {\n this._flushBufferTimer = setTimeout(() => {\n this._flushBuffer()\n }, RECORDING_BUFFER_TIMEOUT)\n return this._buffer\n }\n\n if (this._buffer.data.length > 0) {\n const snapshotEvents = splitBuffer(this._buffer)\n snapshotEvents.forEach((snapshotBuffer) => {\n this._flushedSizeTracker?.trackSize(snapshotBuffer.size)\n this._captureSnapshot({\n $snapshot_bytes: snapshotBuffer.size,\n $snapshot_data: snapshotBuffer.data,\n $session_id: snapshotBuffer.sessionId,\n $window_id: snapshotBuffer.windowId,\n $lib: Config.LIB_NAME,\n $lib_version: Config.LIB_VERSION,\n })\n })\n\n // Notify strategy that initial flush is complete (performance optimization)\n this._strategy?.onFlushComplete()\n }\n\n // buffer is empty, we clear it in case the session id has changed\n return this._clearBuffer()\n }\n\n private _hasPassedMinimumDuration = (): boolean => {\n const persistedSessionId = this._instance.persistence?.props[SESSION_RECORDING_PAST_MINIMUM_DURATION]\n return persistedSessionId === this._sessionId\n }\n\n private _getBufferDuration = (): number | null => {\n if (this._buffer.data.length === 0) {\n return null\n }\n\n const firstTimestamp = this._buffer.data[0]?.timestamp\n const lastTimestamp = this._buffer.data[this._buffer.data.length - 1]?.timestamp\n\n if (!isNumber(firstTimestamp) || !isNumber(lastTimestamp)) {\n return null\n }\n\n return lastTimestamp - firstTimestamp\n }\n\n private _isBelowMinimumDuration = (): boolean => {\n const minimumDuration = this._minimumDuration\n if (!isNumber(minimumDuration)) {\n return false\n }\n\n const strictMode = this._instance.config.session_recording?.strictMinimumDuration ?? false\n\n if (!strictMode) {\n const sessionDuration = this._sessionDuration\n const isPositiveSessionDuration = isNumber(sessionDuration) && sessionDuration >= 0\n return isPositiveSessionDuration && sessionDuration < minimumDuration\n }\n\n if (this._hasPassedMinimumDuration()) {\n return false\n }\n\n const bufferDuration = this._getBufferDuration()\n if (isNull(bufferDuration)) {\n return true\n }\n\n if (bufferDuration >= minimumDuration) {\n this._instance.persistence?.register({\n [SESSION_RECORDING_PAST_MINIMUM_DURATION]: this._sessionId,\n })\n return false\n }\n\n return true\n }\n\n private _captureSnapshotBuffered(properties: Properties) {\n const additionalBytes = 2 + (this._buffer?.data.length || 0) // 2 bytes for the array brackets and 1 byte for each comma\n\n // Extract target session ID from properties to ensure we flush when session changes\n // This is critical for lifecycle events ($session_ending, $session_starting) which may\n // have different target session IDs than this._sessionId\n const targetSessionId = properties.$session_id as string\n\n if (\n !this._isIdle && // we never want to flush when idle\n (this._buffer.size + properties.$snapshot_bytes + additionalBytes > RECORDING_MAX_EVENT_SIZE ||\n this._buffer.sessionId !== targetSessionId)\n ) {\n this._buffer = this._flushBuffer()\n // After flushing, update buffer to use the new target session/window IDs\n this._buffer.sessionId = targetSessionId\n this._buffer.windowId = properties.$window_id as string\n }\n\n this._buffer.size += properties.$snapshot_bytes\n this._buffer.data.push(properties.$snapshot_data)\n this._buffer.sizes.push(properties.$snapshot_bytes)\n\n if (!this._flushBufferTimer && !this._isIdle) {\n this._flushBufferTimer = setTimeout(() => {\n this._flushBuffer()\n }, RECORDING_BUFFER_TIMEOUT)\n }\n }\n\n private _captureSnapshot(properties: Properties) {\n // :TRICKY: Make sure we batch these requests, use a custom endpoint and don't truncate the strings.\n this._instance.capture('$snapshot', properties, {\n _url: this._instance.requestRouter.endpointFor('api', this._endpoint),\n _noTruncate: true,\n _batchKey: SESSION_RECORDING_BATCH_KEY,\n skip_client_rate_limiting: true,\n })\n }\n\n private get _sessionDuration(): number | null {\n const mostRecentSnapshot = this._buffer?.data[this._buffer?.data.length - 1]\n const { sessionStartTimestamp } = this._sessionManager.checkAndGetSessionAndWindowId(true)\n return mostRecentSnapshot ? mostRecentSnapshot.timestamp - sessionStartTimestamp : null\n }\n\n private _clearBufferBeforeMostRecentMeta(): SnapshotBuffer {\n if (!this._buffer || this._buffer.data.length === 0) {\n return this._clearBuffer()\n }\n\n // Find the last meta event index by iterating backwards\n let lastMetaIndex = -1\n for (let i = this._buffer.data.length - 1; i >= 0; i--) {\n if (this._buffer.data[i].type === EventType.Meta) {\n lastMetaIndex = i\n break\n }\n }\n if (lastMetaIndex >= 0) {\n this._buffer.data = this._buffer.data.slice(lastMetaIndex)\n this._buffer.sizes = this._buffer.sizes.slice(lastMetaIndex)\n this._buffer.size = this._buffer.sizes.reduce((a, b) => a + b, 0)\n return this._buffer\n } else {\n return this._clearBuffer()\n }\n }\n\n private _clearBuffer(): SnapshotBuffer {\n this._buffer = {\n size: 0,\n data: [],\n sizes: [],\n sessionId: this._sessionId,\n windowId: this._windowId,\n }\n return this._buffer\n }\n\n private _onBeforeUnload = (): void => {\n // If still buffering (waiting for triggers), discard the buffer\n if (this.status === BUFFERING) {\n this._clearBuffer()\n return\n }\n\n this._flushBuffer()\n }\n\n private _onOffline = (): void => {\n this._tryAddCustomEvent('browser offline', {})\n }\n\n private _onOnline = (): void => {\n this._tryAddCustomEvent('browser online', {})\n }\n\n private _onVisibilityChange = (): void => {\n if (document?.visibilityState) {\n const label = 'window ' + document.visibilityState\n this._tryAddCustomEvent(label, {})\n }\n }\n\n private _reportStarted(startReason: SessionStartReason, tagPayload?: Record) {\n this._instance.register_for_session({\n $session_recording_start_reason: startReason,\n })\n logger.info(startReason.replace('_', ' '), tagPayload)\n if (startReason !== 'session_id_changed') {\n this._tryAddCustomEvent('$recording_started', {\n reason: startReason,\n ...tagPayload,\n })\n }\n }\n\n private _isInteractiveEvent(event: eventWithTime) {\n return (\n event.type === INCREMENTAL_SNAPSHOT_EVENT_TYPE &&\n ACTIVE_SOURCES.indexOf(event.data?.source as IncrementalSource) !== -1\n )\n }\n\n private _updateWindowAndSessionIds(event: eventWithTime) {\n // Some recording events are triggered by non-user events (e.g. \"X minutes ago\" text updating on the screen).\n // We don't want to extend the session or trigger a new session in these cases. These events are designated by event\n // type -> incremental update, and source -> mutation.\n\n const isUserInteraction = this._isInteractiveEvent(event)\n\n if (!isUserInteraction && !this._isIdle) {\n // We check if the lastActivityTimestamp is old enough to go idle\n const timeSinceLastActivity = event.timestamp - this._lastActivityTimestamp\n if (timeSinceLastActivity > this._sessionIdleThresholdMilliseconds) {\n // we mark as idle right away,\n // or else we get multiple idle events\n // if there are lots of non-user activity events being emitted\n this._isIdle = true\n\n // don't take full snapshots while idle\n clearInterval(this._fullSnapshotTimer)\n\n this._tryAddCustomEvent('sessionIdle', {\n eventTimestamp: event.timestamp,\n lastActivityTimestamp: this._lastActivityTimestamp,\n threshold: this._sessionIdleThresholdMilliseconds,\n bufferLength: this._buffer.data.length,\n bufferSize: this._buffer.size,\n })\n\n // proactively flush the buffer in case the session is idle for a long time\n this._flushBuffer()\n }\n }\n\n let returningFromIdle = false\n if (isUserInteraction) {\n this._lastActivityTimestamp = event.timestamp\n if (this._isIdle) {\n const idleWasUnknown = this._isIdle === 'unknown'\n // Remove the idle state\n this._isIdle = false\n // if the idle state was unknown, we don't want to add an event, since we're just in bootup\n // whereas if it was true, we know we've been idle for a while, and we can mark ourselves as returning from idle\n if (!idleWasUnknown) {\n this._tryAddCustomEvent('sessionNoLongerIdle', {\n reason: 'user activity',\n type: event.type,\n })\n returningFromIdle = true\n }\n }\n }\n\n if (this._isIdle) {\n return\n }\n\n // We only want to extend the session if it is an interactive event.\n const { windowId, sessionId } = this._sessionManager.checkAndGetSessionAndWindowId(\n !isUserInteraction,\n event.timestamp\n )\n\n const sessionIdChanged = this._sessionId !== sessionId\n const windowIdChanged = this._windowId !== windowId\n\n this._windowId = windowId\n this._sessionId = sessionId\n\n if (sessionIdChanged || windowIdChanged) {\n this.stop()\n this.start('session_id_changed')\n } else if (returningFromIdle) {\n this._scheduleFullSnapshot()\n }\n }\n\n private _clearConditionalRecordingPersistence(): void {\n this._strategy?.clearConditionalRecordingPersistence()\n }\n\n get sdkDebugProperties(): Properties {\n const { sessionStartTimestamp } = this._sessionManager.checkAndGetSessionAndWindowId(true)\n\n return {\n $recording_status: this.status,\n $sdk_debug_replay_internal_buffer_length: this._buffer.data.length,\n $sdk_debug_replay_internal_buffer_size: this._buffer.size,\n $sdk_debug_current_session_duration: this._sessionDuration,\n $sdk_debug_session_start: sessionStartTimestamp,\n $sdk_debug_replay_flushed_size: this._flushedSizeTracker?.currentTrackedSize,\n $sdk_debug_replay_full_snapshots: this._fullSnapshotTimestamps,\n $snapshot_max_depth_exceeded: this._maxDepthExceeded,\n $sdk_debug_replay_rrweb_error: this._rrwebError,\n }\n }\n\n private _startRecorder() {\n if (this._stopRrweb) {\n return\n }\n\n // rrweb config info: https://github.com/rrweb-io/rrweb/blob/7d5d0033258d6c29599fb08412202d9a2c7b9413/src/record/index.ts#L28\n const sessionRecordingOptions: recordOptions = {\n // a limited set of the rrweb config options that we expose to our users.\n // see https://github.com/rrweb-io/rrweb/blob/master/guide.md\n blockClass: 'ph-no-capture',\n blockSelector: undefined,\n ignoreClass: 'ph-ignore-input',\n maskTextClass: 'ph-mask',\n maskTextSelector: undefined,\n maskTextFn: undefined,\n maskAllInputs: true,\n maskInputOptions: { password: true },\n maskInputFn: undefined,\n slimDOMOptions: {},\n collectFonts: false,\n inlineStylesheet: true,\n recordCrossOriginIframes: false,\n }\n\n // only allows user to set our allowlisted options\n const userSessionRecordingOptions = this._instance.config.session_recording\n for (const [key, value] of Object.entries(userSessionRecordingOptions || {})) {\n if (key in sessionRecordingOptions) {\n if (key === 'maskInputOptions') {\n // ensure password config is set if not included\n sessionRecordingOptions.maskInputOptions = { password: true, ...value }\n } else {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n sessionRecordingOptions[key] = value\n }\n }\n }\n\n if (this._canvasRecording && this._canvasRecording.enabled) {\n sessionRecordingOptions.recordCanvas = true\n sessionRecordingOptions.sampling = { canvas: this._canvasRecording.fps }\n sessionRecordingOptions.dataURLOptions = { type: 'image/webp', quality: this._canvasRecording.quality }\n }\n\n if (this._masking) {\n sessionRecordingOptions.maskAllInputs = this._masking.maskAllInputs ?? true\n sessionRecordingOptions.maskTextSelector = this._masking.maskTextSelector ?? undefined\n sessionRecordingOptions.blockSelector = this._masking.blockSelector ?? undefined\n }\n\n const rrwebRecord = getRRWebRecord()\n if (!rrwebRecord) {\n logger.error(\n '_startRecorder was called but rrwebRecord is not available. This indicates something has gone wrong.'\n )\n return\n }\n\n this._mutationThrottler =\n this._mutationThrottler ??\n new MutationThrottler(rrwebRecord, {\n refillRate: this._instance.config.session_recording.__mutationThrottlerRefillRate,\n bucketSize: this._instance.config.session_recording.__mutationThrottlerBucketSize,\n onBlockedNode: (id, node) => {\n const message = `Too many mutations on node '${id}'. Rate limiting. This could be due to SVG animations or something similar`\n logger.info(message, {\n node: node,\n })\n\n this.log(LOGGER_PREFIX + ' ' + message, 'warn')\n },\n })\n\n const activePlugins = this._gatherRRWebPlugins()\n this._stopRrweb = rrwebRecord({\n emit: (event) => {\n this.onRRwebEmit(event)\n },\n plugins: activePlugins,\n ...sessionRecordingOptions,\n })\n\n if (!this._stopRrweb) {\n this._rrwebError = true\n logger.error(\n 'rrweb failed to start - Loss of recording data is possible. Check the browser console for rrweb errors.'\n )\n return\n }\n\n this._rrwebError = false\n\n // We reset the last activity timestamp, resetting the idle timer\n this._lastActivityTimestamp = Date.now()\n // stay unknown if we're not sure if we're idle or not\n this._isIdle = isBoolean(this._isIdle) ? this._isIdle : 'unknown'\n\n this.tryAddCustomEvent('$remote_config_received', this._remoteConfig)\n this._tryAddCustomEvent('$session_options', {\n sessionRecordingOptions,\n activePlugins: activePlugins.map((p) => p?.name),\n })\n\n this._tryAddCustomEvent('$posthog_config', {\n config: this._instance.config,\n })\n }\n\n tryAddCustomEvent(tag: string, payload: any): boolean {\n return this._tryAddCustomEvent(tag, payload)\n }\n}\n", "import {\n SESSION_RECORDING_IS_SAMPLED,\n SESSION_RECORDING_OVERRIDE_SAMPLING,\n SESSION_RECORDING_OVERRIDE_LINKED_FLAG,\n SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER,\n SESSION_RECORDING_OVERRIDE_URL_TRIGGER,\n SESSION_RECORDING_REMOTE_CONFIG,\n COOKIELESS_ALWAYS,\n} from '../../constants'\nimport { PostHog } from '../../posthog-core'\nimport { RemoteConfigLoader } from '../../remote-config'\nimport { Properties, RemoteConfig, SessionRecordingPersistedConfig, SessionStartReason } from '../../types'\nimport { type eventWithTime } from './types/rrweb-types'\n\nimport { isNullish, isNumber, isUndefined, isValidSampleRate } from '@posthog/core'\nimport { createLogger } from '../../utils/logger'\nimport {\n assignableWindow,\n LazyLoadedSessionRecordingInterface,\n PostHogExtensionKind,\n window,\n} from '../../utils/globals'\nimport { RECORDING_REMOTE_CONFIG_TTL_MS } from './external/lazy-loaded-session-recorder'\nimport {\n AWAITING_CONFIG,\n DISABLED,\n LAZY_LOADING,\n MISSING_CONFIG,\n SessionRecordingStatus,\n TriggerType,\n} from './external/triggerMatching'\nimport type { Extension } from '../types'\n\nconst LOGGER_PREFIX = '[SessionRecording]'\nconst logger = createLogger(LOGGER_PREFIX)\n\nexport class SessionRecording implements Extension {\n _forceAllowLocalhostNetworkCapture: boolean = false\n\n private _recordingStatus: SessionRecordingStatus = DISABLED\n\n private get _config() {\n return this._instance.config\n }\n\n private get _persistence() {\n return this._instance.persistence\n }\n\n private _persistFlagsOnSessionListener: (() => void) | undefined = undefined\n private _lazyLoadedSessionRecording: LazyLoadedSessionRecordingInterface | undefined\n\n public get started(): boolean {\n return !!this._lazyLoadedSessionRecording?.isStarted\n }\n\n get status(): SessionRecordingStatus {\n if (this._recordingStatus === AWAITING_CONFIG || this._recordingStatus === MISSING_CONFIG) {\n return this._recordingStatus\n }\n return this._lazyLoadedSessionRecording?.status ?? this._recordingStatus\n }\n\n constructor(private readonly _instance: PostHog) {\n if (!this._instance.sessionManager) {\n logger.error('started without valid sessionManager')\n throw new Error(LOGGER_PREFIX + ' started without valid sessionManager. This is a bug.')\n }\n\n if (this._config.cookieless_mode === COOKIELESS_ALWAYS) {\n throw new Error(LOGGER_PREFIX + ' cannot be used with cookieless_mode=\"always\"')\n }\n }\n\n initialize() {\n this.startIfEnabledOrStop()\n }\n\n private get _isRecordingEnabled() {\n const enabled_server_side = !!this._instance.get_property(SESSION_RECORDING_REMOTE_CONFIG)?.enabled\n const enabled_client_side = !this._config.disable_session_recording\n const isDisabled = this._config.disable_session_recording || this._instance.consent.isOptedOut()\n return window && enabled_server_side && enabled_client_side && !isDisabled\n }\n\n startIfEnabledOrStop(startReason?: SessionStartReason) {\n if (this._isRecordingEnabled && this._lazyLoadedSessionRecording?.isStarted) {\n return\n }\n\n // According to the rrweb docs, rrweb is not supported on IE11 and below:\n // \"rrweb does not support IE11 and below because it uses the MutationObserver API, which was supported by these browsers.\"\n // https://github.com/rrweb-io/rrweb/blob/master/guide.md#compatibility-note\n //\n // However, MutationObserver does exist on IE11, it just doesn't work well and does not detect all changes.\n // Instead, when we load \"recorder.js\", the first JS error is about \"Object.assign\" and \"Array.from\" being undefined.\n // Thus instead of MutationObserver, we look for this function and block recording if it's undefined.\n const canRunReplay = !isUndefined(Object.assign) && !isUndefined(Array.from)\n if (this._isRecordingEnabled && canRunReplay) {\n this._lazyLoadAndStart(startReason)\n logger.info('starting')\n } else {\n this._recordingStatus = DISABLED\n this.stopRecording()\n }\n }\n\n /**\n * session recording waits until it receives remote config before loading the script\n * this is to ensure we can control the script name remotely\n * and because we wait until we have local and remote config to determine if we should start at all\n * if start is called and there is no remote config then we wait until there is\n */\n private _lazyLoadAndStart(startReason?: SessionStartReason) {\n // by checking `_isRecordingEnabled` here we know that\n // we have stored remote config and client config to read\n // replay waits for both local and remote config before starting\n if (!this._isRecordingEnabled) {\n return\n }\n\n if (this._recordingStatus !== AWAITING_CONFIG && this._recordingStatus !== MISSING_CONFIG) {\n this._recordingStatus = LAZY_LOADING\n }\n\n // If recorder.js is already loaded (if array.full.js snippet is used or posthog-js/dist/recorder is\n // imported), don't load the script. Otherwise, remotely import recorder.js from cdn since it hasn't been loaded.\n if (\n !assignableWindow?.__PosthogExtensions__?.rrweb?.record ||\n !assignableWindow.__PosthogExtensions__?.initSessionRecording\n ) {\n assignableWindow.__PosthogExtensions__?.loadExternalDependency?.(\n this._instance,\n this._scriptName,\n (err) => {\n if (err) {\n return logger.error('could not load recorder', err)\n }\n this._onScriptLoaded(startReason)\n }\n )\n } else {\n this._onScriptLoaded(startReason)\n }\n }\n\n stopRecording() {\n this._persistFlagsOnSessionListener?.()\n this._persistFlagsOnSessionListener = undefined\n this._lazyLoadedSessionRecording?.stop()\n }\n\n private _discardRecording() {\n this._persistFlagsOnSessionListener?.()\n this._persistFlagsOnSessionListener = undefined\n this._lazyLoadedSessionRecording?.discard()\n }\n\n private _resetSampling() {\n this._persistence?.unregister(SESSION_RECORDING_IS_SAMPLED)\n }\n\n private _validateSampleRate(rate: unknown, source: string): number | null {\n if (isNullish(rate)) {\n return null\n }\n const parsed = isNumber(rate) ? rate : parseFloat(rate as string)\n if (!isValidSampleRate(parsed)) {\n logger.warn(`${source} must be between 0 and 1. Ignoring invalid value:`, rate)\n return null\n }\n return parsed\n }\n\n private _persistRemoteConfig(response: RemoteConfig): void {\n if (this._persistence) {\n const persistence = this._persistence\n\n const persistResponse = () => {\n const sessionRecordingConfigResponse =\n response.sessionRecording === false ? undefined : response.sessionRecording\n\n const localSampleRate = this._validateSampleRate(\n this._config.session_recording?.sampleRate,\n 'session_recording.sampleRate'\n )\n const remoteSampleRate = this._validateSampleRate(\n sessionRecordingConfigResponse?.sampleRate,\n 'remote config sampleRate'\n )\n const parsedSampleRate = localSampleRate ?? remoteSampleRate\n if (isNullish(parsedSampleRate)) {\n this._resetSampling()\n }\n\n const receivedMinimumDuration = sessionRecordingConfigResponse?.minimumDurationMilliseconds\n\n persistence.register({\n [SESSION_RECORDING_REMOTE_CONFIG]: {\n cache_timestamp: Date.now(),\n enabled: !!sessionRecordingConfigResponse,\n ...sessionRecordingConfigResponse,\n networkPayloadCapture: {\n capturePerformance: response.capturePerformance,\n ...sessionRecordingConfigResponse?.networkPayloadCapture,\n },\n canvasRecording: {\n enabled: sessionRecordingConfigResponse?.recordCanvas,\n fps: sessionRecordingConfigResponse?.canvasFps,\n quality: sessionRecordingConfigResponse?.canvasQuality,\n },\n sampleRate: parsedSampleRate,\n minimumDurationMilliseconds: isUndefined(receivedMinimumDuration)\n ? null\n : receivedMinimumDuration,\n endpoint: sessionRecordingConfigResponse?.endpoint,\n triggerMatchType: sessionRecordingConfigResponse?.triggerMatchType,\n masking: sessionRecordingConfigResponse?.masking,\n urlTriggers: sessionRecordingConfigResponse?.urlTriggers,\n // V2 fields - will be undefined for V1 configs\n version: sessionRecordingConfigResponse?.version,\n triggerGroups: sessionRecordingConfigResponse?.triggerGroups,\n } satisfies SessionRecordingPersistedConfig,\n })\n }\n\n persistResponse()\n\n // in case we see multiple flags responses, we should only use the response from the most recent one\n this._persistFlagsOnSessionListener?.()\n // we 100% know there is a session manager by this point\n this._persistFlagsOnSessionListener = this._instance.sessionManager?.onSessionId(persistResponse)\n }\n }\n\n onRemoteConfig(response: RemoteConfig) {\n if (!('sessionRecording' in response)) {\n if (this._recordingStatus === AWAITING_CONFIG) {\n this._recordingStatus = MISSING_CONFIG\n logger.warn('config refresh failed, recording will not start until page reload')\n }\n this.startIfEnabledOrStop()\n return\n }\n if (response.sessionRecording === false) {\n this._persistRemoteConfig(response)\n this._discardRecording()\n return\n }\n\n this._persistRemoteConfig(response)\n this.startIfEnabledOrStop()\n }\n\n log(message: string, level: 'log' | 'warn' | 'error' = 'log') {\n if (this._lazyLoadedSessionRecording?.log) {\n this._lazyLoadedSessionRecording.log(message, level)\n } else {\n logger.warn('log called before recorder was ready')\n }\n }\n\n private get _scriptName(): PostHogExtensionKind {\n const remoteConfig: SessionRecordingPersistedConfig | undefined = this._instance?.persistence?.get_property(\n SESSION_RECORDING_REMOTE_CONFIG\n )\n return (remoteConfig?.scriptConfig?.script as PostHogExtensionKind) || 'lazy-recorder'\n }\n\n private _isRemoteConfigFresh(): boolean {\n const persistedConfig = this._instance.get_property(SESSION_RECORDING_REMOTE_CONFIG)\n if (!persistedConfig) {\n return false\n }\n const config = typeof persistedConfig === 'object' ? persistedConfig : JSON.parse(persistedConfig)\n // default to now so that configs persisted by older SDK versions\n // (which never set cache_timestamp) are treated as fresh\n const cacheTimestamp = config.cache_timestamp ?? Date.now()\n return Date.now() - cacheTimestamp <= RECORDING_REMOTE_CONFIG_TTL_MS\n }\n\n private _onScriptLoaded(startReason?: SessionStartReason) {\n if (!assignableWindow.__PosthogExtensions__?.initSessionRecording) {\n logger.warn(\n 'Called on script loaded before session recording is available. This can be caused by adblockers.'\n )\n this._instance.register_for_session({\n $sdk_debug_recording_script_not_loaded: true,\n })\n return\n }\n\n if (!this._lazyLoadedSessionRecording) {\n this._lazyLoadedSessionRecording = assignableWindow.__PosthogExtensions__?.initSessionRecording(\n this._instance\n )\n ;(this._lazyLoadedSessionRecording as any)._forceAllowLocalhostNetworkCapture =\n this._forceAllowLocalhostNetworkCapture\n }\n\n if (!this._isRemoteConfigFresh()) {\n if (this._recordingStatus === MISSING_CONFIG || this._recordingStatus === AWAITING_CONFIG) {\n return\n }\n this._recordingStatus = AWAITING_CONFIG\n logger.info('persisted remote config is stale, requesting fresh config before starting')\n new RemoteConfigLoader(this._instance).load()\n return\n }\n\n this._recordingStatus = LAZY_LOADING\n this._lazyLoadedSessionRecording.start(startReason)\n }\n\n /**\n * this is maintained on the public API only because it has always been on the public API\n * if you are calling this directly you are certainly doing something wrong\n * @deprecated\n */\n onRRwebEmit(rawEvent: eventWithTime) {\n this._lazyLoadedSessionRecording?.onRRwebEmit?.(rawEvent)\n }\n\n /**\n * this ignores the linked flag config and (if other conditions are met) causes capture to start\n *\n * It is not usual to call this directly,\n * instead call `posthog.startSessionRecording({linked_flag: true})`\n * */\n public overrideLinkedFlag() {\n if (!this._lazyLoadedSessionRecording) {\n this._persistence?.register({\n [SESSION_RECORDING_OVERRIDE_LINKED_FLAG]: true,\n })\n }\n\n this._lazyLoadedSessionRecording?.overrideLinkedFlag()\n }\n\n /**\n * this ignores the sampling config and (if other conditions are met) causes capture to start\n *\n * It is not usual to call this directly,\n * instead call `posthog.startSessionRecording({sampling: true})`\n * */\n public overrideSampling() {\n if (!this._lazyLoadedSessionRecording) {\n this._persistence?.register({\n [SESSION_RECORDING_OVERRIDE_SAMPLING]: true,\n })\n }\n\n this._lazyLoadedSessionRecording?.overrideSampling()\n }\n\n /**\n * this ignores the URL/Event trigger config and (if other conditions are met) causes capture to start\n *\n * It is not usual to call this directly,\n * instead call `posthog.startSessionRecording({trigger: 'url' | 'event'})`\n * */\n public overrideTrigger(triggerType: TriggerType) {\n if (!this._lazyLoadedSessionRecording) {\n this._persistence?.register({\n [triggerType === 'url'\n ? SESSION_RECORDING_OVERRIDE_URL_TRIGGER\n : SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER]: true,\n })\n }\n\n this._lazyLoadedSessionRecording?.overrideTrigger(triggerType)\n }\n\n /*\n * whenever we capture an event, we add these properties to the event\n * these are used to debug issues with the session recording\n * when looking at the event feed for a session\n */\n get sdkDebugProperties(): Properties {\n return (\n this._lazyLoadedSessionRecording?.sdkDebugProperties || {\n $recording_status: this.status,\n }\n )\n }\n\n /**\n * This adds a custom event to the session recording\n *\n * It is not intended for arbitrary public use - playback only displays known custom events\n * And is exposed on the public interface only so that other parts of the SDK are able to use it\n *\n * if you are calling this from client code, you're probably looking for `posthog.capture('$custom_event', {...})`\n */\n tryAddCustomEvent(tag: string, payload: any): boolean {\n return !!this._lazyLoadedSessionRecording?.tryAddCustomEvent(tag, payload)\n }\n}\n", "import RageClick from './extensions/rageclick'\nimport { DeadClickCandidate, Properties, RemoteConfig } from './types'\nimport { PostHog } from './posthog-core'\n\nimport { document, window } from './utils/globals'\nimport { getEventTarget, getParentElement } from './autocapture-utils'\nimport { DOM_EVENT_BEFOREUNLOAD, DOM_EVENT_VISIBILITYCHANGE, HEATMAPS_ENABLED_SERVER_SIDE } from './constants'\nimport { isNumber, isNullish, isEmptyObject, isObject } from '@posthog/core'\nimport { createLogger } from './utils/logger'\nimport { isElementInToolbar, isElementNode, isTag } from './utils/element-utils'\nimport { DeadClicksAutocapture, isDeadClicksEnabledForHeatmaps } from './extensions/dead-clicks-autocapture'\nimport { includes } from '@posthog/core'\nimport { addEventListener } from './utils'\nimport { maskQueryParams } from './utils/request-utils'\nimport { PERSONAL_DATA_CAMPAIGN_PARAMS, MASKED } from './utils/event-utils'\nimport type { Extension } from './extensions/types'\n\nconst DEFAULT_FLUSH_INTERVAL = 5000\n\nconst logger = createLogger('[Heatmaps]')\n\ntype HeatmapEventBuffer =\n | {\n [key: string]: Properties[]\n }\n | undefined\n\nfunction elementOrParentPositionMatches(el: Element | null, matches: string[], breakOnElement?: Element): boolean {\n let curEl: Element | null | false = el\n\n while (curEl && isElementNode(curEl) && !isTag(curEl, 'body')) {\n if (curEl === breakOnElement) {\n return false\n }\n\n if (includes(matches, window?.getComputedStyle(curEl).position)) {\n return true\n }\n\n curEl = getParentElement(curEl)\n }\n\n return false\n}\n\nfunction isValidMouseEvent(e: unknown): e is MouseEvent {\n return isObject(e) && 'clientX' in e && 'clientY' in e && isNumber(e.clientX) && isNumber(e.clientY)\n}\n\nfunction shouldPoll(document: Document | undefined): boolean {\n return document?.visibilityState === 'visible'\n}\n\nexport class Heatmaps implements Extension {\n instance: PostHog\n rageclicks: RageClick\n _enabledServerSide: boolean = false\n\n private get _config() {\n return this.instance.config\n }\n\n _initialized = false\n _mouseMoveTimeout: ReturnType | undefined\n\n private _buffer: HeatmapEventBuffer\n private _flushInterval: ReturnType | null = null\n private _deadClicksCapture: DeadClicksAutocapture | undefined\n private _onClickHandler: ((e: Event) => void) | undefined\n private _onMouseMoveHandler: ((e: Event) => void) | undefined\n private _flushHandler: (() => void) | undefined\n private _onVisibilityChange_handler: (() => void) | undefined\n\n constructor(instance: PostHog) {\n this.instance = instance\n this._enabledServerSide = !!this.instance.persistence?.props[HEATMAPS_ENABLED_SERVER_SIDE]\n this.rageclicks = new RageClick(instance.config.rageclick)\n }\n\n initialize() {\n this.startIfEnabled()\n }\n\n public get flushIntervalMilliseconds(): number {\n let flushInterval = DEFAULT_FLUSH_INTERVAL\n if (isObject(this._config.capture_heatmaps) && this._config.capture_heatmaps.flush_interval_milliseconds) {\n flushInterval = this._config.capture_heatmaps.flush_interval_milliseconds\n }\n return flushInterval\n }\n\n public get isEnabled(): boolean {\n if (!isNullish(this._config.capture_heatmaps)) {\n return this._config.capture_heatmaps !== false\n }\n if (!isNullish(this._config.enable_heatmaps)) {\n return this._config.enable_heatmaps\n }\n return this._enabledServerSide\n }\n\n public startIfEnabled(): void {\n if (this.isEnabled) {\n // nested if here since we only want to run the else\n // if this.enabled === false\n // not if this method is called more than once\n if (this._initialized) {\n return\n }\n logger.info('starting...')\n this._setupListeners()\n this._onVisibilityChange()\n } else {\n clearInterval(this._flushInterval ?? undefined)\n this._removeListeners()\n this.getAndClearBuffer()\n }\n }\n\n public onRemoteConfig(response: RemoteConfig) {\n if (!('heatmaps' in response)) {\n return\n }\n\n const optIn = !!response['heatmaps']\n\n if (this.instance.persistence) {\n this.instance.persistence.register({\n [HEATMAPS_ENABLED_SERVER_SIDE]: optIn,\n })\n }\n // store this in-memory in case persistence is disabled\n this._enabledServerSide = optIn\n this.startIfEnabled()\n }\n\n public getAndClearBuffer(): HeatmapEventBuffer {\n const buffer = this._buffer\n this._buffer = undefined\n return buffer\n }\n\n private _onDeadClick(click: DeadClickCandidate): void {\n this._onClick(click.originalEvent, 'deadclick')\n }\n\n private _onVisibilityChange(): void {\n // always clear the interval just in case\n if (this._flushInterval) {\n clearInterval(this._flushInterval)\n }\n\n this._flushInterval = shouldPoll(document)\n ? setInterval(this._flush.bind(this), this.flushIntervalMilliseconds)\n : null\n }\n\n private _setupListeners(): void {\n if (!window || !document) {\n return\n }\n\n this._flushHandler = this._flush.bind(this)\n addEventListener(window, DOM_EVENT_BEFOREUNLOAD, this._flushHandler)\n\n this._onClickHandler = (e) => this._onClick((e || window?.event) as MouseEvent)\n addEventListener(document, 'click', this._onClickHandler, { capture: true })\n\n this._onMouseMoveHandler = (e) => this._onMouseMove((e || window?.event) as MouseEvent)\n addEventListener(document, 'mousemove', this._onMouseMoveHandler, { capture: true })\n\n this._deadClicksCapture = new DeadClicksAutocapture(\n this.instance,\n isDeadClicksEnabledForHeatmaps,\n this._onDeadClick.bind(this)\n )\n this._deadClicksCapture.startIfEnabledOrStop()\n\n this._onVisibilityChange_handler = this._onVisibilityChange.bind(this)\n addEventListener(document, DOM_EVENT_VISIBILITYCHANGE, this._onVisibilityChange_handler)\n\n this._initialized = true\n }\n\n private _removeListeners(): void {\n if (!window || !document) {\n return\n }\n\n if (this._flushHandler) {\n window.removeEventListener(DOM_EVENT_BEFOREUNLOAD, this._flushHandler)\n }\n\n if (this._onClickHandler) {\n document.removeEventListener('click', this._onClickHandler, { capture: true })\n }\n\n if (this._onMouseMoveHandler) {\n document.removeEventListener('mousemove', this._onMouseMoveHandler, { capture: true })\n }\n\n if (this._onVisibilityChange_handler) {\n document.removeEventListener(DOM_EVENT_VISIBILITYCHANGE, this._onVisibilityChange_handler)\n }\n\n clearTimeout(this._mouseMoveTimeout)\n\n this._deadClicksCapture?.stop()\n\n this._initialized = false\n }\n\n private _getProperties(e: MouseEvent, type: string): Properties {\n // We need to know if the target element is fixed or not\n // If fixed then we won't account for scrolling\n // If not then we will account for scrolling\n\n const scrollY = this.instance.scrollManager.scrollY()\n const scrollX = this.instance.scrollManager.scrollX()\n const scrollElement = this.instance.scrollManager.scrollElement()\n\n const isFixedOrSticky = elementOrParentPositionMatches(getEventTarget(e), ['fixed', 'sticky'], scrollElement)\n\n return {\n x: e.clientX + (isFixedOrSticky ? 0 : scrollX),\n y: e.clientY + (isFixedOrSticky ? 0 : scrollY),\n target_fixed: isFixedOrSticky,\n type,\n }\n }\n\n private _onClick(e: MouseEvent, type: string = 'click'): void {\n if (isElementInToolbar(e.target) || !isValidMouseEvent(e)) {\n return\n }\n\n const properties = this._getProperties(e, type)\n\n if (this.rageclicks?.isRageClick(e.clientX, e.clientY, new Date().getTime())) {\n this._capture({\n ...properties,\n type: 'rageclick',\n })\n }\n\n this._capture(properties)\n }\n\n private _onMouseMove(e: Event): void {\n if (isElementInToolbar(e.target) || !isValidMouseEvent(e)) {\n return\n }\n\n clearTimeout(this._mouseMoveTimeout)\n\n this._mouseMoveTimeout = setTimeout(() => {\n this._capture(this._getProperties(e as MouseEvent, 'mousemove'))\n }, 500)\n }\n\n private _capture(properties: Properties): void {\n if (!window) {\n return\n }\n\n const href = window.location.href\n\n // mask url query params\n const maskPersonalDataProperties = this._config.mask_personal_data_properties\n const customPersonalDataProperties = this._config.custom_personal_data_properties\n\n const paramsToMask = maskPersonalDataProperties\n ? [...PERSONAL_DATA_CAMPAIGN_PARAMS, ...(customPersonalDataProperties || [])]\n : []\n\n const url = maskQueryParams(href, paramsToMask, MASKED)\n\n this._buffer = this._buffer || {}\n\n if (!this._buffer[url]) {\n this._buffer[url] = []\n }\n\n this._buffer[url].push(properties)\n }\n\n private _flush(): void {\n if (!this._buffer || isEmptyObject(this._buffer)) {\n return\n }\n\n this.instance.capture('$$heatmap', {\n $heatmap_data: this.getAndClearBuffer(),\n })\n }\n}\n", "import { PostHog } from './posthog-core'\nimport { ProductTour, ProductTourCallback } from './posthog-product-tours-types'\nimport { PRODUCT_TOURS, PRODUCT_TOURS_ENABLED_SERVER_SIDE } from './constants'\nimport { RemoteConfig } from './types'\nimport { createLogger } from './utils/logger'\nimport { isArray, isNullish } from '@posthog/core'\nimport { assignableWindow } from './utils/globals'\nimport { Extension } from './extensions/types'\n\nconst logger = createLogger('[Product Tours]')\n\ninterface ProductTourManagerInterface {\n start: () => void\n stop: () => void\n showTourById: (tourId: string) => void\n previewTour: (tour: ProductTour) => void\n dismissTour: (reason: string) => void\n nextStep: () => void\n previousStep: () => void\n getActiveProductTours: (callback: ProductTourCallback) => void\n resetTour: (tourId: string) => void\n resetAllTours: () => void\n cancelPendingTour: (tourId: string) => void\n}\n\nconst isProductToursEnabled = (instance: PostHog): boolean => {\n if (instance.config.disable_product_tours) {\n return false\n }\n return !!instance.persistence?.get_property(PRODUCT_TOURS_ENABLED_SERVER_SIDE)\n}\n\nexport class PostHogProductTours implements Extension {\n private _instance: PostHog\n private _productTourManager: ProductTourManagerInterface | null = null\n private _cachedTours: ProductTour[] | null = null\n\n private get _persistence() {\n return this._instance.persistence\n }\n\n constructor(instance: PostHog) {\n this._instance = instance\n }\n\n initialize() {\n this.loadIfEnabled()\n }\n\n onRemoteConfig(response: RemoteConfig): void {\n if (!('productTours' in response)) {\n return\n }\n\n if (this._persistence) {\n this._persistence.register({\n [PRODUCT_TOURS_ENABLED_SERVER_SIDE]: !!response.productTours,\n })\n }\n this.loadIfEnabled()\n }\n\n loadIfEnabled(): void {\n if (this._productTourManager || !isProductToursEnabled(this._instance)) {\n return\n }\n this._loadScript(() => this._startProductTours())\n }\n\n private _loadScript(cb: () => void): void {\n if (assignableWindow.__PosthogExtensions__?.generateProductTours) {\n cb()\n return\n }\n assignableWindow.__PosthogExtensions__?.loadExternalDependency?.(this._instance, 'product-tours', (err) => {\n if (err) {\n logger.error('Could not load product tours script', err)\n return\n }\n cb()\n })\n }\n\n private _startProductTours(): void {\n if (this._productTourManager || !assignableWindow.__PosthogExtensions__?.generateProductTours) {\n return\n }\n this._productTourManager = assignableWindow.__PosthogExtensions__.generateProductTours(this._instance, true)\n }\n\n getProductTours(callback: ProductTourCallback, forceReload: boolean = false): void {\n if (isArray(this._cachedTours) && !forceReload) {\n callback(this._cachedTours, { isLoaded: true })\n return\n }\n\n const persistence = this._persistence\n if (persistence) {\n const storedTours = persistence.props[PRODUCT_TOURS]\n if (isArray(storedTours) && !forceReload) {\n this._cachedTours = storedTours\n callback(storedTours, { isLoaded: true })\n return\n }\n }\n\n this._instance._send_request({\n url: this._instance.requestRouter.endpointFor(\n 'api',\n `/api/product_tours/?token=${this._instance.config.token}`\n ),\n method: 'GET',\n callback: (response) => {\n const statusCode = response.statusCode\n if (statusCode !== 200 || !response.json) {\n const error = `Product Tours API could not be loaded, status: ${statusCode}`\n logger.error(error)\n callback([], { isLoaded: false, error })\n return\n }\n\n const tours: ProductTour[] = isArray(response.json.product_tours) ? response.json.product_tours : []\n this._cachedTours = tours\n\n if (persistence) {\n persistence.register({ [PRODUCT_TOURS]: tours })\n }\n\n callback(tours, { isLoaded: true })\n },\n })\n }\n\n getActiveProductTours(callback: ProductTourCallback): void {\n if (isNullish(this._productTourManager)) {\n callback([], { isLoaded: false, error: 'Product tours not loaded' })\n return\n }\n this._productTourManager.getActiveProductTours(callback)\n }\n\n showProductTour(tourId: string): void {\n this._productTourManager?.showTourById(tourId)\n }\n\n // force load product tours extension and render a tour,\n // ignoring all display conditions.\n previewTour(tour: ProductTour): void {\n if (this._productTourManager) {\n this._productTourManager.previewTour(tour)\n return\n }\n\n this._loadScript(() => {\n this._startProductTours()\n this._productTourManager?.previewTour(tour)\n })\n }\n\n dismissProductTour(): void {\n this._productTourManager?.dismissTour('user_clicked_skip')\n }\n\n nextStep(): void {\n this._productTourManager?.nextStep()\n }\n\n previousStep(): void {\n this._productTourManager?.previousStep()\n }\n\n clearCache(): void {\n this._cachedTours = null\n this._persistence?.unregister(PRODUCT_TOURS)\n }\n\n resetTour(tourId: string): void {\n this._productTourManager?.resetTour(tourId)\n }\n\n resetAllTours(): void {\n this._productTourManager?.resetAllTours()\n }\n\n cancelPendingTour(tourId: string): void {\n this._productTourManager?.cancelPendingTour(tourId)\n }\n}\n", "import type { Extension } from './extensions/types'\nimport { PostHog } from './posthog-core'\nimport { CaptureResult, Properties, RemoteConfig, SiteApp, SiteAppGlobals, SiteAppLoader } from './types'\nimport { assignableWindow } from './utils/globals'\nimport { createLogger } from './utils/logger'\n\nconst logger = createLogger('[SiteApps]')\nconst APP_INIT_ERROR = 'Error while initializing PostHog app with config id '\n\nexport class SiteApps implements Extension {\n apps: Record\n\n private _stopBuffering?: () => void\n private _bufferedInvocations: SiteAppGlobals[]\n\n constructor(private _instance: PostHog) {\n // events captured between loading posthog-js and the site app; up to 1000 events\n this._bufferedInvocations = []\n this.apps = {}\n }\n\n public get isEnabled(): boolean {\n return !!this._instance.config.opt_in_site_apps\n }\n\n private _eventCollector(_eventName: string, eventPayload?: CaptureResult | undefined) {\n if (!eventPayload) {\n return\n }\n const globals = this.globalsForEvent(eventPayload)\n this._bufferedInvocations.push(globals)\n if (this._bufferedInvocations.length > 1000) {\n this._bufferedInvocations = this._bufferedInvocations.slice(10)\n }\n }\n\n get siteAppLoaders(): SiteAppLoader[] | undefined {\n return assignableWindow._POSTHOG_REMOTE_CONFIG?.[this._instance.config.token]?.siteApps\n }\n\n initialize() {\n if (this.isEnabled) {\n const stop = this._instance._addCaptureHook(this._eventCollector.bind(this))\n this._stopBuffering = () => {\n stop()\n this._bufferedInvocations = []\n this._stopBuffering = undefined\n }\n }\n }\n\n globalsForEvent(event: CaptureResult): SiteAppGlobals {\n if (!event) {\n throw new Error('Event payload is required')\n }\n const groups: SiteAppGlobals['groups'] = {}\n const groupIds = this._instance.get_property('$groups') || []\n const groupProperties: Record =\n this._instance.get_property('$stored_group_properties') || {}\n for (const [type, properties] of Object.entries(groupProperties)) {\n groups[type] = { id: groupIds[type], type, properties }\n }\n const { $set_once, $set, ..._event } = event\n const globals = {\n event: {\n ..._event,\n properties: {\n ...event.properties,\n ...($set ? { $set: { ...(event.properties?.$set ?? {}), ...$set } } : {}),\n ...($set_once ? { $set_once: { ...(event.properties?.$set_once ?? {}), ...$set_once } } : {}),\n },\n elements_chain: event.properties?.['$elements_chain'] ?? '',\n // TODO:\n // - elements_chain_href: '',\n // - elements_chain_texts: [] as string[],\n // - elements_chain_ids: [] as string[],\n // - elements_chain_elements: [] as string[],\n distinct_id: event.properties?.['distinct_id'],\n },\n person: {\n properties: this._instance.get_property('$stored_person_properties'),\n },\n groups,\n }\n return globals\n }\n\n setupSiteApp(loader: SiteAppLoader) {\n const app = this.apps[loader.id]\n const processBufferedEvents = () => {\n if (!app.errored && this._bufferedInvocations.length) {\n logger.info(`Processing ${this._bufferedInvocations.length} events for site app with id ${loader.id}`)\n this._bufferedInvocations.forEach((globals) => app.processEvent?.(globals))\n app.processedBuffer = true\n }\n\n if (Object.values(this.apps).every((app) => app.processedBuffer || app.errored)) {\n this._stopBuffering?.()\n }\n }\n\n let hasInitReturned = false\n const onLoaded = (success: boolean) => {\n app.errored = !success\n app.loaded = true\n logger.info(`Site app with id ${loader.id} ${success ? 'loaded' : 'errored'}`)\n // ensure that we don't call processBufferedEvents until after init() returns and we've set up processEvent\n if (hasInitReturned) {\n processBufferedEvents()\n }\n }\n\n try {\n const { processEvent } = loader.init({\n posthog: this._instance,\n callback: (success) => {\n onLoaded(success)\n },\n })\n if (processEvent) {\n app.processEvent = processEvent\n }\n hasInitReturned = true\n } catch (e) {\n logger.error(APP_INIT_ERROR + loader.id, e)\n onLoaded(false)\n }\n\n // if the app loaded synchronously, process the events now\n if (hasInitReturned && app.loaded) {\n try {\n processBufferedEvents()\n } catch (e) {\n logger.error(`Error while processing buffered events PostHog app with config id ${loader.id}`, e)\n app.errored = true\n }\n }\n }\n\n private _setupSiteApps() {\n const siteAppLoaders = this.siteAppLoaders || []\n\n // do this in 2 passes, so that this.apps is populated before we call init\n for (const loader of siteAppLoaders) {\n this.apps[loader.id] = {\n id: loader.id,\n loaded: false,\n errored: false,\n processedBuffer: false,\n }\n }\n for (const loader of siteAppLoaders) {\n this.setupSiteApp(loader)\n }\n }\n\n private _onCapturedEvent(event: CaptureResult) {\n if (Object.keys(this.apps).length === 0) {\n return\n }\n\n const globals = this.globalsForEvent(event)\n\n for (const app of Object.values(this.apps)) {\n try {\n app.processEvent?.(globals)\n } catch (e) {\n logger.error(`Error while processing event ${event.event} for site app ${app.id}`, e)\n }\n }\n }\n\n onRemoteConfig(response: RemoteConfig): void {\n if (this.siteAppLoaders?.length) {\n if (!this.isEnabled) {\n logger.error(`PostHog site apps are disabled. Enable the \"opt_in_site_apps\" config to proceed.`)\n return\n }\n\n this._setupSiteApps()\n\n // NOTE: We could improve this to only fire if we actually have listeners for the event\n this._instance.on('eventCaptured', (event) => this._onCapturedEvent(event))\n\n return\n }\n\n // NOTE: Below this is now only the fallback for legacy site app support. Once we have fully removed to the remote config loader we can get rid of this\n\n this._stopBuffering?.()\n\n if (!response['siteApps']?.length) {\n return\n }\n\n if (!this.isEnabled) {\n logger.error(`PostHog site apps are disabled. Enable the \"opt_in_site_apps\" config to proceed.`)\n return\n }\n\n for (const { id, url } of response['siteApps']) {\n assignableWindow[`__$$ph_site_app_${id}`] = this._instance\n assignableWindow.__PosthogExtensions__?.loadSiteApp?.(this._instance, url, (err) => {\n if (err) {\n return logger.error(APP_INIT_ERROR + id, err)\n }\n })\n }\n }\n}\n", "import { isNullish } from '@posthog/core'\n\nexport function extractHref(elementsChain: string): string {\n const match = elementsChain.match(/(?::|\")href=\"(.*?)\"/)\n return match ? match[1] : ''\n}\n\nexport function extractTexts(elementsChain: string): string[] {\n const texts: string[] = []\n const regex = /(?::|\")text=\"(.*?)\"/g\n let match\n while (!isNullish((match = regex.exec(elementsChain)))) {\n if (!texts.includes(match[1])) {\n texts.push(match[1])\n }\n }\n return texts\n}\n\nexport function matchString(\n value: string | undefined | null,\n pattern: string,\n matching: 'exact' | 'contains' | 'regex'\n): boolean {\n if (isNullish(value)) return false\n switch (matching) {\n case 'exact':\n return value === pattern\n case 'contains': {\n // Simulating SQL LIKE behavior (_ = any single character, % = any zero or more characters)\n const likePattern = pattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/_/g, '.')\n .replace(/%/g, '.*')\n return new RegExp(likePattern, 'i').test(value)\n }\n case 'regex':\n try {\n return new RegExp(pattern).test(value)\n } catch {\n return false\n }\n default:\n return false\n }\n}\n\nexport function matchTexts(texts: string[], pattern: string, matching: 'exact' | 'contains' | 'regex'): boolean {\n return texts.some((text) => matchString(text, pattern, matching))\n}\n", "import { PostHog } from '../../posthog-core'\nimport { ActionStepType, PropertyFilters, SurveyActionType, SurveyElement } from '../../posthog-surveys-types'\nimport { SimpleEventEmitter } from '../../utils/simple-event-emitter'\nimport { CaptureResult, PropertyMatchType } from '../../types'\nimport { isArray, isUndefined } from '@posthog/core'\nimport { matchPropertyFilters } from '../../utils/property-utils'\nimport { extractTexts, extractHref, matchString, matchTexts } from '../../utils/elements-chain-utils'\n\nexport class ActionMatcher {\n private readonly _actionRegistry?: Set\n private readonly _instance?: PostHog\n private readonly _actionEvents: Set\n private _debugEventEmitter = new SimpleEventEmitter()\n\n constructor(instance?: PostHog) {\n this._instance = instance\n this._actionEvents = new Set()\n this._actionRegistry = new Set()\n }\n\n init() {\n if (!isUndefined(this._instance?._addCaptureHook)) {\n const matchEventToAction = (eventName: string, eventPayload: any) => {\n this.on(eventName, eventPayload)\n }\n this._instance?._addCaptureHook(matchEventToAction)\n }\n }\n\n register(actions: SurveyActionType[]): void {\n if (isUndefined(this._instance?._addCaptureHook)) {\n return\n }\n\n actions.forEach((action) => {\n this._actionRegistry?.add(action)\n action.steps?.forEach((step) => {\n this._actionEvents?.add(step?.event || '')\n })\n })\n\n if (this._instance?.autocapture) {\n const selectorsToWatch: Set = new Set()\n actions.forEach((action) => {\n action.steps?.forEach((step) => {\n if (step?.selector) {\n selectorsToWatch.add(step?.selector)\n }\n })\n })\n this._instance?.autocapture.setElementSelectors(selectorsToWatch)\n }\n }\n\n on(eventName: string, eventPayload?: CaptureResult) {\n if (eventPayload == null || eventName.length == 0) {\n return\n }\n\n if (!this._actionEvents.has(eventName) && !this._actionEvents.has(eventPayload?.event)) {\n return\n }\n\n if (this._actionRegistry && this._actionRegistry?.size > 0) {\n this._actionRegistry.forEach((action) => {\n if (this._checkAction(eventPayload, action)) {\n this._debugEventEmitter.emit('actionCaptured', action.name)\n }\n })\n }\n }\n\n _addActionHook(callback: (actionName: string, eventPayload?: any) => void): void {\n this.onAction('actionCaptured', (data) => callback(data))\n }\n\n private _checkAction(event?: CaptureResult, action?: SurveyActionType): boolean {\n if (action?.steps == null) {\n return false\n }\n\n for (const step of action.steps) {\n if (this._checkStep(event, step)) {\n return true\n }\n }\n\n return false\n }\n\n onAction(event: 'actionCaptured', cb: (...args: any[]) => void): () => void {\n return this._debugEventEmitter.on(event, cb)\n }\n\n private _checkStep = (event?: CaptureResult, step?: ActionStepType): boolean => {\n return (\n this._checkStepEvent(event, step) &&\n this._checkStepUrl(event, step) &&\n this._checkStepElement(event, step) &&\n this._checkStepProperties(event, step)\n )\n }\n\n private _checkStepEvent = (event?: CaptureResult, step?: ActionStepType): boolean => {\n // CHECK CONDITIONS, OTHERWISE SKIPPED\n if (step?.event && event?.event !== step?.event) {\n return false // EVENT NAME IS A MISMATCH\n }\n return true\n }\n\n private _checkStepUrl(event?: CaptureResult, step?: ActionStepType): boolean {\n // CHECK CONDITIONS, OTHERWISE SKIPPED\n if (step?.url) {\n const eventUrl = event?.properties?.$current_url\n if (!eventUrl || typeof eventUrl !== 'string') {\n return false\n }\n if (!matchString(eventUrl, step.url, step.url_matching || 'contains')) {\n return false\n }\n }\n return true\n }\n\n private _checkStepElement(event?: CaptureResult, step?: ActionStepType): boolean {\n if (!this._checkStepHref(event, step)) return false\n if (!this._checkStepText(event, step)) return false\n if (!this._checkStepSelector(event, step)) return false\n return true\n }\n\n private _checkStepHref(event?: CaptureResult, step?: ActionStepType): boolean {\n if (!step?.href) return true\n\n const elements = this._getElementsList(event)\n if (elements.length > 0) {\n return elements.some((el) => matchString(el.href, step.href!, step.href_matching || 'exact'))\n }\n\n const chain = (event?.properties?.$elements_chain as string) || ''\n if (chain) {\n return matchString(extractHref(chain), step.href, step.href_matching || 'exact')\n }\n\n return false\n }\n\n private _checkStepText(event?: CaptureResult, step?: ActionStepType): boolean {\n if (!step?.text) return true\n\n const elements = this._getElementsList(event)\n if (elements.length > 0) {\n return elements.some(\n (el) =>\n matchString(el.text, step.text!, step.text_matching || 'exact') ||\n matchString(el.$el_text, step.text!, step.text_matching || 'exact')\n )\n }\n\n const chain = (event?.properties?.$elements_chain as string) || ''\n if (chain) {\n return matchTexts(extractTexts(chain), step.text, step.text_matching || 'exact')\n }\n\n return false\n }\n\n private _checkStepSelector(event?: CaptureResult, step?: ActionStepType): boolean {\n if (!step?.selector) return true\n\n // check exact match on $element_selectors from autocapture\n const elementSelectors = event?.properties?.$element_selectors as string[] | undefined\n if (elementSelectors?.includes(step.selector)) {\n return true\n }\n\n // check against compiled regex\n const chain = (event?.properties?.$elements_chain as string) || ''\n if (step.selector_regex && chain) {\n try {\n return new RegExp(step.selector_regex).test(chain)\n } catch {\n return false\n }\n }\n\n return false\n }\n\n private _getElementsList(event?: CaptureResult): SurveyElement[] {\n if (event?.properties?.$elements == null) {\n return []\n }\n\n return event?.properties.$elements as unknown as SurveyElement[]\n }\n\n private _checkStepProperties(event?: CaptureResult, step?: ActionStepType): boolean {\n if (!step?.properties || step.properties.length === 0) {\n return true\n }\n\n // transform to match same property format as normal events\n const propertyFilters: PropertyFilters = step.properties.reduce((acc, filter) => {\n const values = isArray(filter.value)\n ? filter.value.map(String)\n : filter.value != null\n ? [String(filter.value)]\n : []\n\n acc[filter.key] = {\n values,\n operator: (filter.operator || 'exact') as PropertyMatchType,\n }\n return acc\n }, {})\n\n return matchPropertyFilters(propertyFilters, event?.properties)\n }\n}\n", "import { SurveyActionType, SurveyEventType, SurveyEventWithFilters } from '../posthog-surveys-types'\nimport { ActionMatcher } from '../extensions/surveys/action-matcher'\nimport { PostHog } from '../posthog-core'\nimport { CaptureResult } from '../types'\nimport { matchPropertyFilters } from './property-utils'\nimport { isUndefined } from '@posthog/core'\nimport { createLogger } from './logger'\n\n/**\n * Interface for items that can be triggered by events/actions.\n * Both Survey and ProductTour implement this interface.\n */\nexport interface EventTriggerable {\n id: string\n conditions?: {\n events?: { repeatedActivation?: boolean; values: SurveyEventWithFilters[] } | null\n cancelEvents?: { values: SurveyEventWithFilters[] } | null\n actions?: { values: SurveyActionType[] } | null\n } | null\n}\n\n/**\n * Abstract base class for receiving events and matching them to triggerable items.\n * Subclasses implement type-specific behavior for surveys and product tours.\n */\nexport abstract class EventReceiver {\n // eventToItems is a mapping of event name to all the items that are activated by it\n protected _eventToItems: Map\n // cancelEventToItems is a mapping of event name to all the items that should be cancelled by it\n protected _cancelEventToItems: Map\n // actionToItems is a mapping of action name to all the items that are activated by it\n protected readonly _actionToItems: Map\n // actionMatcher can look at CaptureResult payloads and match an event to its corresponding action.\n protected _actionMatcher?: ActionMatcher | null\n protected readonly _instance?: PostHog\n\n constructor(instance: PostHog) {\n this._instance = instance\n this._eventToItems = new Map()\n this._cancelEventToItems = new Map()\n this._actionToItems = new Map()\n }\n\n // Abstract methods for subclasses to implement\n protected abstract _getActivatedKey(): string\n protected abstract _getShownEventName(): string\n protected abstract _getItems(callback: (items: T[]) => void): void\n protected abstract _cancelPendingItem(itemId: string): void\n protected abstract _getLogger(): ReturnType\n /** Check if item is permanently ineligible (e.g. completed/dismissed). Skip adding to activated list. */\n protected abstract _isItemPermanentlyIneligible(itemId?: string): boolean\n\n private _doesEventMatchFilter(\n eventConfig: SurveyEventWithFilters | undefined,\n eventPayload?: CaptureResult\n ): boolean {\n if (!eventConfig) {\n return false\n }\n\n return matchPropertyFilters(eventConfig.propertyFilters, eventPayload?.properties)\n }\n\n private _buildEventToItemMap(items: T[], conditionField: SurveyEventType): Map {\n const map = new Map()\n items.forEach((item) => {\n item.conditions?.[conditionField]?.values?.forEach((event) => {\n if (event?.name) {\n const existing = map.get(event.name) || []\n existing.push(item.id)\n map.set(event.name, existing)\n }\n })\n })\n return map\n }\n\n /**\n * build a map of (Event1) => [Item1, Item2, Item3]\n * used for items that should be [activated|cancelled] by Event1\n */\n private _getMatchingItems(\n eventName: string,\n eventPayload: CaptureResult | undefined,\n conditionField: SurveyEventType\n ): T[] {\n const itemIdMap = conditionField === SurveyEventType.Activation ? this._eventToItems : this._cancelEventToItems\n const itemIds = itemIdMap.get(eventName)\n\n let items: T[] = []\n this._getItems((allItems) => {\n items = allItems.filter((item) => itemIds?.includes(item.id))\n })\n\n return items.filter((item) => {\n const eventConfig = item.conditions?.[conditionField]?.values?.find((e) => e.name === eventName)\n return this._doesEventMatchFilter(eventConfig, eventPayload)\n })\n }\n\n register(items: T[]): void {\n if (isUndefined(this._instance?._addCaptureHook)) {\n return\n }\n\n this._setupEventBasedItems(items)\n this._setupActionBasedItems(items)\n }\n\n private _setupActionBasedItems(items: T[]) {\n const actionBasedItems = items.filter(\n (item: T) => item.conditions?.actions && item.conditions?.actions?.values?.length > 0\n )\n\n if (actionBasedItems.length === 0) {\n return\n }\n\n if (this._actionMatcher == null) {\n this._actionMatcher = new ActionMatcher(this._instance)\n this._actionMatcher.init()\n // match any actions to its corresponding item.\n const matchActionToItem = (actionName: string) => {\n this.onAction(actionName)\n }\n\n this._actionMatcher._addActionHook(matchActionToItem)\n }\n\n actionBasedItems.forEach((item) => {\n if (\n item.conditions &&\n item.conditions?.actions &&\n item.conditions?.actions?.values &&\n item.conditions?.actions?.values?.length > 0\n ) {\n // register the known set of actions with\n // the action-matcher so it can match\n // events to actions\n this._actionMatcher?.register(item.conditions.actions.values)\n\n // maintain a mapping of (Action1) => [Item1, Item2, Item3]\n // where Items 1-3 are all activated by Action1\n item.conditions?.actions?.values?.forEach((action) => {\n if (action && action.name) {\n const knownItems: string[] | undefined = this._actionToItems.get(action.name)\n if (knownItems) {\n knownItems.push(item.id)\n }\n this._actionToItems.set(action.name, knownItems || [item.id])\n }\n })\n }\n })\n }\n\n private _setupEventBasedItems(items: T[]) {\n const eventBasedItems = items.filter(\n (item: T) => item.conditions?.events && item.conditions?.events?.values?.length > 0\n )\n\n const itemsWithCancelEvents = items.filter(\n (item: T) => item.conditions?.cancelEvents && item.conditions?.cancelEvents?.values?.length > 0\n )\n\n if (eventBasedItems.length === 0 && itemsWithCancelEvents.length === 0) {\n return\n }\n\n // match any events to its corresponding item.\n const matchEventToItem = (eventName: string, eventPayload?: CaptureResult) => {\n this.onEvent(eventName, eventPayload)\n }\n this._instance?._addCaptureHook(matchEventToItem)\n\n this._eventToItems = this._buildEventToItemMap(items, SurveyEventType.Activation)\n this._cancelEventToItems = this._buildEventToItemMap(items, SurveyEventType.Cancellation)\n }\n\n onEvent(event: string, eventPayload?: CaptureResult): void {\n const logger = this._getLogger()\n const activatedKey = this._getActivatedKey()\n const shownEventName = this._getShownEventName()\n\n const existingActivatedItems: string[] = this._instance?.persistence?.props[activatedKey] || []\n if (shownEventName === event && eventPayload && existingActivatedItems.length > 0) {\n // remove item from activatedItems here.\n logger.info('event matched, removing item from activated items', {\n event,\n eventPayload,\n existingActivatedItems,\n })\n const itemId = eventPayload?.properties?.$survey_id || eventPayload?.properties?.$product_tour_id\n if (itemId) {\n const index = existingActivatedItems.indexOf(itemId)\n if (index >= 0) {\n existingActivatedItems.splice(index, 1)\n this._updateActivatedItems(existingActivatedItems)\n }\n }\n\n return\n }\n\n // check if this event should cancel any pending items\n if (this._cancelEventToItems.has(event)) {\n const itemsToCancel = this._getMatchingItems(event, eventPayload, SurveyEventType.Cancellation)\n\n if (itemsToCancel.length > 0) {\n logger.info('cancel event matched, cancelling items', {\n event,\n itemsToCancel: itemsToCancel.map((s) => s.id),\n })\n\n itemsToCancel.forEach((item) => {\n // remove from activated items\n const index = existingActivatedItems.indexOf(item.id)\n if (index >= 0) {\n existingActivatedItems.splice(index, 1)\n }\n // cancel any pending timeout for this item\n this._cancelPendingItem(item.id)\n })\n\n this._updateActivatedItems(existingActivatedItems)\n }\n }\n\n // if the event is not in the eventToItems map, nothing else to do\n if (!this._eventToItems.has(event)) {\n return\n }\n\n logger.info('event name matched', {\n event,\n eventPayload,\n items: this._eventToItems.get(event),\n })\n\n const matchedItems = this._getMatchingItems(event, eventPayload, SurveyEventType.Activation)\n\n this._updateActivatedItems(existingActivatedItems.concat(matchedItems.map((item) => item.id) || []))\n }\n\n onAction(actionName: string): void {\n const activatedKey = this._getActivatedKey()\n const existingActivatedItems: string[] = this._instance?.persistence?.props[activatedKey] || []\n if (this._actionToItems.has(actionName)) {\n this._updateActivatedItems(existingActivatedItems.concat(this._actionToItems.get(actionName) || []))\n }\n }\n\n private _updateActivatedItems(activatedItems: string[]) {\n const logger = this._getLogger()\n const activatedKey = this._getActivatedKey()\n // Filter out permanently ineligible items and remove duplicates\n const eligibleItems = [...new Set(activatedItems)].filter(\n (itemId) => !this._isItemPermanentlyIneligible(itemId)\n )\n logger.info('updating activated items', {\n activatedItems: eligibleItems,\n })\n\n this._instance?.persistence?.register({\n [activatedKey]: eligibleItems,\n })\n }\n\n getActivatedIds(): string[] {\n const activatedKey = this._getActivatedKey()\n const existingActivatedItems = this._instance?.persistence?.props[activatedKey]\n return existingActivatedItems ? existingActivatedItems : []\n }\n\n getEventToItemsMap(): Map {\n return this._eventToItems\n }\n\n _getActionMatcher(): ActionMatcher | null | undefined {\n return this._actionMatcher\n }\n}\n", "import { SURVEYS_ACTIVATED } from '../constants'\nimport { Survey, SurveyEventName } from '../posthog-surveys-types'\nimport { PostHog } from '../posthog-core'\nimport { SURVEY_LOGGER as logger } from './survey-utils'\nimport { EventReceiver } from './event-receiver'\nimport { createLogger } from './logger'\n\nexport class SurveyEventReceiver extends EventReceiver {\n constructor(instance: PostHog) {\n super(instance)\n }\n\n protected _getActivatedKey(): string {\n return SURVEYS_ACTIVATED\n }\n\n protected _getShownEventName(): string {\n return SurveyEventName.SHOWN\n }\n\n protected _getItems(callback: (items: Survey[]) => void): void {\n this._instance?.getSurveys(callback)\n }\n\n protected _cancelPendingItem(itemId: string): void {\n this._instance?.cancelPendingSurvey(itemId)\n }\n\n protected _getLogger(): ReturnType {\n return logger\n }\n\n protected _isItemPermanentlyIneligible(): boolean {\n // Surveys have complex eligibility rules checked at display time\n // For now, we don't filter at activation time\n return false\n }\n\n // Backward compatibility - keep getSurveys() as alias for getActivatedIds()\n getSurveys(): string[] {\n return this.getActivatedIds()\n }\n\n // Backward compatibility - keep getEventToSurveys() as alias\n getEventToSurveys(): Map {\n return this.getEventToItemsMap()\n }\n}\n", "import { LOAD_EXT_NOT_FOUND, SURVEYS } from './constants'\n\nconst SURVEY_NOT_LOADED = 'SDK is not enabled or survey functionality is not yet loaded'\nconst SURVEY_DISABLED = 'Disabled. Not loading surveys.'\nimport { SurveyManager } from './extensions/surveys'\nimport type { Extension } from './extensions/types'\nimport { PostHog } from './posthog-core'\nimport {\n DisplaySurveyOptions,\n DisplaySurveyType,\n Survey,\n SurveyCallback,\n SurveyRenderReason,\n} from './posthog-surveys-types'\nimport { Properties, RemoteConfig } from './types'\nimport { assignableWindow, document } from './utils/globals'\nimport { SurveyEventReceiver } from './utils/survey-event-receiver'\nimport {\n doesSurveyActivateByAction,\n doesSurveyActivateByEvent,\n IN_APP_SURVEY_TYPES,\n isSurveyRunning,\n SURVEY_LOGGER as logger,\n SURVEY_IN_PROGRESS_PREFIX,\n SURVEY_SEEN_PREFIX,\n} from './utils/survey-utils'\nimport { isNullish, isUndefined, isArray } from '@posthog/core'\n\nexport class PostHogSurveys implements Extension {\n // this is set to undefined until the remote config is loaded\n // then it's set to true if there are surveys to load\n // or false if there are no surveys to load\n // or false if the surveys feature is disabled in the project settings\n private _isSurveysEnabled?: boolean = undefined\n public _surveyEventReceiver: SurveyEventReceiver | null\n private _surveyManager: SurveyManager | null = null\n private _isInitializingSurveys: boolean = false\n private _surveyCallbacks: SurveyCallback[] = []\n // Promise for in-flight survey fetch - allows multiple callers to await the same request\n private _getSurveysInFlightPromise: Promise<{\n surveys: Survey[]\n context: { isLoaded: boolean; error?: string }\n }> | null = null\n\n private get _config() {\n return this._instance.config\n }\n\n constructor(private readonly _instance: PostHog) {\n // we set this to undefined here because we need the persistence storage for this type\n // but that's not initialized until loadIfEnabled is called.\n this._surveyEventReceiver = null\n }\n\n initialize() {\n this.loadIfEnabled()\n }\n\n onRemoteConfig(response: RemoteConfig) {\n // only load surveys if they are enabled and there are surveys to load\n if (this._config.disable_surveys) {\n return\n }\n\n const surveys = response['surveys']\n if (isNullish(surveys)) {\n return logger.warn('Flags not loaded yet. Not loading surveys.')\n }\n const isArrayResponse = isArray(surveys)\n this._isSurveysEnabled = isArrayResponse ? surveys.length > 0 : surveys\n logger.info(`flags response received, isSurveysEnabled: ${this._isSurveysEnabled}`)\n this.loadIfEnabled()\n }\n\n reset(): void {\n localStorage.removeItem('lastSeenSurveyDate')\n const surveyKeys = []\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i)\n if (key?.startsWith(SURVEY_SEEN_PREFIX) || key?.startsWith(SURVEY_IN_PROGRESS_PREFIX)) {\n surveyKeys.push(key)\n }\n }\n\n surveyKeys.forEach((key) => localStorage.removeItem(key))\n }\n\n loadIfEnabled() {\n // Initial guard clauses\n if (this._surveyManager) {\n return\n } // Already loaded\n if (this._isInitializingSurveys) {\n logger.info('Already initializing surveys, skipping...')\n return\n }\n if (this._config.disable_surveys) {\n logger.info(SURVEY_DISABLED)\n return\n }\n if (this._config.cookieless_mode && this._instance.consent.isOptedOut()) {\n logger.info('Not loading surveys in cookieless mode without consent.')\n return\n }\n\n const phExtensions = assignableWindow?.__PosthogExtensions__\n if (!phExtensions) {\n logger.error('PostHog Extensions not found.')\n return\n }\n\n // waiting for remote config to load\n // if surveys is forced enable (like external surveys), ignore the remote config and load surveys\n if (isUndefined(this._isSurveysEnabled) && !this._config.advanced_enable_surveys) {\n return\n }\n\n const isSurveysEnabled = this._isSurveysEnabled || this._config.advanced_enable_surveys\n\n this._isInitializingSurveys = true\n\n try {\n const generateSurveys = phExtensions.generateSurveys\n if (generateSurveys) {\n // Surveys code is already loaded\n this._completeSurveyInitialization(generateSurveys, isSurveysEnabled)\n return\n }\n\n // If we reach here, surveys code is not loaded yet\n const loadExternalDependency = phExtensions.loadExternalDependency\n if (!loadExternalDependency) {\n // Cannot load surveys code\n this._handleSurveyLoadError(LOAD_EXT_NOT_FOUND)\n return\n }\n\n // If we reach here, we need to load the dependency\n loadExternalDependency(this._instance, 'surveys', (err) => {\n if (err || !phExtensions.generateSurveys) {\n this._handleSurveyLoadError('Could not load surveys script', err)\n } else {\n // Need to get the function reference again inside the callback\n this._completeSurveyInitialization(phExtensions.generateSurveys, isSurveysEnabled)\n }\n })\n } catch (e) {\n this._handleSurveyLoadError('Error initializing surveys', e)\n throw e\n } finally {\n // Ensure the flag is always reset\n this._isInitializingSurveys = false\n }\n }\n\n /** Helper to finalize survey initialization */\n private _completeSurveyInitialization(\n generateSurveysFn: (instance: PostHog, isSurveysEnabled: boolean) => any,\n isSurveysEnabled: boolean\n ): void {\n this._surveyManager = generateSurveysFn(this._instance, isSurveysEnabled)\n this._surveyEventReceiver = new SurveyEventReceiver(this._instance)\n logger.info('Surveys loaded successfully')\n this._notifySurveyCallbacks({ isLoaded: true })\n }\n\n /** Helper to handle errors during survey loading */\n private _handleSurveyLoadError(message: string, error?: any): void {\n logger.error(message, error)\n this._notifySurveyCallbacks({ isLoaded: false, error: message })\n }\n\n /**\n * Register a callback that runs when surveys are initialized.\n * ### Usage:\n *\n * posthog.onSurveysLoaded((surveys) => {\n * // You can work with all surveys\n * console.log('All available surveys:', surveys)\n *\n * // Or get active matching surveys\n * posthog.getActiveMatchingSurveys((activeMatchingSurveys) => {\n * if (activeMatchingSurveys.length > 0) {\n * posthog.renderSurvey(activeMatchingSurveys[0].id, '#survey-container')\n * }\n * })\n * })\n *\n * @param {Function} callback The callback function will be called when surveys are loaded or updated.\n * It receives the array of all surveys and a context object with error status.\n * @returns {Function} A function that can be called to unsubscribe the listener.\n */\n onSurveysLoaded(callback: SurveyCallback): () => void {\n this._surveyCallbacks.push(callback)\n\n if (this._surveyManager) {\n this._notifySurveyCallbacks({\n isLoaded: true,\n })\n }\n // Return unsubscribe function\n return () => {\n this._surveyCallbacks = this._surveyCallbacks.filter((cb: SurveyCallback) => cb !== callback)\n }\n }\n\n getSurveys(callback: SurveyCallback, forceReload = false) {\n // In case we manage to load the surveys script, but config says not to load surveys\n // then we shouldn't return survey data\n if (this._config.disable_surveys) {\n logger.info(SURVEY_DISABLED)\n return callback([])\n }\n\n const existingSurveys = this._instance.get_property(SURVEYS)\n if (existingSurveys && !forceReload) {\n return callback(existingSurveys, {\n isLoaded: true,\n })\n }\n\n // If a fetch is already in progress and Promise is available, reuse that promise\n // In browsers without Promise (IE11), we skip this optimization and just make concurrent requests\n if (typeof Promise !== 'undefined' && this._getSurveysInFlightPromise) {\n this._getSurveysInFlightPromise.then(({ surveys, context }) => callback(surveys, context))\n return\n }\n\n // Create a new promise for this fetch that other callers can reuse\n // We need to assign the promise before starting the request, because\n // in tests (and potentially in some edge cases) the callback may fire synchronously\n let resolvePromise: (value: { surveys: Survey[]; context: { isLoaded: boolean; error?: string } }) => void\n if (typeof Promise !== 'undefined') {\n this._getSurveysInFlightPromise = new Promise((resolve) => {\n resolvePromise = resolve\n })\n }\n\n this._instance._send_request({\n url: this._instance.requestRouter.endpointFor('api', `/api/surveys/?token=${this._config.token}`),\n method: 'GET',\n timeout: this._config.surveys_request_timeout_ms,\n callback: (response) => {\n this._getSurveysInFlightPromise = null\n\n const statusCode = response.statusCode\n if (statusCode !== 200 || !response.json) {\n const error = `Surveys API could not be loaded, status: ${statusCode}`\n logger.error(error)\n const context = { isLoaded: false, error }\n callback([], context)\n resolvePromise?.({ surveys: [], context })\n return\n }\n const surveys = response.json.surveys || []\n\n const eventOrActionBasedSurveys = surveys.filter(\n (survey: Survey) =>\n isSurveyRunning(survey) &&\n (doesSurveyActivateByEvent(survey) || doesSurveyActivateByAction(survey))\n )\n\n if (eventOrActionBasedSurveys.length > 0) {\n this._surveyEventReceiver?.register(eventOrActionBasedSurveys)\n }\n\n this._instance.persistence?.register({ [SURVEYS]: surveys })\n const context = { isLoaded: true }\n callback(surveys, context)\n resolvePromise?.({ surveys, context })\n },\n })\n }\n\n /** Helper method to notify all registered callbacks */\n private _notifySurveyCallbacks(context: { isLoaded: boolean; error?: string }): void {\n for (const callback of this._surveyCallbacks) {\n try {\n if (!context.isLoaded) {\n return callback([], context)\n }\n this.getSurveys(callback)\n } catch (error) {\n logger.error('Error in survey callback', error)\n }\n }\n }\n\n getActiveMatchingSurveys(callback: SurveyCallback, forceReload = false) {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n return this._surveyManager.getActiveMatchingSurveys(callback, forceReload)\n }\n\n private _getSurveyById(surveyId: string): Survey | null {\n let survey: Survey | null = null\n this.getSurveys((surveys) => {\n survey = surveys.find((x) => x.id === surveyId) ?? null\n })\n return survey\n }\n\n private _checkSurveyEligibility(surveyId: string | Survey): { eligible: boolean; reason?: string } {\n if (isNullish(this._surveyManager)) {\n return { eligible: false, reason: SURVEY_NOT_LOADED }\n }\n const survey = typeof surveyId === 'string' ? this._getSurveyById(surveyId) : surveyId\n if (!survey) {\n return { eligible: false, reason: 'Survey not found' }\n }\n return this._surveyManager.checkSurveyEligibility(survey)\n }\n\n canRenderSurvey(surveyId: string | Survey): SurveyRenderReason {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return { visible: false, disabledReason: SURVEY_NOT_LOADED }\n }\n const eligibility = this._checkSurveyEligibility(surveyId)\n\n return { visible: eligibility.eligible, disabledReason: eligibility.reason }\n }\n\n canRenderSurveyAsync(surveyId: string, forceReload: boolean): Promise {\n // Ensure surveys are loaded before checking\n // Using Promise to wrap the callback-based getSurveys method\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return Promise.resolve({\n visible: false,\n disabledReason: SURVEY_NOT_LOADED,\n })\n }\n\n // eslint-disable-next-line compat/compat\n return new Promise((resolve) => {\n this.getSurveys((surveys) => {\n const survey = surveys.find((x) => x.id === surveyId) ?? null\n if (!survey) {\n resolve({ visible: false, disabledReason: 'Survey not found' })\n } else {\n const eligibility = this._checkSurveyEligibility(survey)\n resolve({ visible: eligibility.eligible, disabledReason: eligibility.reason })\n }\n }, forceReload)\n })\n }\n\n renderSurvey(surveyId: string | Survey, selector: string, properties?: Properties) {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n const survey = typeof surveyId === 'string' ? this._getSurveyById(surveyId) : surveyId\n if (!survey?.id) {\n logger.warn('Survey not found')\n return\n }\n if (!IN_APP_SURVEY_TYPES.includes(survey.type)) {\n logger.warn(`Surveys of type ${survey.type} cannot be rendered in the app`)\n return\n }\n const elem = document?.querySelector(selector)\n if (!elem) {\n logger.warn('Survey element not found')\n return\n }\n if (survey.appearance?.surveyPopupDelaySeconds) {\n logger.info(\n `Rendering survey ${survey.id} with delay of ${survey.appearance.surveyPopupDelaySeconds} seconds`\n )\n setTimeout(() => {\n logger.info(\n `Rendering survey ${survey.id} with delay of ${survey.appearance?.surveyPopupDelaySeconds} seconds`\n )\n this._surveyManager?.renderSurvey(survey, elem, properties)\n logger.info(`Survey ${survey.id} rendered`)\n }, survey.appearance.surveyPopupDelaySeconds * 1000)\n return\n }\n this._surveyManager.renderSurvey(survey, elem, properties)\n }\n\n displaySurvey(surveyId: string, options: DisplaySurveyOptions) {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n const survey = this._getSurveyById(surveyId)\n if (!survey) {\n logger.warn('Survey not found')\n return\n }\n let surveyToDisplay = survey\n if (survey.appearance?.surveyPopupDelaySeconds && options.ignoreDelay) {\n surveyToDisplay = {\n ...survey,\n appearance: {\n ...survey.appearance,\n surveyPopupDelaySeconds: 0,\n },\n }\n }\n if (options.displayType !== DisplaySurveyType.Popover && options.initialResponses) {\n logger.warn('initialResponses is only supported for popover surveys. prefill will not be applied.')\n }\n if (options.ignoreConditions === false) {\n const canRender = this.canRenderSurvey(survey)\n if (!canRender.visible) {\n logger.warn('Survey is not eligible to be displayed: ', canRender.disabledReason)\n return\n }\n }\n if (options.displayType === DisplaySurveyType.Inline) {\n this.renderSurvey(surveyToDisplay, options.selector, options.properties)\n return\n }\n this._surveyManager.handlePopoverSurvey(surveyToDisplay, options)\n }\n\n cancelPendingSurvey(surveyId: string): void {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n this._surveyManager.cancelSurvey(surveyId)\n }\n\n handlePageUnload(): void {\n this._surveyManager?.handlePageUnload()\n }\n}\n", "import { addEventListener, trySafe, isToolbarInstance } from '../utils'\nimport { PostHog } from '../posthog-core'\nimport { ToolbarParams } from '../types'\nimport { _getHashParam } from '../utils/request-utils'\nimport { createLogger } from '../utils/logger'\nimport { window, document, assignableWindow } from '../utils/globals'\nimport { TOOLBAR_ID } from '../constants'\nimport { isFunction, isNullish } from '@posthog/core'\nimport { Extension } from './types'\n\n// TRICKY: Many web frameworks will modify the route on load, potentially before posthog is initialized.\n// To get ahead of this we grab it as soon as the posthog-js is parsed\nconst STATE_FROM_WINDOW = window?.location\n ? _getHashParam(window.location.hash, '__posthog') || _getHashParam(location.hash, 'state')\n : null\n\nconst LOCALSTORAGE_KEY = '_postHogToolbarParams'\n\nconst logger = createLogger('[Toolbar]')\n\nconst ToolbarState = { UNINITIALIZED: 0, LOADING: 1, LOADED: 2 } as const\ntype ToolbarState = (typeof ToolbarState)[keyof typeof ToolbarState]\n\nexport class Toolbar implements Extension {\n instance: PostHog\n\n constructor(instance: PostHog) {\n this.instance = instance\n }\n\n // NOTE: We store the state of the toolbar in the global scope to avoid multiple instances of the SDK loading the toolbar\n private _setToolbarState(state: ToolbarState) {\n assignableWindow['ph_toolbar_state'] = state\n }\n\n private _getToolbarState(): ToolbarState {\n return assignableWindow['ph_toolbar_state'] ?? ToolbarState.UNINITIALIZED\n }\n\n initialize(): boolean {\n return this.maybeLoadToolbar()\n }\n\n /**\n * To load the toolbar, we need an access token and other state. That state comes from one of three places:\n * 1. In the URL hash params\n * 2. From session storage under the key `toolbarParams` if the toolbar was initialized on a previous page\n */\n maybeLoadToolbar(\n location: Location | undefined = undefined,\n localStorage: Storage | undefined = undefined,\n history: History | undefined = undefined\n ): boolean {\n // don't load the toolbar on the toolbar :)\n if (isToolbarInstance(this.instance.config)) {\n return false\n }\n if (!window || !document) {\n return false\n }\n location = location ?? window.location\n history = history ?? window.history\n\n try {\n // Before running the code we check if we can access localStorage, if not we opt-out\n if (!localStorage) {\n try {\n window.localStorage.setItem('test', 'test')\n window.localStorage.removeItem('test')\n } catch {\n return false\n }\n\n // If localStorage was undefined, and localStorage is supported we set the default value\n localStorage = window?.localStorage\n }\n\n /**\n * Info about the state\n * The state is a json object\n * 1. (Legacy) The state can be `state={}` as a urlencoded object of info. In this case\n * 2. The state should now be found in `__posthog={}` and can be base64 encoded or urlencoded.\n * 3. Base64 encoding is preferred and will gradually be rolled out everywhere\n */\n\n const stateHash =\n STATE_FROM_WINDOW || _getHashParam(location.hash, '__posthog') || _getHashParam(location.hash, 'state')\n\n let toolbarParams: ToolbarParams\n const state = stateHash\n ? trySafe(() => JSON.parse(atob(decodeURIComponent(stateHash)))) ||\n trySafe(() => JSON.parse(decodeURIComponent(stateHash)))\n : null\n\n const parseFromUrl = state && state['action'] === 'ph_authorize'\n\n if (parseFromUrl) {\n // happens if they are initializing the toolbar using an old snippet\n toolbarParams = state\n toolbarParams.source = 'url'\n\n if (toolbarParams && Object.keys(toolbarParams).length > 0) {\n if (state['desiredHash']) {\n // hash that was in the url before the redirect\n location.hash = state['desiredHash']\n } else if (history) {\n // second param is unused see https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState\n history.replaceState(history.state, '', location.pathname + location.search) // completely remove hash\n } else {\n location.hash = '' // clear hash (but leaves # unfortunately)\n }\n }\n } else {\n // get credentials from localStorage from a previous initialization\n\n toolbarParams = JSON.parse(localStorage.getItem(LOCALSTORAGE_KEY) || '{}')\n toolbarParams.source = 'localstorage'\n\n // delete \"add-action\" or other intent from toolbarParams, otherwise we'll have the same intent\n // every time we open the page (e.g. you just visiting your own site an hour later)\n delete toolbarParams.userIntent\n }\n\n if (toolbarParams['token'] && this.instance.config.token === toolbarParams['token']) {\n this.loadToolbar(toolbarParams)\n return true\n } else {\n return false\n }\n } catch {\n return false\n }\n }\n\n private _callLoadToolbar(params: ToolbarParams) {\n const loadFn = assignableWindow['ph_load_toolbar'] || assignableWindow['ph_load_editor']\n if (isNullish(loadFn) || !isFunction(loadFn)) {\n logger.warn('No toolbar load function found')\n return\n }\n loadFn(params, this.instance)\n }\n\n loadToolbar(params?: ToolbarParams): boolean {\n const toolbarRunning = !!document?.getElementById(TOOLBAR_ID)\n\n if (!window || toolbarRunning) {\n // The toolbar will clear the localStorage key when it's done with it. If it is present that indicates the toolbar is already open and running\n return false\n }\n\n const disableToolbarMetrics =\n this.instance.requestRouter.region === 'custom' && this.instance.config.advanced_disable_toolbar_metrics\n\n const toolbarParams = {\n token: this.instance.config.token,\n ...params,\n apiURL: this.instance.requestRouter.endpointFor('ui'),\n ...(disableToolbarMetrics ? { instrument: false } : {}),\n }\n window.localStorage.setItem(\n LOCALSTORAGE_KEY,\n JSON.stringify({\n ...toolbarParams,\n source: undefined,\n })\n )\n\n if (this._getToolbarState() === ToolbarState.LOADED) {\n this._callLoadToolbar(toolbarParams)\n } else if (this._getToolbarState() === ToolbarState.UNINITIALIZED) {\n // only load the toolbar once, even if there are multiple instances of PostHogLib\n this._setToolbarState(ToolbarState.LOADING)\n\n assignableWindow.__PosthogExtensions__?.loadExternalDependency?.(this.instance, 'toolbar', (err) => {\n if (err) {\n logger.error('[Toolbar] Failed to load', err)\n this._setToolbarState(ToolbarState.UNINITIALIZED)\n return\n }\n this._setToolbarState(ToolbarState.LOADED)\n this._callLoadToolbar(toolbarParams)\n })\n\n // Turbolinks doesn't fire an onload event but does replace the entire body, including the toolbar.\n // Thus, we ensure the toolbar is only loaded inside the body, and then reloaded on turbolinks:load.\n addEventListener(window, 'turbolinks:load', () => {\n this._setToolbarState(ToolbarState.UNINITIALIZED)\n this.loadToolbar(toolbarParams)\n })\n }\n\n return true\n }\n\n /** @deprecated Use \"loadToolbar\" instead. */\n _loadEditor(params: ToolbarParams): boolean {\n return this.loadToolbar(params)\n }\n\n /** @deprecated Use \"maybeLoadToolbar\" instead. */\n maybeLoadEditor(\n location: Location | undefined = undefined,\n localStorage: Storage | undefined = undefined,\n history: History | undefined = undefined\n ): boolean {\n return this.maybeLoadToolbar(location, localStorage, history)\n }\n}\n", "import { entries, extend } from './utils'\nimport { PostHog } from './posthog-core'\nimport {\n FlagsResponse,\n FeatureFlagsCallback,\n EarlyAccessFeatureCallback,\n EarlyAccessFeatureResponse,\n Properties,\n JsonType,\n Compression,\n EarlyAccessFeature,\n RemoteConfigFeatureFlagCallback,\n EarlyAccessFeatureStage,\n FeatureFlagDetail,\n FeatureFlagResult,\n FeatureFlagOptions,\n OverrideFeatureFlagsOptions,\n} from './types'\nimport { PostHogPersistence } from './posthog-persistence'\nimport type { Extension } from './extensions/types'\n\nimport {\n PERSISTENCE_EARLY_ACCESS_FEATURES,\n DEVICE_ID,\n PERSISTENCE_FEATURE_FLAG_DETAILS,\n PERSISTENCE_FEATURE_FLAG_ERRORS,\n PERSISTENCE_FEATURE_FLAG_EVALUATED_AT,\n ENABLED_FEATURE_FLAGS,\n STORED_GROUP_PROPERTIES_KEY,\n STORED_PERSON_PROPERTIES_KEY,\n FLAG_CALL_REPORTED,\n FLAG_CALL_REPORTED_SESSION_ID,\n PERSISTENCE_FEATURE_FLAG_PAYLOADS,\n PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS,\n} from './constants'\n\nimport { isUndefined, isArray, isNull } from '@posthog/core'\nimport { createLogger } from './utils/logger'\nimport { getTimezone } from './utils/event-utils'\n\nconst logger = createLogger('[FeatureFlags]')\nconst forceDebugLogger = createLogger('[FeatureFlags]', { debugEnabled: true })\nconst FLAG_TIMEOUT_MSG = '\" failed. Feature flags didn\\'t load in time.'\n\n/**\n * Error type constants for the $feature_flag_error property.\n *\n * These values are sent in analytics events to track flag evaluation failures.\n * They should not be changed without considering impact on existing dashboards\n * and queries that filter on these values.\n */\nexport const FeatureFlagError = {\n ERRORS_WHILE_COMPUTING: 'errors_while_computing_flags',\n FLAG_MISSING: 'flag_missing',\n QUOTA_LIMITED: 'quota_limited',\n TIMEOUT: 'timeout',\n CONNECTION_ERROR: 'connection_error',\n UNKNOWN_ERROR: 'unknown_error',\n apiError: (status: number | string) => `api_error_${status}`,\n} as const\n\nconst PERSISTENCE_ACTIVE_FEATURE_FLAGS = '$active_feature_flags'\nconst PERSISTENCE_OVERRIDE_FEATURE_FLAGS = '$override_feature_flags'\nconst PERSISTENCE_FEATURE_FLAG_REQUEST_ID = '$feature_flag_request_id'\n\n/** Converts an array of flag names to a Record where each flag is set to true. */\nconst arrayToFlagsRecord = (flags: string[]): Record => {\n const flagsObj: Record = {}\n for (let i = 0; i < flags.length; i++) {\n flagsObj[flags[i]] = true\n }\n return flagsObj\n}\n\nexport const filterActiveFeatureFlags = (featureFlags?: Record) => {\n const activeFeatureFlags: Record = {}\n for (const [key, value] of entries(featureFlags || {})) {\n if (value) {\n activeFeatureFlags[key] = value\n }\n }\n return activeFeatureFlags\n}\n\nexport const parseFlagsResponse = (\n response: Partial,\n persistence: PostHogPersistence,\n currentFlags: Record = {},\n currentFlagPayloads: Record = {},\n currentFlagDetails: Record = {},\n options?: { partialResponse?: boolean }\n) => {\n const normalizedResponse = normalizeFlagsResponse(response)\n const flagDetails = normalizedResponse.flags\n const featureFlags = normalizedResponse.featureFlags\n const flagPayloads = normalizedResponse.featureFlagPayloads\n\n if (!featureFlags) {\n return // <-- This early return means we don't update anything, which is good.\n }\n\n const requestId = response['requestId']\n const evaluatedAt = response['evaluatedAt']\n\n // using the v1 api\n if (isArray(featureFlags)) {\n logger.warn('v1 of the feature flags endpoint is deprecated. Please use the latest version.')\n const $enabled_feature_flags: Record = {}\n if (featureFlags) {\n for (let i = 0; i < featureFlags.length; i++) {\n $enabled_feature_flags[featureFlags[i]] = true\n }\n }\n persistence &&\n persistence.register({\n [PERSISTENCE_ACTIVE_FEATURE_FLAGS]: featureFlags,\n [ENABLED_FEATURE_FLAGS]: $enabled_feature_flags,\n })\n return\n }\n\n // using the v2+ api\n let newFeatureFlags = featureFlags\n let newFeatureFlagPayloads = flagPayloads\n let newFeatureFlagDetails = flagDetails\n if (options?.partialResponse) {\n // The response is intentionally partial (e.g., only survey flags were requested via\n // advanced_only_evaluate_survey_feature_flags). Merge with existing flags so that\n // bootstrapped or previously loaded non-survey flags are preserved.\n newFeatureFlags = { ...currentFlags, ...newFeatureFlags }\n newFeatureFlagPayloads = { ...currentFlagPayloads, ...newFeatureFlagPayloads }\n newFeatureFlagDetails = { ...currentFlagDetails, ...newFeatureFlagDetails }\n } else if (response.errorsWhileComputingFlags) {\n // if not all flags were computed, we upsert flags instead of replacing them\n // but filter out flags that failed to evaluate so they don't overwrite cached values\n if (flagDetails) {\n const successfulKeys = new Set(Object.keys(flagDetails).filter((key) => !flagDetails[key]?.failed))\n\n newFeatureFlags = {\n ...currentFlags,\n ...Object.fromEntries(Object.entries(newFeatureFlags).filter(([key]) => successfulKeys.has(key))),\n }\n newFeatureFlagPayloads = {\n ...currentFlagPayloads,\n ...Object.fromEntries(\n Object.entries(newFeatureFlagPayloads || {}).filter(([key]) => successfulKeys.has(key))\n ),\n }\n newFeatureFlagDetails = {\n ...currentFlagDetails,\n ...Object.fromEntries(\n Object.entries(newFeatureFlagDetails || {}).filter(([key]) => successfulKeys.has(key))\n ),\n }\n } else {\n // v1 responses don't have flagDetails, so we can't filter by failed field\n // Fall back to the original merge behavior\n newFeatureFlags = { ...currentFlags, ...newFeatureFlags }\n newFeatureFlagPayloads = { ...currentFlagPayloads, ...newFeatureFlagPayloads }\n newFeatureFlagDetails = { ...currentFlagDetails, ...newFeatureFlagDetails }\n }\n }\n\n persistence &&\n persistence.register({\n [PERSISTENCE_ACTIVE_FEATURE_FLAGS]: Object.keys(filterActiveFeatureFlags(newFeatureFlags)),\n [ENABLED_FEATURE_FLAGS]: newFeatureFlags || {},\n [PERSISTENCE_FEATURE_FLAG_PAYLOADS]: newFeatureFlagPayloads || {},\n [PERSISTENCE_FEATURE_FLAG_DETAILS]: newFeatureFlagDetails || {},\n ...(requestId ? { [PERSISTENCE_FEATURE_FLAG_REQUEST_ID]: requestId } : {}),\n ...(evaluatedAt ? { [PERSISTENCE_FEATURE_FLAG_EVALUATED_AT]: evaluatedAt } : {}),\n })\n}\n\nconst normalizeFlagsResponse = (response: Partial): Partial => {\n const flagDetails = response['flags']\n\n if (flagDetails) {\n // This is a /flags?v=2 request.\n\n // Map of flag keys to flag values: Record\n response.featureFlags = Object.fromEntries(\n Object.keys(flagDetails).map((flag) => [flag, flagDetails[flag].variant ?? flagDetails[flag].enabled])\n )\n // Map of flag keys to flag payloads: Record\n response.featureFlagPayloads = Object.fromEntries(\n Object.keys(flagDetails)\n .filter((flag) => flagDetails[flag].enabled)\n .filter((flag) => flagDetails[flag].metadata?.payload)\n .map((flag) => [flag, flagDetails[flag].metadata?.payload])\n )\n } else {\n logger.warn(\n 'Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version'\n )\n }\n return response\n}\n\nexport const QuotaLimitedResource = {\n FeatureFlags: 'feature_flags',\n Recordings: 'recordings',\n} as const\nexport type QuotaLimitedResource = (typeof QuotaLimitedResource)[keyof typeof QuotaLimitedResource]\n\nexport class PostHogFeatureFlags implements Extension {\n _override_warning: boolean = false\n featureFlagEventHandlers: FeatureFlagsCallback[]\n $anon_distinct_id: string | undefined\n private _hasLoadedFlags: boolean = false\n private _requestInFlight: boolean = false\n private _reloadingDisabled: boolean = false\n private _additionalReloadRequested: boolean = false\n private _reloadDebouncer?: any\n private _flagsLoadedFromRemote: boolean = false\n private _hasLoggedDeprecationWarning: boolean = false\n private _staleCacheRefreshTriggered: boolean = false\n\n constructor(private _instance: PostHog) {\n this.featureFlagEventHandlers = []\n }\n\n private get _config() {\n return this._instance.config\n }\n\n private get _persistence() {\n return this._instance.persistence\n }\n\n private _prop(key: string): any {\n return this._instance.get_property(key)\n }\n\n /**\n * Check if the feature flag cache is stale based on the configured TTL.\n */\n private _isCacheStale(): boolean {\n return this._persistence?._isFeatureFlagCacheStale(this._config.feature_flag_cache_ttl_ms) ?? false\n }\n\n /**\n * Triggers a debounced reload when cache staleness is first detected.\n * Returns true if cache is stale, false otherwise.\n */\n private _checkAndTriggerStaleRefresh(): boolean {\n if (!this._isCacheStale()) {\n return false\n }\n // Only trigger refresh once per stale period\n if (!this._staleCacheRefreshTriggered && !this._requestInFlight) {\n this._staleCacheRefreshTriggered = true\n logger.warn('Feature flag cache is stale, triggering refresh...')\n this.reloadFeatureFlags()\n }\n return true\n }\n\n private _getValidEvaluationEnvironments(): string[] {\n // Support both evaluation_contexts (new) and evaluation_environments (deprecated)\n const envs = this._config.evaluation_contexts ?? this._config.evaluation_environments\n\n // Log deprecation warning if using old field (only once)\n if (\n this._config.evaluation_environments &&\n !this._config.evaluation_contexts &&\n !this._hasLoggedDeprecationWarning\n ) {\n logger.warn(\n 'evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version.'\n )\n this._hasLoggedDeprecationWarning = true\n }\n\n if (!envs?.length) {\n return []\n }\n\n return envs.filter((env: string) => {\n const isValid = env && typeof env === 'string' && env.trim().length > 0\n if (!isValid) {\n logger.error('Invalid evaluation context found:', env, 'Expected non-empty string')\n }\n return isValid\n })\n }\n\n private _shouldIncludeEvaluationEnvironments(): boolean {\n return this._getValidEvaluationEnvironments().length > 0\n }\n\n initialize() {\n const { config } = this._instance\n const bootstrapFlags = config.bootstrap?.featureFlags ?? {}\n const hasBootstrappedFlags = Object.keys(bootstrapFlags).length\n if (hasBootstrappedFlags) {\n const bootstrapPayloads = config.bootstrap?.featureFlagPayloads ?? {}\n const activeFlags = Object.keys(bootstrapFlags)\n .filter((flag) => !!bootstrapFlags[flag])\n .reduce((res: Record, key) => {\n res[key] = bootstrapFlags[key] || false\n return res\n }, {})\n const featureFlagPayloads = Object.keys(bootstrapPayloads)\n .filter((key) => activeFlags[key])\n .reduce((res: Record, key) => {\n if (bootstrapPayloads[key]) {\n res[key] = bootstrapPayloads[key]\n }\n return res\n }, {})\n\n this.receivedFeatureFlags({ featureFlags: activeFlags, featureFlagPayloads })\n }\n }\n\n updateFlags(\n flags: Record,\n payloads?: Record,\n options?: { merge?: boolean }\n ): void {\n // If merging, combine with existing flags\n const existingFlags = options?.merge ? this.getFlagVariants() : {}\n const existingPayloads = options?.merge ? this.getFlagPayloads() : {}\n const finalFlags = { ...existingFlags, ...flags }\n const finalPayloads = { ...existingPayloads, ...payloads }\n\n // Convert simple flags to v4 format to avoid deprecation warning\n const flagDetails: Record = {}\n for (const [key, value] of Object.entries(finalFlags)) {\n const isVariant = typeof value === 'string'\n flagDetails[key] = {\n key,\n enabled: isVariant ? true : Boolean(value),\n variant: isVariant ? value : undefined,\n reason: undefined,\n // id: 0 indicates manually injected flags (not from server evaluation)\n metadata: !isUndefined(finalPayloads?.[key])\n ? { id: 0, version: undefined, description: undefined, payload: finalPayloads[key] }\n : undefined,\n }\n }\n\n this.receivedFeatureFlags({\n flags: flagDetails,\n })\n }\n\n get hasLoadedFlags(): boolean {\n return this._hasLoadedFlags\n }\n\n getFlags(): string[] {\n return Object.keys(this.getFlagVariants())\n }\n\n getFlagsWithDetails(): Record {\n const flagDetails = this._prop(PERSISTENCE_FEATURE_FLAG_DETAILS)\n\n const overridenFlags = this._prop(PERSISTENCE_OVERRIDE_FEATURE_FLAGS)\n const overriddenPayloads = this._prop(PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS)\n\n if (!overriddenPayloads && !overridenFlags) {\n return flagDetails || {}\n }\n\n const finalDetails = extend({}, flagDetails || {})\n const overriddenKeys = [\n ...new Set([...Object.keys(overriddenPayloads || {}), ...Object.keys(overridenFlags || {})]),\n ]\n for (const key of overriddenKeys) {\n const originalDetail = finalDetails[key]\n const overrideFlagValue = overridenFlags?.[key]\n\n const finalEnabled = isUndefined(overrideFlagValue)\n ? (originalDetail?.enabled ?? false)\n : !!overrideFlagValue\n\n const overrideVariant = isUndefined(overrideFlagValue)\n ? originalDetail.variant\n : typeof overrideFlagValue === 'string'\n ? overrideFlagValue\n : undefined\n\n const overridePayload = overriddenPayloads?.[key]\n\n const overridenDetail = {\n ...originalDetail,\n enabled: finalEnabled,\n // If the flag is not enabled, the variant should be undefined, even if the original has a variant value.\n variant: finalEnabled ? (overrideVariant ?? originalDetail?.variant) : undefined,\n }\n\n // Keep track of the original enabled and variant values so we can send them in the $feature_flag_called event.\n // This will be helpful for debugging and for understanding the impact of overrides.\n if (finalEnabled !== originalDetail?.enabled) {\n overridenDetail.original_enabled = originalDetail?.enabled\n }\n\n if (overrideVariant !== originalDetail?.variant) {\n overridenDetail.original_variant = originalDetail?.variant\n }\n\n if (overridePayload) {\n overridenDetail.metadata = {\n ...originalDetail?.metadata,\n payload: overridePayload,\n original_payload: originalDetail?.metadata?.payload,\n }\n }\n\n finalDetails[key] = overridenDetail\n }\n\n if (!this._override_warning) {\n logger.warn(' Overriding feature flag details!', {\n flagDetails,\n overriddenPayloads,\n finalDetails,\n })\n this._override_warning = true\n }\n return finalDetails\n }\n\n getFlagVariants(): Record {\n const enabledFlags = this._prop(ENABLED_FEATURE_FLAGS)\n const overriddenFlags = this._prop(PERSISTENCE_OVERRIDE_FEATURE_FLAGS)\n if (!overriddenFlags) {\n return enabledFlags || {}\n }\n\n const finalFlags = extend({}, enabledFlags)\n const overriddenKeys = Object.keys(overriddenFlags)\n for (let i = 0; i < overriddenKeys.length; i++) {\n finalFlags[overriddenKeys[i]] = overriddenFlags[overriddenKeys[i]]\n }\n if (!this._override_warning) {\n logger.warn(' Overriding feature flags!', {\n enabledFlags,\n overriddenFlags,\n finalFlags,\n })\n this._override_warning = true\n }\n return finalFlags\n }\n\n getFlagPayloads(): Record {\n const flagPayloads = this._prop(PERSISTENCE_FEATURE_FLAG_PAYLOADS)\n const overriddenPayloads = this._prop(PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS)\n\n if (!overriddenPayloads) {\n return flagPayloads || {}\n }\n\n const finalPayloads = extend({}, flagPayloads || {})\n const overriddenKeys = Object.keys(overriddenPayloads)\n for (let i = 0; i < overriddenKeys.length; i++) {\n finalPayloads[overriddenKeys[i]] = overriddenPayloads[overriddenKeys[i]]\n }\n\n if (!this._override_warning) {\n logger.warn(' Overriding feature flag payloads!', {\n flagPayloads,\n overriddenPayloads,\n finalPayloads,\n })\n this._override_warning = true\n }\n return finalPayloads\n }\n\n /**\n * Reloads feature flags asynchronously.\n *\n * Constraints:\n *\n * 1. Avoid parallel requests\n * 2. Delay a few milliseconds after each reloadFeatureFlags call to batch subsequent changes together\n */\n reloadFeatureFlags(): void {\n if (this._reloadingDisabled || this._config.advanced_disable_feature_flags) {\n // If reloading has been explicitly disabled then we don't want to do anything\n // Or if feature flags are disabled\n return\n }\n\n if (this._reloadDebouncer) {\n // If we're already in a debounce then we don't want to do anything\n return\n }\n\n // Emit event so consumers know flags are being reloaded\n this._instance._internalEventEmitter.emit('featureFlagsReloading', true)\n\n // Debounce multiple calls on the same tick\n this._reloadDebouncer = setTimeout(() => {\n this._callFlagsEndpoint()\n }, 5)\n }\n\n private _clearDebouncer(): void {\n clearTimeout(this._reloadDebouncer)\n this._reloadDebouncer = undefined\n }\n\n ensureFlagsLoaded(): void {\n if (this._hasLoadedFlags || this._requestInFlight || this._reloadDebouncer) {\n // If we are or have already loaded the flags then we don't want to do anything\n return\n }\n\n this.reloadFeatureFlags()\n }\n\n setAnonymousDistinctId(anon_distinct_id: string): void {\n this.$anon_distinct_id = anon_distinct_id\n }\n\n setReloadingPaused(isPaused: boolean): void {\n this._reloadingDisabled = isPaused\n }\n\n _callFlagsEndpoint(options?: { disableFlags?: boolean }): void {\n // Ensure we don't have double queued /flags requests\n this._clearDebouncer()\n if (this._instance._shouldDisableFlags()) {\n // The way this is documented is essentially used to refuse to ever call the /flags endpoint.\n return\n }\n if (this._requestInFlight) {\n this._additionalReloadRequested = true\n return\n }\n const token = this._config.token\n const deviceId = this._prop(DEVICE_ID)\n\n const data: Record = {\n token: token,\n distinct_id: this._instance.get_distinct_id(),\n groups: this._instance.getGroups(),\n $anon_distinct_id: this.$anon_distinct_id,\n person_properties: {\n ...(this._persistence?.get_initial_props() || {}),\n ...(this._prop(STORED_PERSON_PROPERTIES_KEY) || {}),\n },\n group_properties: this._prop(STORED_GROUP_PROPERTIES_KEY),\n timezone: getTimezone(),\n }\n\n // Add device_id if available (handle cookieless mode where it's null)\n if (!isNull(deviceId) && !isUndefined(deviceId)) {\n data.$device_id = deviceId\n }\n\n if (options?.disableFlags || this._config.advanced_disable_feature_flags) {\n data.disable_flags = true\n }\n\n // Add evaluation contexts if configured\n if (this._shouldIncludeEvaluationEnvironments()) {\n data.evaluation_contexts = this._getValidEvaluationEnvironments()\n }\n\n const queryParams = this._config.advanced_only_evaluate_survey_feature_flags\n ? '&only_evaluate_survey_feature_flags=true'\n : ''\n\n const url = this._instance.requestRouter.endpointFor('flags', '/flags/?v=2' + queryParams)\n\n this._requestInFlight = true\n this._instance._send_request({\n method: 'POST',\n url,\n data,\n compression: this._config.disable_compression ? undefined : Compression.Base64,\n timeout: this._config.feature_flag_request_timeout_ms,\n callback: (response) => {\n let errorsLoading = true\n\n if (response.statusCode === 200) {\n // successful request\n // reset anon_distinct_id after at least a single request with it\n // makes it through\n if (!this._additionalReloadRequested) {\n this.$anon_distinct_id = undefined\n }\n errorsLoading = false\n }\n\n this._requestInFlight = false\n\n if (data.disable_flags && !this._additionalReloadRequested) {\n // If flags are disabled then there is no need to call /flags again (flags are the only thing that may change)\n // UNLESS, an additional reload is requested.\n return\n }\n\n this._flagsLoadedFromRemote = !errorsLoading\n\n const flagErrors: string[] = []\n if (response.error) {\n if (response.error instanceof Error) {\n flagErrors.push(\n response.error.name === 'AbortError'\n ? FeatureFlagError.TIMEOUT\n : FeatureFlagError.CONNECTION_ERROR\n )\n } else {\n flagErrors.push(FeatureFlagError.UNKNOWN_ERROR)\n }\n } else if (response.statusCode !== 200) {\n flagErrors.push(FeatureFlagError.apiError(response.statusCode))\n }\n if (response.json?.errorsWhileComputingFlags) {\n flagErrors.push(FeatureFlagError.ERRORS_WHILE_COMPUTING)\n }\n const isQuotaLimited = !!response.json?.quotaLimited?.includes(QuotaLimitedResource.FeatureFlags)\n if (isQuotaLimited) {\n flagErrors.push(FeatureFlagError.QUOTA_LIMITED)\n }\n\n this._persistence?.register({\n [PERSISTENCE_FEATURE_FLAG_ERRORS]: flagErrors,\n })\n\n if (isQuotaLimited) {\n // log a warning and then early return\n logger.warn(\n 'You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.'\n )\n return\n }\n\n if (!data.disable_flags) {\n this.receivedFeatureFlags(response.json ?? {}, errorsLoading, {\n partialResponse: !!this._config.advanced_only_evaluate_survey_feature_flags,\n })\n }\n\n if (this._additionalReloadRequested) {\n this._additionalReloadRequested = false\n this._callFlagsEndpoint()\n }\n },\n })\n }\n\n /**\n * Get feature flag's value for user.\n *\n * By default, this method may return cached values from localStorage if the `/flags` endpoint\n * hasn't responded yet. This reduces flicker but means you might briefly see stale values\n * (e.g., a flag that was disabled on the server).\n *\n * ### Usage:\n *\n * if(posthog.getFeatureFlag('my-flag') === 'some-variant') { // do something }\n *\n * // Only use fresh values from the server (returns undefined until /flags responds)\n * if(posthog.getFeatureFlag('my-flag', { fresh: true }) === 'some-variant') { // do something }\n *\n * @param {String} key Key of the feature flag.\n * @param {Object} options Optional settings.\n * @param {boolean} [options.send_event=true] If false, won't send a $feature_flag_called event to PostHog.\n * @param {boolean} [options.fresh=false] If true, only returns values loaded from the server, not cached localStorage values.\n * Use this when you need to ensure the flag value reflects the current server state,\n * such as after disabling a flag. Returns undefined until the /flags endpoint responds.\n * @returns {boolean | string | undefined} The flag value, or undefined if not found or not yet loaded.\n */\n getFeatureFlag(key: string, options: FeatureFlagOptions = {}): boolean | string | undefined {\n if (options.fresh && !this._flagsLoadedFromRemote) {\n return undefined\n }\n if (!this._hasLoadedFlags && !(this.getFlags() && this.getFlags().length > 0)) {\n logger.warn('getFeatureFlag for key \"' + key + FLAG_TIMEOUT_MSG)\n return undefined\n }\n // Check if cache is stale and trigger refresh if needed\n if (this._checkAndTriggerStaleRefresh()) {\n return undefined\n }\n const result = this.getFeatureFlagResult(key, options)\n return result?.variant ?? result?.enabled\n }\n\n /*\n * Retrieves the details for a feature flag.\n *\n * ### Usage:\n *\n * const details = getFeatureFlagDetails(\"my-flag\")\n * console.log(details.metadata.version)\n * console.log(details.reason)\n *\n * @param {String} key Key of the feature flag.\n */\n getFeatureFlagDetails(key: string): FeatureFlagDetail | undefined {\n const details = this.getFlagsWithDetails()\n return details[key]\n }\n\n /**\n * @deprecated Use `getFeatureFlagResult()` instead which properly tracks the feature flag call.\n * `getFeatureFlagPayload()` does not emit the `$feature_flag_called` event which may result in\n * missing analytics. This method will be removed in a future version.\n */\n getFeatureFlagPayload(key: string): JsonType {\n // Don't send event to maintain backwards compatibility - this method never tracked calls\n const result = this.getFeatureFlagResult(key, { send_event: false })\n return result?.payload\n }\n\n /**\n * Get a feature flag result including both the flag value and payload, while properly tracking the call.\n * This method emits the `$feature_flag_called` event by default.\n *\n * By default, this method may return cached values from localStorage if the `/flags` endpoint\n * hasn't responded yet. This reduces flicker but means you might briefly see stale values\n * (e.g., a flag that was disabled on the server).\n *\n * ### Usage:\n *\n * const result = posthog.getFeatureFlagResult('my-flag')\n * if (result?.enabled) {\n * console.log('Flag is enabled with payload:', result.payload)\n * }\n *\n * // Only use fresh values from the server\n * const freshResult = posthog.getFeatureFlagResult('my-flag', { fresh: true })\n *\n * @param {String} key Key of the feature flag.\n * @param {Object} [options] Options for the feature flag lookup.\n * @param {boolean} [options.send_event=true] If false, won't send the $feature_flag_called event.\n * @param {boolean} [options.fresh=false] If true, only returns values loaded from the server, not cached localStorage values.\n * Use this when you need to ensure the flag value reflects the current server state.\n * Returns undefined until the /flags endpoint responds.\n * @returns {FeatureFlagResult | undefined} The feature flag result including key, enabled, variant, and payload.\n */\n getFeatureFlagResult(key: string, options: FeatureFlagOptions = {}): FeatureFlagResult | undefined {\n if (options.fresh && !this._flagsLoadedFromRemote) {\n return undefined\n }\n if (!this._hasLoadedFlags && !(this.getFlags() && this.getFlags().length > 0)) {\n logger.warn('getFeatureFlagResult for key \"' + key + FLAG_TIMEOUT_MSG)\n return undefined\n }\n // Check if cache is stale and trigger refresh if needed\n if (this._checkAndTriggerStaleRefresh()) {\n return undefined\n }\n\n const flagVariants = this.getFlagVariants()\n const flagExists = key in flagVariants\n const flagValue = flagVariants[key]\n const payloads = this.getFlagPayloads()\n const payload = payloads[key]\n const flagReportValue = String(flagValue)\n const requestId = this._prop(PERSISTENCE_FEATURE_FLAG_REQUEST_ID) || undefined\n const evaluatedAt = this._prop(PERSISTENCE_FEATURE_FLAG_EVALUATED_AT) || undefined\n let flagCallReported: Record = this._prop(FLAG_CALL_REPORTED) || {}\n\n // When session-scoped dedup is enabled, reset the reported flags whenever the session changes.\n if (this._config.advanced_feature_flags_dedup_per_session) {\n const currentSessionId = this._instance.get_session_id()\n const storedSessionId = this._prop(FLAG_CALL_REPORTED_SESSION_ID)\n if (currentSessionId && currentSessionId !== storedSessionId) {\n flagCallReported = {}\n this._persistence?.register({\n [FLAG_CALL_REPORTED]: flagCallReported,\n [FLAG_CALL_REPORTED_SESSION_ID]: currentSessionId,\n })\n }\n }\n\n if (options.send_event || !('send_event' in options)) {\n if (!(key in flagCallReported) || !flagCallReported[key].includes(flagReportValue)) {\n if (isArray(flagCallReported[key])) {\n flagCallReported[key].push(flagReportValue)\n } else {\n flagCallReported[key] = [flagReportValue]\n }\n this._persistence?.register({ [FLAG_CALL_REPORTED]: flagCallReported })\n\n const flagDetails = this.getFeatureFlagDetails(key)\n const errors: string[] = [...(this._prop(PERSISTENCE_FEATURE_FLAG_ERRORS) ?? [])]\n if (isUndefined(flagValue)) {\n errors.push(FeatureFlagError.FLAG_MISSING)\n }\n\n const properties: Record = {\n $feature_flag: key,\n $feature_flag_response: flagValue,\n $feature_flag_payload: payload || null,\n $feature_flag_request_id: requestId,\n $feature_flag_evaluated_at: evaluatedAt,\n $feature_flag_bootstrapped_response: this._config.bootstrap?.featureFlags?.[key] || null,\n $feature_flag_bootstrapped_payload: this._config.bootstrap?.featureFlagPayloads?.[key] || null,\n // If we haven't yet received a response from the /flags endpoint, we must have used the bootstrapped value\n $used_bootstrap_value: !this._flagsLoadedFromRemote,\n }\n\n if (!isUndefined(flagDetails?.metadata?.version)) {\n properties.$feature_flag_version = flagDetails.metadata.version\n }\n\n const reason = flagDetails?.reason?.description ?? flagDetails?.reason?.code\n if (reason) {\n properties.$feature_flag_reason = reason\n }\n\n if (flagDetails?.metadata?.id) {\n properties.$feature_flag_id = flagDetails.metadata.id\n }\n\n // It's possible that flag values were overridden by calling overrideFeatureFlags.\n // We want to capture the original values in case someone forgets they were using overrides\n // and is wondering why their app is acting weird.\n if (!isUndefined(flagDetails?.original_variant) || !isUndefined(flagDetails?.original_enabled)) {\n properties.$feature_flag_original_response = !isUndefined(flagDetails.original_variant)\n ? flagDetails.original_variant\n : flagDetails.original_enabled\n }\n\n if (flagDetails?.metadata?.original_payload) {\n properties.$feature_flag_original_payload = flagDetails?.metadata?.original_payload\n }\n\n if (errors.length) {\n properties.$feature_flag_error = errors.join(',')\n }\n\n this._instance.capture('$feature_flag_called', properties)\n }\n }\n\n if (!flagExists) {\n return undefined\n }\n\n let parsedPayload = payload\n if (!isUndefined(payload)) {\n try {\n parsedPayload = JSON.parse(payload as any)\n } catch {\n // payload is already parsed or not valid JSON, keep as-is\n }\n }\n\n return {\n key,\n enabled: !!flagValue,\n variant: typeof flagValue === 'string' ? flagValue : undefined,\n payload: parsedPayload,\n }\n }\n\n /*\n * Fetches the payload for a remote config feature flag. This method will bypass any cached values and fetch the latest\n * value from the PostHog API.\n *\n * Note: Because the posthog-js SDK is primarily used with public project API keys, encrypted remote config payloads will\n * be redacted, never decrypted in the response.\n *\n * ### Usage:\n *\n * getRemoteConfigPayload(\"home-page-welcome-message\", (payload) => console.log(`Fetched remote config: ${payload}`))\n *\n * @param {String} key Key of the feature flag.\n * @param {Function} [callback] The callback function will be called once the remote config feature flag payload has been fetched.\n */\n getRemoteConfigPayload(key: string, callback: RemoteConfigFeatureFlagCallback): void {\n const token = this._config.token\n const data: Record = {\n distinct_id: this._instance.get_distinct_id(),\n token,\n }\n\n // Add evaluation contexts if configured\n if (this._shouldIncludeEvaluationEnvironments()) {\n data.evaluation_contexts = this._getValidEvaluationEnvironments()\n }\n\n this._instance._send_request({\n method: 'POST',\n url: this._instance.requestRouter.endpointFor('flags', '/flags/?v=2'),\n data,\n compression: this._config.disable_compression ? undefined : Compression.Base64,\n timeout: this._config.feature_flag_request_timeout_ms,\n callback: (response) => {\n const flagPayloads = response.json?.['featureFlagPayloads']\n callback(flagPayloads?.[key] || undefined)\n },\n })\n }\n\n /**\n * See if feature flag is enabled for user.\n *\n * By default, this method may return cached values from localStorage if the `/flags` endpoint\n * hasn't responded yet. This reduces flicker but means you might briefly see stale values\n * (e.g., a flag that was disabled on the server).\n *\n * ### Usage:\n *\n * if(posthog.isFeatureEnabled('beta-feature')) { // do something }\n *\n * // Only use fresh values from the server\n * if(posthog.isFeatureEnabled('beta-feature', { fresh: true })) { // do something }\n *\n * @param {String} key Key of the feature flag.\n * @param {Object} [options] Optional settings.\n * @param {boolean} [options.send_event=true] If false, won't send a $feature_flag_called event to PostHog.\n * @param {boolean} [options.fresh=false] If true, only returns values loaded from the server, not cached localStorage values.\n * Use this when you need to ensure the flag value reflects the current server state.\n * Returns undefined until the /flags endpoint responds.\n * @returns {boolean | undefined} Whether the flag is enabled, or undefined if not found or not yet loaded.\n */\n isFeatureEnabled(key: string, options: FeatureFlagOptions = {}): boolean | undefined {\n if (options.fresh && !this._flagsLoadedFromRemote) {\n return undefined\n }\n if (!this._hasLoadedFlags && !(this.getFlags() && this.getFlags().length > 0)) {\n logger.warn('isFeatureEnabled for key \"' + key + FLAG_TIMEOUT_MSG)\n return undefined\n }\n const flagValue = this.getFeatureFlag(key, options)\n return isUndefined(flagValue) ? undefined : !!flagValue\n }\n\n addFeatureFlagsHandler(handler: FeatureFlagsCallback): void {\n this.featureFlagEventHandlers.push(handler)\n }\n\n removeFeatureFlagsHandler(handler: FeatureFlagsCallback): void {\n this.featureFlagEventHandlers = this.featureFlagEventHandlers.filter((h) => h !== handler)\n }\n\n receivedFeatureFlags(\n response: Partial,\n errorsLoading?: boolean,\n options?: { partialResponse?: boolean }\n ): void {\n if (!this._persistence) {\n return\n }\n this._hasLoadedFlags = true\n\n const currentFlags = this.getFlagVariants()\n const currentFlagPayloads = this.getFlagPayloads()\n const currentFlagDetails = this.getFlagsWithDetails()\n parseFlagsResponse(response, this._persistence, currentFlags, currentFlagPayloads, currentFlagDetails, options)\n\n // Reset stale refresh flag when we successfully receive fresh flags\n if (!errorsLoading) {\n this._staleCacheRefreshTriggered = false\n }\n\n this._fireFeatureFlagsCallbacks(errorsLoading)\n }\n\n /**\n * @deprecated Use overrideFeatureFlags instead. This will be removed in a future version.\n */\n override(flags: boolean | string[] | Record, suppressWarning: boolean = false): void {\n logger.warn('override is deprecated. Please use overrideFeatureFlags instead.')\n this.overrideFeatureFlags({\n flags: flags,\n suppressWarning: suppressWarning,\n })\n }\n\n /**\n * Override feature flags on the client-side. Useful for setting non-persistent feature flags,\n * or for testing/debugging feature flags in the PostHog app.\n *\n * ### Usage:\n *\n * - posthog.featureFlags.overrideFeatureFlags(false) // clear all overrides\n * - posthog.featureFlags.overrideFeatureFlags(['beta-feature']) // enable flags\n * - posthog.featureFlags.overrideFeatureFlags({'beta-feature': 'variant'}) // set variants\n * - posthog.featureFlags.overrideFeatureFlags({ flags: ['beta-feature'] }) // enable flags\n * - posthog.featureFlags.overrideFeatureFlags({ flags: {'beta-feature': 'variant'} }) // set variants\n * - posthog.featureFlags.overrideFeatureFlags({ // set both flags and payloads\n * flags: {'beta-feature': 'variant'},\n * payloads: { 'beta-feature': { someData: true } }\n * })\n * - posthog.featureFlags.overrideFeatureFlags({ // only override payloads\n * payloads: { 'beta-feature': { someData: true } }\n * })\n */\n overrideFeatureFlags(overrideOptions: OverrideFeatureFlagsOptions): void {\n if (!this._instance.__loaded || !this._persistence) {\n return logger.uninitializedWarning('posthog.featureFlags.overrideFeatureFlags')\n }\n\n // Clear all overrides if false, lets you do something like posthog.featureFlags.overrideFeatureFlags(false)\n if (overrideOptions === false) {\n this._persistence.unregister(PERSISTENCE_OVERRIDE_FEATURE_FLAGS)\n this._persistence.unregister(PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS)\n this._fireFeatureFlagsCallbacks()\n\n return forceDebugLogger.info('All overrides cleared')\n }\n\n // Array syntax: ['flag-a', 'flag-b'] -> { 'flag-a': true, 'flag-b': true }\n if (isArray(overrideOptions)) {\n const flagsObj = arrayToFlagsRecord(overrideOptions)\n this._persistence.register({ [PERSISTENCE_OVERRIDE_FEATURE_FLAGS]: flagsObj })\n this._fireFeatureFlagsCallbacks()\n\n return forceDebugLogger.info('Flag overrides set', { flags: overrideOptions })\n }\n\n if (\n overrideOptions &&\n typeof overrideOptions === 'object' &&\n ('flags' in overrideOptions || 'payloads' in overrideOptions)\n ) {\n const options = overrideOptions\n this._override_warning = Boolean(options.suppressWarning ?? false)\n\n // Handle flags if provided, lets you do something like posthog.featureFlags.overrideFeatureFlags({flags: ['beta-feature']})\n if ('flags' in options) {\n if (options.flags === false) {\n this._persistence.unregister(PERSISTENCE_OVERRIDE_FEATURE_FLAGS)\n forceDebugLogger.info('Flag overrides cleared')\n } else if (options.flags) {\n if (isArray(options.flags)) {\n const flagsObj = arrayToFlagsRecord(options.flags)\n this._persistence.register({ [PERSISTENCE_OVERRIDE_FEATURE_FLAGS]: flagsObj })\n } else {\n this._persistence.register({ [PERSISTENCE_OVERRIDE_FEATURE_FLAGS]: options.flags })\n }\n\n forceDebugLogger.info('Flag overrides set', { flags: options.flags })\n }\n }\n\n // Handle payloads independently, lets you do something like posthog.featureFlags.overrideFeatureFlags({payloads: { 'beta-feature': { someData: true } }})\n if ('payloads' in options) {\n if (options.payloads === false) {\n this._persistence.unregister(PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS)\n forceDebugLogger.info('Payload overrides cleared')\n } else if (options.payloads) {\n this._persistence.register({\n [PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS]: options.payloads,\n })\n forceDebugLogger.info('Payload overrides set', { payloads: options.payloads })\n }\n }\n\n this._fireFeatureFlagsCallbacks()\n return\n }\n\n // Fallback: treat as Record, e.g. {'beta-feature': 'variant'}\n if (overrideOptions && typeof overrideOptions === 'object') {\n this._persistence.register({\n [PERSISTENCE_OVERRIDE_FEATURE_FLAGS]: overrideOptions as Record,\n })\n this._fireFeatureFlagsCallbacks()\n\n return forceDebugLogger.info('Flag overrides set', { flags: overrideOptions })\n }\n\n logger.warn('Invalid overrideOptions provided to overrideFeatureFlags', { overrideOptions })\n }\n\n /*\n * Register an event listener that runs when feature flags become available or when they change.\n * If there are flags, the listener is called immediately in addition to being called on future changes.\n *\n * ### Usage:\n *\n * posthog.onFeatureFlags(function(featureFlags, featureFlagsVariants, { errorsLoading }) { // do something })\n *\n * @param {Function} [callback] The callback function will be called once the feature flags are ready or when they are updated.\n * It'll return a list of feature flags enabled for the user, the variants,\n * and also a context object indicating whether we succeeded to fetch the flags or not.\n * @returns {Function} A function that can be called to unsubscribe the listener. Used by useEffect when the component unmounts.\n */\n onFeatureFlags(callback: FeatureFlagsCallback): () => void {\n this.addFeatureFlagsHandler(callback)\n if (this._hasLoadedFlags) {\n const { flags, flagVariants } = this._prepareFeatureFlagsForCallbacks()\n callback(flags, flagVariants)\n }\n return () => this.removeFeatureFlagsHandler(callback)\n }\n\n updateEarlyAccessFeatureEnrollment(key: string, isEnrolled: boolean, stage?: string): void {\n const existing_early_access_features: EarlyAccessFeature[] = this._prop(PERSISTENCE_EARLY_ACCESS_FEATURES) || []\n const feature = existing_early_access_features.find((f) => f.flagKey === key)\n\n const enrollmentPersonProp = {\n [`$feature_enrollment/${key}`]: isEnrolled,\n }\n\n const properties: Properties = {\n $feature_flag: key,\n $feature_enrollment: isEnrolled,\n $set: enrollmentPersonProp,\n }\n\n if (feature) {\n properties['$early_access_feature_name'] = feature.name\n }\n\n if (stage) {\n properties['$feature_enrollment_stage'] = stage\n }\n\n this._instance.capture('$feature_enrollment_update', properties)\n this.setPersonPropertiesForFlags(enrollmentPersonProp, false)\n\n const newFlags = { ...this.getFlagVariants(), [key]: isEnrolled }\n this._persistence?.register({\n [PERSISTENCE_ACTIVE_FEATURE_FLAGS]: Object.keys(filterActiveFeatureFlags(newFlags)),\n [ENABLED_FEATURE_FLAGS]: newFlags,\n })\n this._fireFeatureFlagsCallbacks()\n }\n\n getEarlyAccessFeatures(\n callback: EarlyAccessFeatureCallback,\n force_reload = false,\n stages?: EarlyAccessFeatureStage[]\n ): void {\n const existing_early_access_features = this._prop(PERSISTENCE_EARLY_ACCESS_FEATURES)\n\n const stageParams = stages ? `&${stages.map((s) => `stage=${s}`).join('&')}` : ''\n\n if (!existing_early_access_features || force_reload) {\n this._instance._send_request({\n url: this._instance.requestRouter.endpointFor(\n 'api',\n `/api/early_access_features/?token=${this._config.token}${stageParams}`\n ),\n method: 'GET',\n callback: (response) => {\n if (!response.json) {\n return\n }\n const earlyAccessFeatures = (response.json as EarlyAccessFeatureResponse).earlyAccessFeatures\n // Unregister first to ensure complete replacement, not merge\n // This prevents accumulation of stale features in persistence\n this._persistence?.unregister(PERSISTENCE_EARLY_ACCESS_FEATURES)\n this._persistence?.register({ [PERSISTENCE_EARLY_ACCESS_FEATURES]: earlyAccessFeatures })\n return callback(earlyAccessFeatures)\n },\n })\n } else {\n return callback(existing_early_access_features)\n }\n }\n\n _prepareFeatureFlagsForCallbacks(): { flags: string[]; flagVariants: Record } {\n const flags = this.getFlags()\n const flagVariants = this.getFlagVariants()\n\n // Return truthy\n const truthyFlags = flags.filter((flag) => flagVariants[flag])\n const truthyFlagVariants = Object.keys(flagVariants)\n .filter((variantKey) => flagVariants[variantKey])\n .reduce((res: Record, key) => {\n res[key] = flagVariants[key]\n return res\n }, {})\n\n return {\n flags: truthyFlags,\n flagVariants: truthyFlagVariants,\n }\n }\n\n _fireFeatureFlagsCallbacks(errorsLoading?: boolean): void {\n const { flags, flagVariants } = this._prepareFeatureFlagsForCallbacks()\n this.featureFlagEventHandlers.forEach((handler) => handler(flags, flagVariants, { errorsLoading }))\n }\n\n /**\n * Set override person properties for feature flags.\n * This is used when dealing with new persons / where you don't want to wait for ingestion\n * to update user properties.\n */\n setPersonPropertiesForFlags(properties: Properties, reloadFeatureFlags = true): void {\n const existingProperties = this._prop(STORED_PERSON_PROPERTIES_KEY) || {}\n\n // If the caller passes { $set, $set_once }, split them apart so we can apply $set_once\n // semantics (skip keys that already exist). Otherwise treat all properties as $set for\n // backward compatibility with the public API.\n const propsToSet = properties?.['$set'] || (!properties?.['$set_once'] ? properties : {})\n const propsToSetOnce = properties?.['$set_once']\n\n const setOnceProps: Properties = {}\n if (propsToSetOnce) {\n for (const key in propsToSetOnce) {\n if (Object.prototype.hasOwnProperty.call(propsToSetOnce, key)) {\n if (!(key in existingProperties)) {\n setOnceProps[key] = propsToSetOnce[key]\n }\n }\n }\n }\n\n this._instance.register({\n [STORED_PERSON_PROPERTIES_KEY]: {\n ...existingProperties,\n ...setOnceProps,\n ...propsToSet,\n },\n })\n\n if (reloadFeatureFlags) {\n this._instance.reloadFeatureFlags()\n }\n }\n\n resetPersonPropertiesForFlags(): void {\n this._instance.unregister(STORED_PERSON_PROPERTIES_KEY)\n }\n\n /**\n * Set override group properties for feature flags.\n * This is used when dealing with new groups / where you don't want to wait for ingestion\n * to update properties.\n * Takes in an object, the key of which is the group type.\n * For example:\n * setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } })\n */\n setGroupPropertiesForFlags(properties: { [type: string]: Properties }, reloadFeatureFlags = true): void {\n // Get persisted group properties\n const existingProperties = this._prop(STORED_GROUP_PROPERTIES_KEY) || {}\n\n if (Object.keys(existingProperties).length !== 0) {\n Object.keys(existingProperties).forEach((groupType) => {\n existingProperties[groupType] = {\n ...existingProperties[groupType],\n ...properties[groupType],\n }\n delete properties[groupType]\n })\n }\n\n this._instance.register({\n [STORED_GROUP_PROPERTIES_KEY]: {\n ...existingProperties,\n ...properties,\n },\n })\n\n if (reloadFeatureFlags) {\n this._instance.reloadFeatureFlags()\n }\n }\n\n resetGroupPropertiesForFlags(group_type?: string): void {\n if (group_type) {\n const existingProperties = this._prop(STORED_GROUP_PROPERTIES_KEY) || {}\n this._instance.register({\n [STORED_GROUP_PROPERTIES_KEY]: { ...existingProperties, [group_type]: {} },\n })\n } else {\n this._instance.unregister(STORED_GROUP_PROPERTIES_KEY)\n }\n }\n\n reset(): void {\n this._hasLoadedFlags = false\n this._requestInFlight = false\n this._reloadingDisabled = false\n this._additionalReloadRequested = false\n this._flagsLoadedFromRemote = false\n this.$anon_distinct_id = undefined\n this._clearDebouncer()\n this._override_warning = false\n }\n}\n", "import { ERROR_TRACKING_CAPTURE_EXTENSION_EXCEPTIONS, ERROR_TRACKING_SUPPRESSION_RULES } from './constants'\nimport { Extension } from './extensions/types'\nimport { PostHog } from './posthog-core'\nimport { CaptureResult, ErrorTrackingSuppressionRule, Properties, RemoteConfig } from './types'\nimport { createLogger } from './utils/logger'\nimport { propertyComparisons } from './utils/property-utils'\nimport { isString, isArray, ErrorTracking, isNullish } from '@posthog/core'\n\nconst logger = createLogger('[Error tracking]')\n\nexport function buildErrorPropertiesBuilder() {\n return new ErrorTracking.ErrorPropertiesBuilder(\n [\n new ErrorTracking.DOMExceptionCoercer(),\n new ErrorTracking.PromiseRejectionEventCoercer(),\n new ErrorTracking.ErrorEventCoercer(),\n new ErrorTracking.ErrorCoercer(),\n new ErrorTracking.EventCoercer(),\n new ErrorTracking.ObjectCoercer(),\n new ErrorTracking.StringCoercer(),\n new ErrorTracking.PrimitiveCoercer(),\n ],\n ErrorTracking.createDefaultStackParser()\n )\n}\nexport class PostHogExceptions implements Extension {\n private readonly _instance: PostHog\n private _suppressionRules: ErrorTrackingSuppressionRule[] = []\n private _errorPropertiesBuilder: ErrorTracking.ErrorPropertiesBuilder = buildErrorPropertiesBuilder()\n\n constructor(instance: PostHog) {\n this._instance = instance\n this._suppressionRules = this._instance.persistence?.get_property(ERROR_TRACKING_SUPPRESSION_RULES) ?? []\n }\n\n onRemoteConfig(response: RemoteConfig) {\n if (!('errorTracking' in response)) {\n return\n }\n\n const suppressionRules = response.errorTracking?.suppressionRules ?? []\n const captureExtensionExceptions = response.errorTracking?.captureExtensionExceptions\n\n // store this in-memory in case persistence is disabled\n this._suppressionRules = suppressionRules\n\n if (this._instance.persistence) {\n this._instance.persistence.register({\n [ERROR_TRACKING_SUPPRESSION_RULES]: this._suppressionRules,\n [ERROR_TRACKING_CAPTURE_EXTENSION_EXCEPTIONS]: captureExtensionExceptions,\n })\n }\n }\n\n private get _captureExtensionExceptions() {\n const enabled_server_side = !!this._instance.get_property(ERROR_TRACKING_CAPTURE_EXTENSION_EXCEPTIONS)\n const enabled_client_side = this._instance.config.error_tracking.captureExtensionExceptions\n return enabled_client_side ?? enabled_server_side ?? false\n }\n\n buildProperties(\n input: unknown,\n metadata?: { handled?: boolean; syntheticException?: Error }\n ): ErrorTracking.ErrorProperties {\n return this._errorPropertiesBuilder.buildFromUnknown(input, {\n syntheticException: metadata?.syntheticException,\n mechanism: {\n handled: metadata?.handled,\n },\n })\n }\n\n sendExceptionEvent(properties: Properties): CaptureResult | undefined {\n const exceptionList = properties.$exception_list\n\n if (this._isExceptionList(exceptionList)) {\n if (this._matchesSuppressionRule(exceptionList)) {\n logger.info('Skipping exception capture because a suppression rule matched')\n return\n }\n\n if (!this._captureExtensionExceptions && this._isExtensionException(exceptionList)) {\n logger.info('Skipping exception capture because it was thrown by an extension')\n return\n }\n\n if (\n !this._instance.config.error_tracking.__capturePostHogExceptions &&\n this._isPostHogException(exceptionList)\n ) {\n logger.info('Skipping exception capture because it was thrown by the PostHog SDK')\n return\n }\n }\n\n return this._instance.capture('$exception', properties, {\n _noTruncate: true,\n _batchKey: 'exceptionEvent',\n _originatedFromCaptureException: true,\n })\n }\n\n private _matchesSuppressionRule(exceptionList: ErrorTracking.ExceptionList): boolean {\n if (exceptionList.length === 0) {\n return false\n }\n\n const exceptionValues = exceptionList.reduce(\n (acc, { type, value }) => {\n if (isString(type) && type.length > 0) {\n acc['$exception_types'].push(type)\n }\n if (isString(value) && value.length > 0) {\n acc['$exception_values'].push(value)\n }\n return acc\n },\n {\n $exception_types: [] as string[],\n $exception_values: [] as string[],\n }\n )\n\n return this._suppressionRules.some((rule) => {\n const results = rule.values.map((v) => {\n const compare = propertyComparisons[v.operator]\n const targets = isArray(v.value) ? v.value : [v.value]\n const values = exceptionValues[v.key] ?? []\n return targets.length > 0 ? compare(targets, values) : false\n })\n return rule.type === 'OR' ? results.some(Boolean) : results.every(Boolean)\n })\n }\n\n private _isExtensionException(exceptionList: ErrorTracking.ExceptionList): boolean {\n const frames = exceptionList.flatMap((e) => e.stacktrace?.frames ?? [])\n return frames.some((f) => f.filename && f.filename.startsWith('chrome-extension://'))\n }\n\n private _isPostHogException(exceptionList: ErrorTracking.ExceptionList): boolean {\n if (exceptionList.length > 0) {\n const exception = exceptionList[0]\n const frames = exception.stacktrace?.frames ?? []\n const lastFrame = frames[frames.length - 1]\n return lastFrame?.filename?.includes('posthog.com/static') ?? false\n }\n\n return false\n }\n\n private _isExceptionList(candidate: unknown): candidate is ErrorTracking.ExceptionList {\n return !isNullish(candidate) && isArray(candidate)\n }\n}\n", "import { PostHog } from './posthog-core'\nimport { navigator, window } from './utils/globals'\nimport {\n WebExperiment,\n WebExperimentsCallback,\n WebExperimentTransform,\n WebExperimentUrlMatchType,\n WebExperimentVariant,\n} from './web-experiments-types'\nimport { WEB_EXPERIMENTS } from './constants'\nimport { isNullish, isString } from '@posthog/core'\nimport { getQueryParam } from './utils/request-utils'\nimport { isMatchingRegex } from './utils/regex-utils'\nimport { logger } from './utils/logger'\nimport { isLikelyBot } from './utils/blocked-uas'\nimport { getCampaignParams } from './utils/event-utils'\nimport { Extension } from './extensions/types'\n\nconst BOT_REFUSE_MSG = 'Refusing to render web experiment since the viewer is a likely bot'\n\nexport const webExperimentUrlValidationMap: Record<\n WebExperimentUrlMatchType,\n (conditionsUrl: string, location: Location) => boolean\n> = {\n icontains: (conditionsUrl, location) =>\n !!window && location.href.toLowerCase().indexOf(conditionsUrl.toLowerCase()) > -1,\n not_icontains: (conditionsUrl, location) =>\n !!window && location.href.toLowerCase().indexOf(conditionsUrl.toLowerCase()) === -1,\n regex: (conditionsUrl, location) => !!window && isMatchingRegex(location.href, conditionsUrl),\n not_regex: (conditionsUrl, location) => !!window && !isMatchingRegex(location.href, conditionsUrl),\n exact: (conditionsUrl, location) => location.href === conditionsUrl,\n is_not: (conditionsUrl, location) => location.href !== conditionsUrl,\n}\n\nexport class WebExperiments implements Extension {\n private _flagToExperiments?: Map\n\n private get _config() {\n return this._instance.config\n }\n\n constructor(private _instance: PostHog) {\n this._instance.onFeatureFlags((flags: string[]) => {\n this.onFeatureFlags(flags)\n })\n }\n\n // No-op: activation is driven by the onFeatureFlags callback registered in the constructor\n initialize() {}\n\n onFeatureFlags(flags: string[]) {\n if (this._is_bot()) {\n WebExperiments._logInfo(BOT_REFUSE_MSG)\n return\n }\n\n if (this._config.disable_web_experiments) {\n return\n }\n\n if (isNullish(this._flagToExperiments)) {\n // Indicates first load so we trigger the loaders\n this._flagToExperiments = new Map()\n this.loadIfEnabled()\n this.previewWebExperiment()\n return\n }\n\n WebExperiments._logInfo('applying feature flags', flags)\n flags.forEach((flag) => {\n if (this._flagToExperiments && this._flagToExperiments?.has(flag)) {\n const selectedVariant = this._instance.getFeatureFlag(flag) as unknown as string\n const webExperiment = this._flagToExperiments?.get(flag)\n if (selectedVariant && webExperiment?.variants[selectedVariant]) {\n this._applyTransforms(\n webExperiment.name,\n selectedVariant,\n webExperiment.variants[selectedVariant].transforms\n )\n }\n }\n })\n }\n\n previewWebExperiment() {\n const location = WebExperiments.getWindowLocation()\n if (location?.search) {\n const experimentID = getQueryParam(location?.search, '__experiment_id')\n const variant = getQueryParam(location?.search, '__experiment_variant')\n if (experimentID && variant) {\n WebExperiments._logInfo(`previewing web experiments ${experimentID} && ${variant}`)\n this.getWebExperiments(\n (webExperiments) => {\n this._showPreviewWebExperiment(parseInt(experimentID), variant, webExperiments)\n },\n false,\n true\n )\n }\n }\n }\n\n loadIfEnabled() {\n if (this._config.disable_web_experiments) {\n return\n }\n\n this.getWebExperimentsAndEvaluateDisplayLogic()\n }\n\n public getWebExperimentsAndEvaluateDisplayLogic = (forceReload: boolean = false): void => {\n this.getWebExperiments((webExperiments) => {\n WebExperiments._logInfo(`retrieved web experiments from the server`)\n this._flagToExperiments = new Map()\n\n webExperiments.forEach((webExperiment) => {\n if (webExperiment.feature_flag_key) {\n if (this._flagToExperiments) {\n WebExperiments._logInfo(\n `setting flag key `,\n webExperiment.feature_flag_key,\n ` to web experiment `,\n webExperiment\n )\n this._flagToExperiments?.set(webExperiment.feature_flag_key, webExperiment)\n }\n\n const selectedVariant = this._instance.getFeatureFlag(webExperiment.feature_flag_key)\n if (isString(selectedVariant) && webExperiment.variants[selectedVariant]) {\n this._applyTransforms(\n webExperiment.name,\n selectedVariant,\n webExperiment.variants[selectedVariant].transforms\n )\n }\n } else if (webExperiment.variants) {\n for (const variant in webExperiment.variants) {\n const testVariant = webExperiment.variants[variant]\n const matchTest = WebExperiments._matchesTestVariant(testVariant)\n if (matchTest) {\n this._applyTransforms(webExperiment.name, variant, testVariant.transforms)\n }\n }\n }\n })\n }, forceReload)\n }\n\n public getWebExperiments(callback: WebExperimentsCallback, forceReload: boolean, previewing?: boolean) {\n if (this._config.disable_web_experiments && !previewing) {\n return callback([])\n }\n\n const existingWebExperiments = this._instance.get_property(WEB_EXPERIMENTS)\n if (existingWebExperiments && !forceReload) {\n return callback(existingWebExperiments)\n }\n\n this._instance._send_request({\n url: this._instance.requestRouter.endpointFor('api', `/api/web_experiments/?token=${this._config.token}`),\n method: 'GET',\n callback: (response) => {\n if (response.statusCode !== 200 || !response.json) {\n return callback([])\n }\n const webExperiments = response.json.experiments || []\n return callback(webExperiments)\n },\n })\n }\n\n private _showPreviewWebExperiment(experimentID: number, variant: string, webExperiments: WebExperiment[]) {\n const previewExperiments = webExperiments.filter((exp) => exp.id === experimentID)\n if (previewExperiments && previewExperiments.length > 0) {\n WebExperiments._logInfo(\n `Previewing web experiment [${previewExperiments[0].name}] with variant [${variant}]`\n )\n this._applyTransforms(\n previewExperiments[0].name,\n variant,\n previewExperiments[0].variants[variant].transforms\n )\n }\n }\n private static _matchesTestVariant(testVariant: WebExperimentVariant) {\n if (isNullish(testVariant.conditions)) {\n return false\n }\n return WebExperiments._matchUrlConditions(testVariant) && WebExperiments._matchUTMConditions(testVariant)\n }\n\n private static _matchUrlConditions(testVariant: WebExperimentVariant): boolean {\n if (isNullish(testVariant.conditions) || isNullish(testVariant.conditions?.url)) {\n return true\n }\n\n const location = WebExperiments.getWindowLocation()\n if (location) {\n const urlCheck = testVariant.conditions?.url\n ? webExperimentUrlValidationMap[testVariant.conditions?.urlMatchType ?? 'icontains'](\n testVariant.conditions.url,\n location\n )\n : true\n return urlCheck\n }\n\n return false\n }\n\n public static getWindowLocation(): Location | undefined {\n return window?.location\n }\n\n private static _matchUTMConditions(testVariant: WebExperimentVariant): boolean {\n if (isNullish(testVariant.conditions) || isNullish(testVariant.conditions?.utm)) {\n return true\n }\n const campaignParams = getCampaignParams()\n if (campaignParams['utm_source']) {\n // eslint-disable-next-line compat/compat\n const utmCampaignMatched = testVariant.conditions?.utm?.utm_campaign\n ? testVariant.conditions?.utm?.utm_campaign == campaignParams['utm_campaign']\n : true\n\n const utmSourceMatched = testVariant.conditions?.utm?.utm_source\n ? testVariant.conditions?.utm?.utm_source == campaignParams['utm_source']\n : true\n\n const utmMediumMatched = testVariant.conditions?.utm?.utm_medium\n ? testVariant.conditions?.utm?.utm_medium == campaignParams['utm_medium']\n : true\n\n const utmTermMatched = testVariant.conditions?.utm?.utm_term\n ? testVariant.conditions?.utm?.utm_term == campaignParams['utm_term']\n : true\n\n return utmCampaignMatched && utmMediumMatched && utmTermMatched && utmSourceMatched\n }\n\n return false\n }\n\n private static _logInfo(msg: string, ...args: any[]) {\n logger.info(`[WebExperiments] ${msg}`, args)\n }\n\n private _applyTransforms(experiment: string, variant: string, transforms: WebExperimentTransform[]) {\n if (this._is_bot()) {\n WebExperiments._logInfo(BOT_REFUSE_MSG)\n return\n }\n\n if (variant === 'control') {\n WebExperiments._logInfo('Control variants leave the page unmodified.')\n return\n }\n\n transforms.forEach((transform) => {\n if (transform.selector) {\n WebExperiments._logInfo(\n `applying transform of variant ${variant} for experiment ${experiment} `,\n transform\n )\n\n // eslint-disable-next-line no-restricted-globals\n const elements = document?.querySelectorAll(transform.selector)\n elements?.forEach((element) => {\n const htmlElement = element as HTMLElement\n if (transform.html) {\n htmlElement.innerHTML = transform.html\n }\n\n if (transform.css) {\n htmlElement.setAttribute('style', transform.css)\n }\n })\n }\n })\n }\n\n _is_bot(): boolean | undefined {\n if (navigator && this._instance) {\n return isLikelyBot(navigator, this._config.custom_blocked_useragents)\n } else {\n return undefined\n }\n }\n}\n", "import { LOAD_EXT_NOT_FOUND } from '../../constants'\nimport { PostHog } from '../../posthog-core'\nimport {\n ConversationsRemoteConfig,\n GetMessagesResponse,\n GetTicketsOptions,\n GetTicketsResponse,\n MarkAsReadResponse,\n RestoreFromTokenResponse,\n RequestRestoreLinkResponse,\n SendMessageResponse,\n UserProvidedTraits,\n} from '../../posthog-conversations-types'\nimport { RemoteConfig } from '../../types'\nimport { assignableWindow, LazyLoadedConversationsInterface } from '../../utils/globals'\nimport { createLogger } from '../../utils/logger'\nimport { isNullish, isUndefined, isBoolean, isNull } from '@posthog/core'\nimport { isToolbarInstance } from '../../utils'\nimport { Extension } from '../types'\n\nconst logger = createLogger('[Conversations]')\nconst NOT_AVAILABLE = 'Conversations not available yet.'\n\nexport type ConversationsManager = LazyLoadedConversationsInterface\n\nexport class PostHogConversations implements Extension {\n // This is set to undefined until the remote config is loaded\n // then it's set to true if conversations are enabled\n // or false if conversations are disabled in the project settings\n private _isConversationsEnabled?: boolean = undefined\n private _conversationsManager: LazyLoadedConversationsInterface | null = null\n private _isInitializing: boolean = false\n private _remoteConfig: ConversationsRemoteConfig | null = null\n\n constructor(private _instance: PostHog) {}\n\n initialize() {\n this.loadIfEnabled()\n }\n\n onRemoteConfig(response: RemoteConfig) {\n // Don't load conversations if disabled via config\n if (this._instance.config.disable_conversations) {\n return\n }\n\n const conversations = response['conversations']\n if (isNullish(conversations)) {\n return\n }\n\n // Handle both boolean and object response\n if (isBoolean(conversations)) {\n this._isConversationsEnabled = conversations\n } else {\n // It's a ConversationsRemoteConfig object\n this._isConversationsEnabled = conversations.enabled\n this._remoteConfig = conversations\n }\n\n this.loadIfEnabled()\n }\n\n reset(): void {\n // Delegate cleanup to the lazy-loaded manager (which knows about persistence keys)\n // If not loaded, there's nothing to reset anyway\n this._conversationsManager?.reset()\n this._conversationsManager = null\n\n // Reset local state\n this._isConversationsEnabled = undefined\n this._remoteConfig = null\n }\n\n loadIfEnabled() {\n if (this._conversationsManager) {\n return\n }\n if (this._isInitializing) {\n return\n }\n if (this._instance.config.disable_conversations) {\n return\n }\n // The toolbar's internal PostHog instance must not own the conversations\n // manager — its distinct_id is always anonymous and would be sent instead\n // of the identified user's ID.\n if (isToolbarInstance(this._instance.config)) {\n return\n }\n if (this._instance.config.cookieless_mode && this._instance.consent.isOptedOut()) {\n return\n }\n\n const phExtensions = assignableWindow?.__PosthogExtensions__\n if (!phExtensions) {\n return\n }\n\n // Wait for remote config to load\n if (isUndefined(this._isConversationsEnabled)) {\n return\n }\n\n // Check if conversations are enabled\n if (!this._isConversationsEnabled) {\n return\n }\n\n // Check if we have the required config\n if (!this._remoteConfig || !this._remoteConfig.token) {\n logger.error('Conversations enabled but missing token in remote config.')\n return\n }\n\n // Note: Domain check is done in ConversationsManager for widget rendering\n // The conversations API is loaded regardless of domain restrictions\n\n this._isInitializing = true\n\n try {\n const initConversations = phExtensions.initConversations\n if (initConversations) {\n // Conversations code is already loaded\n this._completeInitialization(initConversations)\n this._isInitializing = false\n return\n }\n\n // If we reach here, conversations code is not loaded yet\n const loadExternalDependency = phExtensions.loadExternalDependency\n if (!loadExternalDependency) {\n this._handleLoadError(LOAD_EXT_NOT_FOUND)\n return\n }\n\n // Load the conversations bundle\n loadExternalDependency(this._instance, 'conversations', (err) => {\n if (err || !phExtensions.initConversations) {\n this._handleLoadError('Could not load conversations script', err)\n } else {\n this._completeInitialization(phExtensions.initConversations)\n }\n this._isInitializing = false\n })\n } catch (e) {\n this._handleLoadError('Error initializing conversations', e)\n this._isInitializing = false\n }\n }\n\n /** Helper to finalize conversations initialization */\n private _completeInitialization(\n initConversationsFn: (config: ConversationsRemoteConfig, posthog: PostHog) => LazyLoadedConversationsInterface\n ): void {\n if (!this._remoteConfig) {\n logger.error('Cannot complete initialization: remote config is null')\n return\n }\n\n try {\n // Pass config and PostHog instance to the extension\n this._conversationsManager = initConversationsFn(this._remoteConfig, this._instance)\n logger.info('Conversations loaded successfully')\n } catch (e) {\n this._handleLoadError('Error completing conversations initialization', e)\n }\n }\n\n /** Helper to handle initialization errors */\n private _handleLoadError(message: string, error?: any): void {\n logger.error(message, error)\n this._conversationsManager = null\n this._isInitializing = false\n }\n\n /**\n * Show the conversations widget (button and chat panel)\n */\n show(): void {\n if (!this._conversationsManager) {\n logger.warn('Conversations not loaded yet.')\n return\n }\n this._conversationsManager.show()\n }\n\n /**\n * Hide the conversations widget completely (button and chat panel)\n */\n hide(): void {\n if (!this._conversationsManager) {\n return\n }\n this._conversationsManager.hide()\n }\n\n /**\n * Check if conversations are available (enabled in remote config AND loaded)\n * Use this to check if conversations API can be used.\n */\n isAvailable(): boolean {\n return this._isConversationsEnabled === true && !isNull(this._conversationsManager)\n }\n\n /**\n * Check if the widget is currently visible (rendered and shown)\n */\n isVisible(): boolean {\n return this._conversationsManager?.isVisible() ?? false\n }\n\n /**\n * Send a message programmatically\n * Creates a new ticket if none exists or if newTicket is true\n *\n * @param message - The message text to send\n * @param userTraits - Optional user identification data (name, email)\n * @param newTicket - If true, forces creation of a new ticket (starts new conversation)\n * @returns Promise with response or null if conversations not available yet\n * @note Conversations must be available first (check with isAvailable())\n *\n * @example\n * // Send to existing or create new conversation\n * const response = await posthog.conversations.sendMessage('Hello!', {\n * name: 'John Doe',\n * email: 'john@example.com'\n * })\n *\n * @example\n * // Force creation of a new conversation/ticket\n * const newConvo = await posthog.conversations.sendMessage('Start fresh', undefined, true)\n */\n async sendMessage(\n message: string,\n userTraits?: UserProvidedTraits,\n newTicket?: boolean\n ): Promise {\n if (!this._conversationsManager) {\n logger.warn(NOT_AVAILABLE)\n return null\n }\n return this._conversationsManager.sendMessage(message, userTraits, newTicket)\n }\n\n /**\n * Get messages for the current or specified ticket\n *\n * @param ticketId - Optional ticket ID (defaults to current active ticket)\n * @param after - Optional ISO timestamp to fetch messages after\n * @returns Promise with messages response or null if conversations not available yet\n * @note Conversations must be available first (check with isAvailable())\n *\n * @example\n * // Get messages for current ticket\n * const messages = await posthog.conversations.getMessages()\n *\n * // Get messages for specific ticket\n * const messages = await posthog.conversations.getMessages('ticket-uuid')\n */\n async getMessages(ticketId?: string, after?: string): Promise {\n if (!this._conversationsManager) {\n logger.warn(NOT_AVAILABLE)\n return null\n }\n return this._conversationsManager.getMessages(ticketId, after)\n }\n\n /**\n * Mark messages as read for the current or specified ticket\n *\n * @param ticketId - Optional ticket ID (defaults to current active ticket)\n * @returns Promise with response or null if conversations not available yet\n * @note Conversations must be available first (check with isAvailable())\n *\n * @example\n * await posthog.conversations.markAsRead()\n */\n async markAsRead(ticketId?: string): Promise {\n if (!this._conversationsManager) {\n logger.warn(NOT_AVAILABLE)\n return null\n }\n return this._conversationsManager.markAsRead(ticketId)\n }\n\n /**\n * Get list of tickets for the current widget session\n *\n * @param options - Optional filtering and pagination options\n * @returns Promise with tickets response or null if conversations not available yet\n * @note Conversations must be available first (check with isAvailable())\n *\n * @example\n * const tickets = await posthog.conversations.getTickets({\n * limit: 10,\n * offset: 0,\n * status: 'open'\n * })\n */\n async getTickets(options?: GetTicketsOptions): Promise {\n if (!this._conversationsManager) {\n logger.warn(NOT_AVAILABLE)\n return null\n }\n return this._conversationsManager.getTickets(options)\n }\n\n /**\n * Request a restore link email for previous conversations.\n *\n * @param email - Email address associated with previous conversations\n * @returns Promise with generic success response or null if conversations unavailable\n */\n async requestRestoreLink(email: string): Promise {\n if (!this._conversationsManager) {\n logger.warn(NOT_AVAILABLE)\n return null\n }\n return this._conversationsManager.requestRestoreLink(email)\n }\n\n /**\n * Redeem a restore token and relink eligible tickets to this browser session.\n *\n * @param restoreToken - Opaque restore token from restore email link\n * @returns Promise with restore status or null if conversations unavailable\n */\n async restoreFromToken(restoreToken: string): Promise {\n if (!this._conversationsManager) {\n logger.warn(NOT_AVAILABLE)\n return null\n }\n return this._conversationsManager.restoreFromToken(restoreToken)\n }\n\n /**\n * Parse and redeem `ph_conv_restore` token from the current URL.\n *\n * @returns Promise with restore status, or null when no token/conversations unavailable\n */\n async restoreFromUrlToken(): Promise {\n if (!this._conversationsManager) {\n logger.warn(NOT_AVAILABLE)\n return null\n }\n return this._conversationsManager.restoreFromUrlToken()\n }\n\n /**\n * Get the current active ticket ID\n * Returns null if no conversation has been started yet or if not available\n *\n * @returns Ticket ID or null\n * @note Safe to call before conversations are available, will return null\n *\n * @example\n * const ticketId = posthog.conversations.getCurrentTicketId()\n * if (ticketId) {\n * console.log('Current ticket ID:', ticketId)\n * }\n */\n getCurrentTicketId(): string | null {\n return this._conversationsManager?.getCurrentTicketId() ?? null\n }\n\n /**\n * Get the widget session ID (persistent browser identifier)\n * This ID is used for access control and stays the same across page loads\n * Returns null if conversations not available yet\n *\n * @returns Session ID or null if not available\n * @note Safe to call before conversations are available, will return null\n *\n * @example\n * const sessionId = posthog.conversations.getWidgetSessionId()\n * if (!sessionId) {\n * // Conversations not available yet\n * posthog.conversations.show()\n * }\n */\n getWidgetSessionId(): string | null {\n return this._conversationsManager?.getWidgetSessionId() ?? null\n }\n\n /** @internal Called by PostHog.setIdentity() -- forwards to the manager without recursing */\n _onIdentityChanged(): void {\n this._conversationsManager?.setIdentity()\n }\n\n /** @internal Called by PostHog.clearIdentity() -- forwards to the manager without recursing */\n _onIdentityCleared(): void {\n this._conversationsManager?.clearIdentity()\n }\n}\n", "import type {\n CaptureLogOptions,\n LogAttributeValue,\n LogSeverityLevel,\n OtlpSeverityEntry,\n OtlpSeverityText,\n OtlpAnyValue,\n OtlpKeyValue,\n OtlpLogRecord,\n OtlpLogsPayload,\n LogSdkContext,\n} from './types'\nimport { isArray, isBoolean, isNull, isNumber, isUndefined } from '@posthog/core'\nimport Config from './config'\n\n// ============================================================================\n// Severity mapping\n// ============================================================================\n\nconst OTLP_SEVERITY_MAP: Record = {\n trace: { text: 'TRACE', number: 1 },\n debug: { text: 'DEBUG', number: 5 },\n info: { text: 'INFO', number: 9 },\n warn: { text: 'WARN', number: 13 },\n error: { text: 'ERROR', number: 17 },\n fatal: { text: 'FATAL', number: 21 },\n}\n\nconst DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info\n\nexport function getOtlpSeverityText(level: LogSeverityLevel): OtlpSeverityText {\n return (OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY).text\n}\n\nexport function getOtlpSeverityNumber(level: LogSeverityLevel): number {\n return (OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY).number\n}\n\n// ============================================================================\n// OTLP AnyValue conversion\n// ============================================================================\n\nexport function toOtlpAnyValue(value: LogAttributeValue): OtlpAnyValue {\n if (isBoolean(value)) {\n return { boolValue: value }\n }\n if (isNumber(value)) {\n if (Number.isInteger(value)) {\n return { intValue: value }\n }\n return { doubleValue: value }\n }\n if (typeof value === 'string') {\n return { stringValue: value }\n }\n if (isArray(value)) {\n return { arrayValue: { values: value.map((v) => toOtlpAnyValue(v as LogAttributeValue)) } }\n }\n // Objects fall back to JSON — OTLP supports kvlistValue but our encoder stays flat for simplicity\n try {\n return { stringValue: JSON.stringify(value) }\n } catch {\n return { stringValue: String(value) }\n }\n}\n\nexport function toOtlpKeyValueList(attrs: Record): OtlpKeyValue[] {\n const result: OtlpKeyValue[] = []\n for (const key in attrs) {\n const value = attrs[key]\n if (isNull(value) || isUndefined(value)) {\n continue\n }\n result.push({ key, value: toOtlpAnyValue(value) })\n }\n return result\n}\n\n// ============================================================================\n// OTLP LogRecord construction\n// ============================================================================\n\nfunction timestampToUnixNano(): string {\n // OTLP expects nanoseconds as a string (uint64 doesn't fit in JS number)\n // Date.now() * 1_000_000 exceeds Number.MAX_SAFE_INTEGER, so we concat instead of multiply\n return String(Date.now()) + '000000'\n}\n\nexport function buildOtlpLogRecord(options: CaptureLogOptions, sdkContext: LogSdkContext): OtlpLogRecord {\n const level: LogSeverityLevel = options.level || 'info'\n const { text: severityText, number: severityNumber } = OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY\n const now = timestampToUnixNano()\n\n // Build attributes: auto-populated + user-provided (user wins on conflicts)\n const autoAttributes: Record = {}\n\n if (sdkContext.distinctId) {\n autoAttributes.posthogDistinctId = sdkContext.distinctId\n }\n if (sdkContext.sessionId) {\n autoAttributes.sessionId = sdkContext.sessionId\n }\n if (sdkContext.currentUrl) {\n autoAttributes['url.full'] = sdkContext.currentUrl\n }\n if (sdkContext.activeFeatureFlags && sdkContext.activeFeatureFlags.length > 0) {\n autoAttributes.feature_flags = sdkContext.activeFeatureFlags\n }\n\n const mergedAttributes = {\n ...autoAttributes,\n ...(options.attributes || {}),\n }\n\n const record: OtlpLogRecord = {\n timeUnixNano: now,\n observedTimeUnixNano: now,\n severityNumber,\n severityText,\n body: { stringValue: options.body },\n attributes: toOtlpKeyValueList(mergedAttributes),\n }\n\n if (options.trace_id) {\n record.traceId = options.trace_id\n }\n if (options.span_id) {\n record.spanId = options.span_id\n }\n if (!isUndefined(options.trace_flags)) {\n record.flags = options.trace_flags\n }\n\n return record\n}\n\n// ============================================================================\n// OTLP envelope construction\n// ============================================================================\n\nexport function buildOtlpLogsPayload(\n logRecords: OtlpLogRecord[],\n resourceAttributes: Record\n): OtlpLogsPayload {\n return {\n resourceLogs: [\n {\n resource: {\n attributes: toOtlpKeyValueList(resourceAttributes),\n },\n scopeLogs: [\n {\n scope: { name: Config.LIB_NAME },\n logRecords,\n },\n ],\n },\n ],\n }\n}\n", "/**\n * Pre-grouped extension bundles for tree-shaking support.\n *\n * Each bundle is self-contained: a feature plus its runtime dependencies.\n * Use these with `__extensionClasses` to control which extensions are included in your bundle.\n * The default `posthog-js` entrypoint includes all extensions. When using `posthog-js/slim`,\n * you can import only the bundles you need:\n *\n * @example\n * ```ts\n * import posthog from 'posthog-js/slim'\n * import { SessionReplayExtensions, AnalyticsExtensions } from 'posthog-js/extensions'\n *\n * posthog.init('ph_key', {\n * __extensionClasses: {\n * ...SessionReplayExtensions,\n * ...AnalyticsExtensions,\n * }\n * })\n * ```\n *\n * @module\n */\n\nimport { Autocapture } from '../autocapture'\nimport { DeadClicksAutocapture } from './dead-clicks-autocapture'\nimport { ExceptionObserver } from './exception-autocapture'\nimport { HistoryAutocapture } from './history-autocapture'\nimport { TracingHeaders } from './tracing-headers'\nimport { WebVitalsAutocapture } from './web-vitals'\nimport { SessionRecording } from './replay/session-recording'\nimport { Heatmaps } from '../heatmaps'\nimport { PostHogProductTours } from '../posthog-product-tours'\nimport { SiteApps } from '../site-apps'\nimport { PostHogConfig } from '../types'\nimport { PostHogSurveys } from '../posthog-surveys'\nimport { Toolbar } from './toolbar'\nimport { PostHogFeatureFlags } from '../posthog-featureflags'\nimport { PostHogExceptions } from '../posthog-exceptions'\nimport { WebExperiments } from '../web-experiments'\nimport { PostHogConversations } from './conversations/posthog-conversations'\nimport { PostHogLogs } from '../posthog-logs'\n\ntype ExtensionClasses = NonNullable\n\n/** Feature flags. */\nexport const FeatureFlagsExtensions = {\n featureFlags: PostHogFeatureFlags,\n} as const satisfies ExtensionClasses\n\n/** Session replay. */\nexport const SessionReplayExtensions = {\n sessionRecording: SessionRecording,\n} as const satisfies ExtensionClasses\n\n/** Autocapture, click tracking, heatmaps, and web vitals. */\nexport const AnalyticsExtensions = {\n autocapture: Autocapture,\n historyAutocapture: HistoryAutocapture,\n heatmaps: Heatmaps,\n deadClicksAutocapture: DeadClicksAutocapture,\n webVitalsAutocapture: WebVitalsAutocapture,\n} as const satisfies ExtensionClasses\n\n/** Exception and error capture. Requires both the observer (capture hook) and exceptions (forwarding). */\nexport const ErrorTrackingExtensions = {\n exceptionObserver: ExceptionObserver,\n exceptions: PostHogExceptions,\n} as const satisfies ExtensionClasses\n\n/** In-app product tours. Includes feature flags for targeting. */\nexport const ProductToursExtensions = {\n productTours: PostHogProductTours,\n ...FeatureFlagsExtensions,\n} as const satisfies ExtensionClasses\n\n/** Site apps support. */\nexport const SiteAppsExtensions = {\n siteApps: SiteApps,\n} as const satisfies ExtensionClasses\n\n/** Distributed tracing header injection. */\nexport const TracingExtensions = {\n tracingHeaders: TracingHeaders,\n} as const satisfies ExtensionClasses\n\n/** In-app surveys. Includes feature flags for targeting. */\nexport const SurveysExtensions = {\n surveys: PostHogSurveys,\n ...FeatureFlagsExtensions,\n} as const satisfies ExtensionClasses\n\n/** PostHog toolbar for visual element inspection and action setup. */\nexport const ToolbarExtensions = {\n toolbar: Toolbar,\n} as const satisfies ExtensionClasses\n\n/** Web experiments. Includes feature flags for variant evaluation. */\nexport const ExperimentsExtensions = {\n experiments: WebExperiments,\n ...FeatureFlagsExtensions,\n} as const satisfies ExtensionClasses\n\n/** In-app conversations. */\nexport const ConversationsExtensions = {\n conversations: PostHogConversations,\n} as const satisfies ExtensionClasses\n\n/** Console log capture. */\nexport const LogsExtensions = {\n logs: PostHogLogs,\n} as const satisfies ExtensionClasses\n\n/** All extensions — equivalent to the default `posthog-js` bundle. */\nexport const AllExtensions = {\n ...FeatureFlagsExtensions,\n ...SessionReplayExtensions,\n ...AnalyticsExtensions,\n ...ErrorTrackingExtensions,\n ...ProductToursExtensions,\n ...SiteAppsExtensions,\n ...SurveysExtensions,\n ...TracingExtensions,\n ...ToolbarExtensions,\n ...ExperimentsExtensions,\n ...ConversationsExtensions,\n ...LogsExtensions,\n} as const satisfies ExtensionClasses\n", "import { PostHog } from '../posthog-core'\nimport { EVENT_PAGEVIEW } from '../constants'\nimport { window } from '../utils/globals'\nimport { addEventListener } from '../utils'\nimport { logger } from '../utils/logger'\nimport { patch } from './replay/rrweb-plugins/patch'\nimport type { Extension } from './types'\n\n/**\n * This class is used to capture pageview events when the user navigates using the history API (pushState, replaceState)\n * and when the user navigates using the browser's back/forward buttons.\n *\n * The behavior is controlled by the `capture_pageview` configuration option:\n * - When set to `'history_change'`, this class will capture pageviews on history API changes\n */\nexport class HistoryAutocapture implements Extension {\n private _instance: PostHog\n private _popstateListener: (() => void) | undefined\n private _lastPathname: string\n\n constructor(instance: PostHog) {\n this._instance = instance\n this._lastPathname = window?.location?.pathname || ''\n }\n\n initialize() {\n this.startIfEnabled()\n }\n\n public get isEnabled(): boolean {\n return this._instance.config.capture_pageview === 'history_change'\n }\n\n public startIfEnabled(): void {\n if (this.isEnabled) {\n logger.info('History API monitoring enabled, starting...')\n this.monitorHistoryChanges()\n }\n }\n\n public stop(): void {\n if (this._popstateListener) {\n this._popstateListener()\n }\n this._popstateListener = undefined\n logger.info('History API monitoring stopped')\n }\n\n public monitorHistoryChanges(): void {\n if (!window || !window.history) {\n return\n }\n\n // Old fashioned, we could also use arrow functions but I think the closure for a patch is more reliable\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this\n\n if (!(window.history.pushState as any)?.__posthog_wrapped__) {\n patch(window.history, 'pushState', (originalPushState) => {\n return function patchedPushState(\n this: History,\n state: any,\n title: string,\n url?: string | URL | null\n ): void {\n ;(originalPushState as History['pushState']).call(this, state, title, url)\n self._capturePageview('pushState')\n }\n })\n }\n\n if (!(window.history.replaceState as any)?.__posthog_wrapped__) {\n patch(window.history, 'replaceState', (originalReplaceState) => {\n return function patchedReplaceState(\n this: History,\n state: any,\n title: string,\n url?: string | URL | null\n ): void {\n ;(originalReplaceState as History['replaceState']).call(this, state, title, url)\n self._capturePageview('replaceState')\n }\n })\n }\n\n this._setupPopstateListener()\n }\n\n private _capturePageview(navigationType: 'pushState' | 'replaceState' | 'popstate'): void {\n try {\n const currentPathname = window?.location?.pathname\n\n if (!currentPathname) {\n return\n }\n\n // Only capture pageview if the pathname has changed and the feature is enabled\n if (currentPathname !== this._lastPathname && this.isEnabled) {\n this._instance.capture(EVENT_PAGEVIEW, { navigation_type: navigationType })\n }\n\n this._lastPathname = currentPathname\n } catch (error) {\n logger.error(`Error capturing ${navigationType} pageview`, error)\n }\n }\n\n private _setupPopstateListener(): void {\n if (this._popstateListener) {\n return\n }\n\n const handler = () => {\n this._capturePageview('popstate')\n }\n\n addEventListener(window, 'popstate', handler)\n this._popstateListener = () => {\n if (window) {\n window.removeEventListener('popstate', handler)\n }\n }\n }\n}\n", "import { LOAD_EXT_NOT_FOUND } from './constants'\nimport Config from './config'\nimport { PostHog } from './posthog-core'\nimport type { CaptureLogOptions, RemoteConfig, Logger, LogSdkContext, LogAttributeValue, OtlpLogRecord } from './types'\nimport { isNullish } from '@posthog/core'\nimport { assignableWindow } from './utils/globals'\nimport { createLogger } from './utils/logger'\nimport { Extension } from './extensions/types'\nimport { buildOtlpLogRecord, buildOtlpLogsPayload } from './logs-utils'\n\nconst DEFAULT_FLUSH_INTERVAL_MS = 3000\nconst DEFAULT_MAX_BUFFER_SIZE = 100\nconst DEFAULT_MAX_LOGS_PER_INTERVAL = 1000\n\ninterface BufferedLogEntry {\n record: OtlpLogRecord\n}\n\nexport class PostHogLogs implements Extension {\n private _isLogsEnabled: boolean = false\n private _isLoaded: boolean = false\n private readonly _logger = createLogger('[logs]')\n\n private _logBuffer: BufferedLogEntry[] = []\n private _flushTimeout: ReturnType | undefined\n private _logger_instance: Logger | undefined\n\n private _intervalLogCount: number = 0\n private _intervalWindowStart: number = 0\n private _droppedWarned: boolean = false\n\n constructor(private readonly _instance: PostHog) {\n if (this._instance && this._instance.config.logs?.captureConsoleLogs) {\n this._isLogsEnabled = true\n }\n }\n\n initialize() {\n this.loadIfEnabled()\n }\n\n onRemoteConfig(response: RemoteConfig) {\n // only load logs if they are enabled\n const logCapture = response.logs?.captureConsoleLogs\n if (isNullish(logCapture) || !logCapture) {\n return\n }\n this._isLogsEnabled = true\n this.loadIfEnabled()\n }\n\n reset(): void {\n this._logBuffer = []\n if (this._flushTimeout) {\n clearTimeout(this._flushTimeout)\n this._flushTimeout = undefined\n }\n this._intervalLogCount = 0\n this._intervalWindowStart = 0\n this._droppedWarned = false\n }\n\n loadIfEnabled() {\n if (!this._isLogsEnabled || this._isLoaded) {\n return\n }\n\n const phExtensions = assignableWindow?.__PosthogExtensions__\n if (!phExtensions) {\n this._logger.error('PostHog Extensions not found.')\n return\n }\n\n const loadExternalDependency = phExtensions.loadExternalDependency\n if (!loadExternalDependency) {\n this._logger.error(LOAD_EXT_NOT_FOUND)\n return\n }\n\n loadExternalDependency(this._instance, 'logs', (err) => {\n if (err || !phExtensions.logs?.initializeLogs) {\n this._logger.error('Could not load logs script', err)\n } else {\n phExtensions.logs.initializeLogs(this._instance)\n this._isLoaded = true\n }\n })\n }\n\n // ========================================================================\n // captureLog — sends logs directly to the OTEL logs endpoint\n // ========================================================================\n\n captureLog(options: CaptureLogOptions): void {\n if (!this._instance.is_capturing()) {\n return\n }\n\n if (!options || !options.body) {\n this._logger.warn('captureLog requires a body')\n return\n }\n\n const flushIntervalMs = this._instance.config.logs?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS\n const maxLogsPerInterval = this._instance.config.logs?.maxLogsPerInterval ?? DEFAULT_MAX_LOGS_PER_INTERVAL\n const now = Date.now()\n if (now - this._intervalWindowStart >= flushIntervalMs) {\n this._intervalWindowStart = now\n this._intervalLogCount = 0\n this._droppedWarned = false\n }\n if (this._intervalLogCount >= maxLogsPerInterval) {\n if (!this._droppedWarned) {\n this._logger.warn(\n `captureLog dropping logs: exceeded ${maxLogsPerInterval} logs per ${flushIntervalMs}ms`\n )\n this._droppedWarned = true\n }\n return\n }\n this._intervalLogCount++\n\n const sdkContext = this._getSdkContext()\n const record = buildOtlpLogRecord(options, sdkContext)\n\n this._logBuffer.push({ record })\n\n const maxBufferSize = this._instance.config.logs?.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE\n if (this._logBuffer.length >= maxBufferSize) {\n this.flushLogs()\n } else {\n this._scheduleFlush()\n }\n }\n\n get logger(): Logger {\n if (!this._logger_instance) {\n this._logger_instance = {\n trace: (body, attributes) => this.captureLog({ body, level: 'trace', attributes }),\n debug: (body, attributes) => this.captureLog({ body, level: 'debug', attributes }),\n info: (body, attributes) => this.captureLog({ body, level: 'info', attributes }),\n warn: (body, attributes) => this.captureLog({ body, level: 'warn', attributes }),\n error: (body, attributes) => this.captureLog({ body, level: 'error', attributes }),\n fatal: (body, attributes) => this.captureLog({ body, level: 'fatal', attributes }),\n }\n }\n return this._logger_instance\n }\n\n flushLogs(transport?: 'XHR' | 'fetch' | 'sendBeacon'): void {\n if (this._flushTimeout) {\n clearTimeout(this._flushTimeout)\n this._flushTimeout = undefined\n }\n\n if (this._logBuffer.length === 0) {\n return\n }\n\n const entries = this._logBuffer\n this._logBuffer = []\n\n const logsConfig = this._instance.config.logs\n const resourceAttributes: Record = {\n 'service.name': logsConfig?.serviceName || 'unknown_service',\n ...(logsConfig?.environment && { 'deployment.environment': logsConfig.environment }),\n ...(logsConfig?.serviceVersion && { 'service.version': logsConfig.serviceVersion }),\n ...logsConfig?.resourceAttributes,\n }\n\n const payload = buildOtlpLogsPayload(\n entries.map((e) => e.record),\n resourceAttributes\n )\n\n const url =\n this._instance.requestRouter.endpointFor('api', '/i/v1/logs') +\n '?token=' +\n encodeURIComponent(this._instance.config.token)\n\n this._instance._send_retriable_request({\n method: 'POST',\n url,\n data: payload,\n compression: 'best-available',\n batchKey: 'logs',\n transport,\n })\n }\n\n private _scheduleFlush(): void {\n if (this._flushTimeout) {\n return\n }\n this._flushTimeout = setTimeout(() => {\n this._flushTimeout = undefined\n this.flushLogs()\n }, this._instance.config.logs?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS)\n }\n\n private _getSdkContext(): LogSdkContext {\n const context: LogSdkContext = {\n lib: Config.LIB_NAME,\n }\n\n context.distinctId = this._instance.get_distinct_id()\n\n if (this._instance.sessionManager) {\n const { sessionId } = this._instance.sessionManager.checkAndGetSessionAndWindowId(true)\n context.sessionId = sessionId\n }\n\n if (assignableWindow?.location?.href) {\n context.currentUrl = assignableWindow.location.href\n }\n\n if (this._instance.featureFlags) {\n const flags = this._instance.featureFlags.getFlags()\n if (flags && flags.length > 0) {\n context.activeFeatureFlags = flags\n }\n }\n\n return context\n }\n}\n", "import { PostHog } from '../posthog-core'\nimport { AllExtensions } from '../extensions/extension-bundles'\n\nPostHog.__defaultExtensionClasses = {\n ...AllExtensions,\n}\n", "import './default-extensions'\nimport { init_as_module } from '../posthog-core'\nexport { PostHog } from '../posthog-core'\nexport * from '../types'\nexport * from '../posthog-surveys-types'\nexport * from '../posthog-product-tours-types'\nexport * from '../posthog-conversations-types'\nexport const posthog = init_as_module()\nexport default posthog\n", "import posthog from \"posthog-js\";\n\nconst config = window.__POSTHOG_CONFIG;\n\nif (config && config.apiKey) {\n posthog.init(config.apiKey, {\n api_host: config.apiHost,\n person_profiles: \"identified_only\",\n });\n\n if (config.user && config.user.id) {\n // Same distinct id Analytics::Posthog uses server-side (`user_`), so\n // a beta enrollment made here is the one the server's flag check reads,\n // and survey responses land on the same person as server events (sc-15926).\n posthog.identify(`user_${config.user.id}`, {\n email: config.user.email,\n account_id: config.user.accountId,\n });\n }\n\n // The dealership group the server attaches to its events: lets beta flags\n // and surveys target a rooftop, and breaks survey responses down by it.\n const dealershipId = config.context && config.context.dealership_id;\n if (dealershipId) {\n posthog.group(\"dealership\", String(dealershipId));\n }\n}\n\nwindow.posthog = posthog;\n\nexport default posthog;\n", "// Same design-system classes the layout renders; the legacy #flash colours in\n// lib/_flash.css were what showed when this reset the class to a bare \"notice\".\nconst FLASH_CLASSES = {\n notice: \"notice rounded-m border border-solid border-primary-100 bg-gray-50 text-primary-700\",\n error: \"error rounded-m border border-solid border-red-500 bg-red-50 text-red-700\",\n};\n\nwindow.Flash = class Flash {\n constructor (string, timeout) {\n this.string = string;\n this.e = $(\"#flash\").first();\n this.e.html(this.string);\n this.e.attr(\"class\", FLASH_CLASSES.notice);\n this.e.show();\n if (timeout) {\n setTimeout(() => Flash.hide(), timeout);\n }\n }\n\n error () {\n this.e.attr(\"class\", FLASH_CLASSES.error);\n return this;\n }\n\n addClass (className) {\n this.e.addClass(className);\n return this;\n }\n\n static hide () {\n return $(\"#flash\").hide();\n }\n\n static notice (s, timeout) {\n return new Flash(s, timeout);\n }\n\n static error (s, timeout) {\n return new Flash(s, timeout).error();\n }\n\n static doubleSale (s, timeout) {\n return new Flash(s, timeout).error().addClass(\"flash-double-sale\");\n }\n};\n", "window.Vin = class Vin {\n constructor (vin) {\n this.vin = vin;\n }\n\n vintage () {\n return new Vin.Vintage(this.vin).valid();\n }\n\n us () {\n return new Vin.US(this.vin).valid();\n }\n\n vintage_or_us () {\n return this.vintage() || this.us();\n }\n};\n\nwindow.Vin.Base = class Base {\n constructor (vin) {\n this.vin = vin;\n this.errors = [];\n }\n\n valid () {\n this.validate();\n return this.errors.length === 0;\n }\n};\n\nwindow.Vin.Vintage = class Vintage extends Vin.Base {\n validate () {\n this.errors = [];\n if ((this.vin.length < 6) || (this.vin.length > 17)) {\n this.errors.push(\"Vin may not be shorter than 3 characters or longer than 17.\");\n }\n if (!this.vin.match(/^[A-Z0-9]+$/)) {\n return this.errors.push(\"Vin may only contain the characters A-Z and 0-9.\");\n }\n }\n};\n\nwindow.Vin.US = class US extends Vin.Base {\n checksum_digit () {\n return this.vin[8] || \"\";\n }\n\n year_digit () {\n return this.vin[9] || \"\";\n }\n\n validate () {\n this.errors = [];\n if (this.vin.length !== 17) {\n this.errors.push(\"Vin must be exactly 17 characters in length.\");\n }\n if (this.vin.match(/[IOQ]/)) {\n this.errors.push(\"Vin may not contain I, O, or Q characters.\");\n }\n if (this.year_digit().match(/[0UZ]/)) {\n this.errors.push(\"Vin year digit may not contain the 0, U, or Z characters.\");\n }\n if (!this.valid_checksum()) {\n return this.errors.push(`Invalid checksum digit (was ${this.checksum_digit()}, should be ${this.calculated_checksum()})`);\n }\n }\n\n // checksum logic\n valid_checksum () {\n return this.checksum_digit() === this.calculated_checksum();\n }\n\n calculated_checksum () {\n const letter_values = {\n A: 1,\n B: 2,\n C: 3,\n D: 4,\n E: 5,\n F: 6,\n G: 7,\n H: 8,\n J: 1,\n K: 2,\n L: 3,\n M: 4,\n N: 5,\n P: 7,\n R: 9,\n S: 2,\n T: 3,\n U: 4,\n V: 5,\n W: 6,\n X: 7,\n Y: 8,\n Z: 9,\n };\n for (let x = 0; x <= 9; x++) {\n letter_values[x] = x + \"\";\n }\n\n const weights = {\n 1: 8,\n 2: 7,\n 3: 6,\n 4: 5,\n 5: 4,\n 6: 3,\n 7: 2,\n 8: 10,\n 10: 9,\n 11: 8,\n 12: 7,\n 13: 6,\n 14: 5,\n 15: 4,\n 16: 3,\n 17: 2,\n };\n\n let weight = 0;\n\n const iterable = this.vin.split(\"\");\n for (let i = 0; i < iterable.length; i++) {\n const c = iterable[i];\n const position = i + 1;\n const v = letter_values[c] * weights[position];\n if (position !== 9) { weight += v; }\n }\n if ((weight % 11) === 10) {\n return \"X\";\n } else {\n return (weight % 11) + \"\";\n }\n }\n};\n", "const editorConfig = {\n startupFocus: true,\n toolbar: [\n {\n name: \"clipboard\",\n items: [\"Cut\", \"Copy\", \"Paste\", \"PasteText\", \"PasteFromWord\", \"-\", \"Undo\", \"Redo\"],\n }, {\n name: \"editing\",\n items: [\"Find\", \"Replace\", \"-\", \"SelectAll\"],\n }, {\n name: \"links\",\n items: [\"Link\", \"Unlink\"],\n }, {\n name: \"insert\",\n items: [\"Image\", \"VideoThumb\", \"HorizontalRule\", \"SpecialChar\", \"Smiley\", \"PageBreak\"],\n }, \"/\", {\n name: \"basicstyles\",\n items: [\"Bold\", \"Italic\", \"Underline\", \"Strike\", \"Subscript\", \"Superscript\", \"-\", \"RemoveFormat\"],\n }, {\n name: \"paragraph\",\n items: [\n \"NumberedList\",\n \"BulletedList\",\n \"-\",\n \"Outdent\",\n \"Indent\",\n \"-\",\n \"Blockquote\",\n \"-\",\n \"JustifyLeft\",\n \"JustifyCenter\",\n \"JustifyRight\",\n \"JustifyBlock\",\n \"-\",\n \"BidiLtr\",\n \"BidiRtl\",\n ],\n }, \"/\", {\n name: \"styles\",\n items: [\"Styles\", \"Format\", \"Font\", \"FontSize\"],\n }, {\n name: \"colors\",\n items: [\"TextColor\", \"BGColor\"],\n }, {\n name: \"others\",\n items: [\"-\"],\n }, {\n name: \"about\",\n items: [\"About\"],\n },\n ],\n removeDialogTabs: \"link:upload;image:Upload\",\n};\n\nexport default editorConfig;\n", "import editorConfig from \"@/editor/config/toolbar\";\n\nclass Editor {\n constructor (selector) {\n this.field = $(selector);\n this.input = this.field.find(\"textarea\");\n this.inputID = this.input.attr(\"id\");\n this.addPhotoButton = this.field.find(\".addphoto\");\n this.setup();\n }\n\n setup () {\n CKEDITOR.replace(this.inputID, editorConfig);\n this.editor = CKEDITOR.instances[this.inputID];\n this.editor.focus();\n\n this.field.click(e => {\n if (e.target !== this.field) { return; }\n return this.editor.focus();\n });\n\n this.editor.on(\"focus\", () => {\n return this.field.addClass(\"focused\");\n });\n\n this.editor.on(\"blur\", () => {\n return this.field.removeClass(\"focused\");\n });\n\n if (this.addPhotoButton.length) {\n return this.addPhotoButton.on(\"click\", () => {\n return this.addPhoto();\n });\n }\n }\n\n getContent() {\n return this.instance.getData();\n }\n\n setContent(content) {\n this.instance.setData(content);\n }\n\n get instance() {\n return CKEDITOR.instances[this.inputID];\n }\n\n addPhoto () {\n const photo_url = this.addPhotoButton.data(\"url\");\n const html = ``;\n return this.editor.insertHtml(html);\n }\n}\nexport { Editor };\n\njQuery(function ($) {\n if ($(\".edit_user_signature, .new_user_signature\").length) {\n CKEDITOR.on(\"instanceReady\", () => {\n return $(\".edit_user_signature, .new_user_signature\").find(\"div.button, .utility\").show();\n });\n return new Editor(\".editor\");\n }\n});\n", "$(document).ready(function() {\n $(\"#integration_questionnaire_dms_vendor\").change(function() {\n if ($(this).val() === \"Other\") {\n $(this).after(\"\");\n } else {\n $(\"#integration_questionnaire_dms_vendor_other\").remove();\n }\n });\n\n $(\"#integration_questionnaire_inventory_management_vendor\").change(function() {\n if ($(this).val() === \"Other\") {\n $(this).after(\"\");\n } else {\n $(\"#integration_questionnaire_inventory_management_vendor_other\").remove();\n }\n });\n\n $(\"#integration_questionnaire_uses_autocheck\").change(function(event) {\n if (event.target.checked) {\n $(event.target).parent()\n .after(\"\");\n } else {\n $(\"#integration_questionnaire_autocheck_dealer_code\").remove();\n }\n });\n});\n", "const Cls = (window.Views.Upsheet = class Upsheet {\n static initClass () {\n this.updateSuccess = res => {\n if (!res.delivered) { $(\".buy_again\").remove(); }\n if (res.notes) { Views.Upsheet.replace_activity(res.notes); }\n if (!res.lost) { $(\"#lost\").html(\"\"); }\n if (res.quotes) { $(\"#quotes_partial\").html(res.quotes); }\n if (res.sales_stage) { $(\"#sales_stage\").replaceWith(res.sales_stage); }\n $(\"#scheduled_messages_list\").html(res.scheduled_messages);\n $(\"#todo_list\").html(res.todos);\n };\n }\n\n static replace_activity (activity) {\n $(\"#history_list\").html(activity);\n }\n});\nCls.initClass();\n", "jQuery(function () {\n return jQuery(document).ajaxError(function (event, jqxhr, settings, thrownError) {\n // A signed-in user without permission (access_denied's require_login:\n // false) stays put; /login would only bounce them to the dashboard.\n if (jqxhr.status === 403 && jqxhr.responseJSON?.require_login === false) {\n window.Flash?.error(jqxhr.responseJSON.message);\n } else if (thrownError === \"Forbidden\") {\n window.location.replace(\"/login\");\n }\n });\n});\n\nwindow.addEventListener(\"load\", function() {\n // Only maintain marketing panel local storage when in /upsheets\n // (a quick stop-gap measure until we have all upsheet related views reactified).\n if (!window.location.pathname.startsWith(\"/upsheets\")) {\n localStorage.setItem(\"openPanel\", null);\n }\n});\n", "const getDefaultsFromPostinstall = () => (undefined);\nexport { getDefaultsFromPostinstall };", "/**\n * @license\n * Copyright 2017 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 * http://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 * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\n */\n\nexport const CONSTANTS = {\n /**\n * @define {boolean} Whether this is the client Node.js SDK.\n */\n NODE_CLIENT: false,\n /**\n * @define {boolean} Whether this is the Admin Node.js SDK.\n */\n NODE_ADMIN: false,\n\n /**\n * Firebase SDK Version\n */\n SDK_VERSION: '${JSCORE_VERSION}'\n};\n", "/**\n * @license\n * Copyright 2017 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 * http://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 { CONSTANTS } from './constants';\n\n/**\n * Throws an error if the provided assertion is falsy\n */\nexport const assert = function (assertion: unknown, message: string): void {\n if (!assertion) {\n throw assertionError(message);\n }\n};\n\n/**\n * Returns an Error object suitable for throwing.\n */\nexport const assertionError = function (message: string): Error {\n return new Error(\n 'Firebase Database (' +\n CONSTANTS.SDK_VERSION +\n ') INTERNAL ASSERT FAILED: ' +\n message\n );\n};\n", "/**\n * @license\n * Copyright 2017 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 * http://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\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\n// TODO(dlarocque): Define this as a class, since we no longer target ES5.\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length; ) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw new DecodeBase64StringError();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n", "/**\n * @license\n * Copyright 2017 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 * http://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 * Do a deep-copy of basic JavaScript Objects or Arrays.\n */\nexport function deepCopy(value: T): T {\n return deepExtend(undefined, value) as T;\n}\n\n/**\n * Copy properties from source to target (recursively allows extension\n * of Objects and Arrays). Scalar values in the target are over-written.\n * If target is undefined, an object of the appropriate type will be created\n * (and returned).\n *\n * We recursively copy all child properties of plain Objects in the source- so\n * that namespace- like dictionaries are merged.\n *\n * Note that the target can be a function, in which case the properties in\n * the source Object are copied onto it as static properties of the Function.\n *\n * Note: we don't merge __proto__ to prevent prototype pollution\n */\nexport function deepExtend(target: unknown, source: unknown): unknown {\n if (!(source instanceof Object)) {\n return source;\n }\n\n switch (source.constructor) {\n case Date:\n // Treat Dates like scalars; if the target date object had any child\n // properties - they will be lost!\n const dateValue = source as Date;\n return new Date(dateValue.getTime());\n\n case Object:\n if (target === undefined) {\n target = {};\n }\n break;\n case Array:\n // Always copy the array source and overwrite the target.\n target = [];\n break;\n\n default:\n // Not a plain Object - treat it as a scalar.\n return source;\n }\n\n for (const prop in source) {\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\n continue;\n }\n (target as Record)[prop] = deepExtend(\n (target as Record)[prop],\n (source as Record)[prop]\n );\n }\n\n return target;\n}\n\nfunction isValidKey(key: string): boolean {\n return key !== '__proto__';\n}\n", "/**\n * @license\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 * http://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 * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('Unable to locate global object.');\n}\n", "/**\n * @license\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 * http://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 { base64Decode } from './crypt';\nimport { getGlobal } from './global';\nimport { getDefaultsFromPostinstall } from './postinstall';\n\n/**\n * Keys for experimental properties on the `FirebaseDefaults` object.\n * @public\n */\nexport type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge';\n\n/**\n * An object that can be injected into the environment as __FIREBASE_DEFAULTS__,\n * either as a property of globalThis, a shell environment variable, or a\n * cookie.\n *\n * This object can be used to automatically configure and initialize\n * a Firebase app as well as any emulators.\n *\n * @public\n */\nexport interface FirebaseDefaults {\n config?: Record;\n emulatorHosts?: Record;\n _authTokenSyncURL?: string;\n _authIdTokenMaxAge?: number;\n /**\n * Override Firebase's runtime environment detection and\n * force the SDK to act as if it were in the specified environment.\n */\n forceEnvironment?: 'browser' | 'node';\n [key: string]: unknown;\n}\n\ndeclare global {\n // Need `var` for this to work.\n // eslint-disable-next-line no-var\n var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;\n}\n\nconst getDefaultsFromGlobal = (): FirebaseDefaults | undefined =>\n getGlobal().__FIREBASE_DEFAULTS__;\n\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = (): FirebaseDefaults | undefined => {\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n return;\n }\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n if (defaultsJsonString) {\n return JSON.parse(defaultsJsonString);\n }\n};\n\nconst getDefaultsFromCookie = (): FirebaseDefaults | undefined => {\n if (typeof document === 'undefined') {\n return;\n }\n let match;\n try {\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n } catch (e) {\n // Some environments such as Angular Universal SSR have a\n // `document` object but error on accessing `document.cookie`.\n return;\n }\n const decoded = match && base64Decode(match[1]);\n return decoded && JSON.parse(decoded);\n};\n\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nexport const getDefaults = (): FirebaseDefaults | undefined => {\n try {\n return (\n getDefaultsFromPostinstall() ||\n getDefaultsFromGlobal() ||\n getDefaultsFromEnvVariable() ||\n getDefaultsFromCookie()\n );\n } catch (e) {\n /**\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n * to any environment case we have not accounted for. Log to\n * info instead of swallowing so we can find these unknown cases\n * and add paths for them if needed.\n */\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n return;\n }\n};\n\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\nexport const getDefaultEmulatorHost = (\n productName: string\n): string | undefined => getDefaults()?.emulatorHosts?.[productName];\n\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nexport const getDefaultEmulatorHostnameAndPort = (\n productName: string\n): [hostname: string, port: number] | undefined => {\n const host = getDefaultEmulatorHost(productName);\n if (!host) {\n return undefined;\n }\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n }\n // eslint-disable-next-line no-restricted-globals\n const port = parseInt(host.substring(separatorIndex + 1), 10);\n if (host[0] === '[') {\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n return [host.substring(1, separatorIndex - 1), port];\n } else {\n return [host.substring(0, separatorIndex), port];\n }\n};\n\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nexport const getDefaultAppConfig = (): Record | undefined =>\n getDefaults()?.config;\n\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nexport const getExperimentalSetting = (\n name: T\n): FirebaseDefaults[`_${T}`] =>\n getDefaults()?.[`_${name}`] as FirebaseDefaults[`_${T}`];\n", "/**\n * @license\n * Copyright 2017 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 * http://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\nexport class Deferred {\n promise: Promise;\n reject: (value?: unknown) => void = () => {};\n resolve: (value?: unknown) => void = () => {};\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve as (value?: unknown) => void;\n this.reject = reject as (value?: unknown) => void;\n });\n }\n\n /**\n * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\n */\n wrapCallback(\n callback?: (error?: unknown, value?: unknown) => void\n ): (error: unknown, value?: unknown) => void {\n return (error, value?) => {\n if (error) {\n this.reject(error);\n } else {\n this.resolve(value);\n }\n if (typeof callback === 'function') {\n // Attaching noop handler just in case developer wasn't expecting\n // promises\n this.promise.catch(() => {});\n\n // Some of our callbacks don't expect a value and our own tests\n // assert that the parameter length is 1\n if (callback.length === 1) {\n callback(error);\n } else {\n callback(error, value);\n }\n }\n };\n }\n}\n", "/**\n * @license\n * Copyright 2025 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 * http://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 * Checks whether host is a cloud workstation or not.\n * @public\n */\nexport function isCloudWorkstation(url: string): boolean {\n // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions\n // In HTTP request builders, it's called with the protocol.\n // If called with protocol prefix, it's a valid URL, so we extract the hostname\n // If called without, we assume the string is the hostname.\n try {\n const host =\n url.startsWith('http://') || url.startsWith('https://')\n ? new URL(url).hostname\n : url;\n return host.endsWith('.cloudworkstations.dev');\n } catch {\n return false;\n }\n}\n\n/**\n * Makes a fetch request to the given server.\n * Mostly used for forwarding cookies in Firebase Studio.\n * @public\n */\nexport async function pingServer(endpoint: string): Promise {\n const result = await fetch(endpoint, {\n credentials: 'include'\n });\n return result.ok;\n}\n", "/**\n * @license\n * Copyright 2021 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 * http://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 { base64urlEncodeWithoutPadding } from './crypt';\nimport { isCloudWorkstation } from './url';\n\n// Firebase Auth tokens contain snake_case claims following the JWT standard / convention.\n/* eslint-disable camelcase */\n\nexport type FirebaseSignInProvider =\n | 'custom'\n | 'email'\n | 'password'\n | 'phone'\n | 'anonymous'\n | 'google.com'\n | 'facebook.com'\n | 'github.com'\n | 'twitter.com'\n | 'microsoft.com'\n | 'apple.com';\n\ninterface FirebaseIdToken {\n // Always set to https://securetoken.google.com/PROJECT_ID\n iss: string;\n\n // Always set to PROJECT_ID\n aud: string;\n\n // The user's unique ID\n sub: string;\n\n // The token issue time, in seconds since epoch\n iat: number;\n\n // The token expiry time, normally 'iat' + 3600\n exp: number;\n\n // The user's unique ID. Must be equal to 'sub'\n user_id: string;\n\n // The time the user authenticated, normally 'iat'\n auth_time: number;\n\n // The sign in provider, only set when the provider is 'anonymous'\n provider_id?: 'anonymous';\n\n // The user's primary email\n email?: string;\n\n // The user's email verification status\n email_verified?: boolean;\n\n // The user's primary phone number\n phone_number?: string;\n\n // The user's display name\n name?: string;\n\n // The user's profile photo URL\n picture?: string;\n\n // Information on all identities linked to this user\n firebase: {\n // The primary sign-in provider\n sign_in_provider: FirebaseSignInProvider;\n\n // A map of providers to the user's list of unique identifiers from\n // each provider\n identities?: { [provider in FirebaseSignInProvider]?: string[] };\n };\n\n // Custom claims set by the developer\n [claim: string]: unknown;\n\n uid?: never; // Try to catch a common mistake of \"uid\" (should be \"sub\" instead).\n}\n\nexport type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) &\n Partial;\n\nexport function createMockUserToken(\n token: EmulatorMockTokenOptions,\n projectId?: string\n): string {\n if (token.uid) {\n throw new Error(\n 'The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.'\n );\n }\n // Unsecured JWTs use \"none\" as the algorithm.\n const header = {\n alg: 'none',\n type: 'JWT'\n };\n\n const project = projectId || 'demo-project';\n const iat = token.iat || 0;\n const sub = token.sub || token.user_id;\n if (!sub) {\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n }\n\n const payload: FirebaseIdToken = {\n // Set all required fields to decent defaults\n iss: `https://securetoken.google.com/${project}`,\n aud: project,\n iat,\n exp: iat + 3600,\n auth_time: iat,\n sub,\n user_id: sub,\n firebase: {\n sign_in_provider: 'custom',\n identities: {}\n },\n\n // Override with user options\n ...token\n };\n\n // Unsecured JWTs use the empty string as a signature.\n const signature = '';\n return [\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n signature\n ].join('.');\n}\n\ninterface EmulatorStatusMap {\n [name: string]: boolean;\n}\nconst emulatorStatus: EmulatorStatusMap = {};\n\ninterface EmulatorSummary {\n prod: string[];\n emulator: string[];\n}\n\n// Checks whether any products are running on an emulator\nfunction getEmulatorSummary(): EmulatorSummary {\n const summary: EmulatorSummary = {\n prod: [],\n emulator: []\n };\n for (const key of Object.keys(emulatorStatus)) {\n if (emulatorStatus[key]) {\n summary.emulator.push(key);\n } else {\n summary.prod.push(key);\n }\n }\n return summary;\n}\n\nfunction getOrCreateEl(id: string): { created: boolean; element: HTMLElement } {\n let parentDiv = document.getElementById(id);\n let created = false;\n if (!parentDiv) {\n parentDiv = document.createElement('div');\n parentDiv.setAttribute('id', id);\n created = true;\n }\n return { created, element: parentDiv };\n}\n\nlet previouslyDismissed = false;\n/**\n * Updates Emulator Banner. Primarily used for Firebase Studio\n * @param name\n * @param isRunningEmulator\n * @public\n */\nexport function updateEmulatorBanner(\n name: string,\n isRunningEmulator: boolean\n): void {\n if (\n typeof window === 'undefined' ||\n typeof document === 'undefined' ||\n !isCloudWorkstation(window.location.host) ||\n emulatorStatus[name] === isRunningEmulator ||\n emulatorStatus[name] || // If already set to use emulator, can't go back to prod.\n previouslyDismissed\n ) {\n return;\n }\n\n emulatorStatus[name] = isRunningEmulator;\n\n function prefixedId(id: string): string {\n return `__firebase__banner__${id}`;\n }\n const bannerId = '__firebase__banner';\n const summary = getEmulatorSummary();\n const showError = summary.prod.length > 0;\n\n function tearDown(): void {\n const element = document.getElementById(bannerId);\n if (element) {\n element.remove();\n }\n }\n\n function setupBannerStyles(bannerEl: HTMLElement): void {\n bannerEl.style.display = 'flex';\n bannerEl.style.background = '#7faaf0';\n bannerEl.style.position = 'fixed';\n bannerEl.style.bottom = '5px';\n bannerEl.style.left = '5px';\n bannerEl.style.padding = '.5em';\n bannerEl.style.borderRadius = '5px';\n bannerEl.style.alignItems = 'center';\n }\n\n function setupIconStyles(prependIcon: SVGElement, iconId: string): void {\n prependIcon.setAttribute('width', '24');\n prependIcon.setAttribute('id', iconId);\n prependIcon.setAttribute('height', '24');\n prependIcon.setAttribute('viewBox', '0 0 24 24');\n prependIcon.setAttribute('fill', 'none');\n prependIcon.style.marginLeft = '-6px';\n }\n\n function setupCloseBtn(): HTMLSpanElement {\n const closeBtn = document.createElement('span');\n closeBtn.style.cursor = 'pointer';\n closeBtn.style.marginLeft = '16px';\n closeBtn.style.fontSize = '24px';\n closeBtn.innerHTML = ' ×';\n closeBtn.onclick = () => {\n previouslyDismissed = true;\n tearDown();\n };\n return closeBtn;\n }\n\n function setupLinkStyles(\n learnMoreLink: HTMLAnchorElement,\n learnMoreId: string\n ): void {\n learnMoreLink.setAttribute('id', learnMoreId);\n learnMoreLink.innerText = 'Learn more';\n learnMoreLink.href =\n 'https://firebase.google.com/docs/studio/preview-apps#preview-backend';\n learnMoreLink.setAttribute('target', '__blank');\n learnMoreLink.style.paddingLeft = '5px';\n learnMoreLink.style.textDecoration = 'underline';\n }\n\n function setupDom(): void {\n const banner = getOrCreateEl(bannerId);\n const firebaseTextId = prefixedId('text');\n const firebaseText: HTMLSpanElement =\n document.getElementById(firebaseTextId) || document.createElement('span');\n const learnMoreId = prefixedId('learnmore');\n const learnMoreLink: HTMLAnchorElement =\n (document.getElementById(learnMoreId) as HTMLAnchorElement) ||\n document.createElement('a');\n const prependIconId = prefixedId('preprendIcon');\n const prependIcon: SVGElement =\n (document.getElementById(\n prependIconId\n ) as HTMLOrSVGElement as SVGElement) ||\n document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n if (banner.created) {\n // update styles\n const bannerEl = banner.element;\n setupBannerStyles(bannerEl);\n setupLinkStyles(learnMoreLink, learnMoreId);\n const closeBtn = setupCloseBtn();\n setupIconStyles(prependIcon, prependIconId);\n bannerEl.append(prependIcon, firebaseText, learnMoreLink, closeBtn);\n document.body.appendChild(bannerEl);\n }\n\n if (showError) {\n firebaseText.innerText = `Preview backend disconnected.`;\n prependIcon.innerHTML = `\n\n\n\n\n\n\n`;\n } else {\n prependIcon.innerHTML = `\n\n\n\n\n\n\n`;\n firebaseText.innerText = 'Preview backend running in this workspace.';\n }\n firebaseText.setAttribute('id', firebaseTextId);\n }\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', setupDom);\n } else {\n setupDom();\n }\n}\n", "/**\n * @license\n * Copyright 2017 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 * http://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 { CONSTANTS } from './constants';\nimport { getDefaults } from './defaults';\n\n/**\n * Type placeholder for `WorkerGlobalScope` from `webworker`\n */\ndeclare class WorkerGlobalScope {}\n\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nexport function getUA(): string {\n if (\n typeof navigator !== 'undefined' &&\n typeof navigator['userAgent'] === 'string'\n ) {\n return navigator['userAgent'];\n } else {\n return '';\n }\n}\n\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nexport function isMobileCordova(): boolean {\n return (\n typeof window !== 'undefined' &&\n // @ts-ignore Setting up an broadly applicable index signature for Window\n // just to deal with this case would probably be a bad idea.\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n );\n}\n\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n const forceEnvironment = getDefaults()?.forceEnvironment;\n if (forceEnvironment === 'node') {\n return true;\n } else if (forceEnvironment === 'browser') {\n return false;\n }\n\n try {\n return (\n Object.prototype.toString.call(global.process) === '[object process]'\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Detect Browser Environment.\n * Note: This will return true for certain test frameworks that are incompletely\n * mimicking a browser, and should not lead to assuming all browser APIs are\n * available.\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' || isWebWorker();\n}\n\n/**\n * Detect Web Worker context.\n */\nexport function isWebWorker(): boolean {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n typeof self !== 'undefined' &&\n self instanceof WorkerGlobalScope\n );\n}\n\n/**\n * Detect Cloudflare Worker context.\n */\nexport function isCloudflareWorker(): boolean {\n return (\n typeof navigator !== 'undefined' &&\n navigator.userAgent === 'Cloudflare-Workers'\n );\n}\n\n/**\n * Detect browser extensions (Chrome and Firefox at least).\n */\ninterface BrowserRuntime {\n id?: unknown;\n}\ndeclare const chrome: { runtime?: BrowserRuntime };\ndeclare const browser: { runtime?: BrowserRuntime };\nexport function isBrowserExtension(): boolean {\n const runtime =\n typeof chrome === 'object'\n ? chrome.runtime\n : typeof browser === 'object'\n ? browser.runtime\n : undefined;\n return typeof runtime === 'object' && runtime.id !== undefined;\n}\n\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nexport function isReactNative(): boolean {\n return (\n typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n );\n}\n\n/** Detects Electron apps. */\nexport function isElectron(): boolean {\n return getUA().indexOf('Electron/') >= 0;\n}\n\n/** Detects Internet Explorer. */\nexport function isIE(): boolean {\n const ua = getUA();\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n\n/** Detects Universal Windows Platform apps. */\nexport function isUWP(): boolean {\n return getUA().indexOf('MSAppHost/') >= 0;\n}\n\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nexport function isNodeSdk(): boolean {\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n\n/** Returns true if we are running in Safari. */\nexport function isSafari(): boolean {\n return (\n !isNode() &&\n !!navigator.userAgent &&\n navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/** Returns true if we are running in Safari or WebKit */\nexport function isSafariOrWebkit(): boolean {\n return (\n !isNode() &&\n !!navigator.userAgent &&\n (navigator.userAgent.includes('Safari') ||\n navigator.userAgent.includes('WebKit')) &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nexport function isIndexedDBAvailable(): boolean {\n try {\n return typeof indexedDB === 'object';\n } catch (e) {\n return false;\n }\n}\n\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nexport function validateIndexedDBOpenable(): Promise {\n return new Promise((resolve, reject) => {\n try {\n let preExist: boolean = true;\n const DB_CHECK_NAME =\n 'validate-browser-context-for-indexeddb-analytics-module';\n const request = self.indexedDB.open(DB_CHECK_NAME);\n request.onsuccess = () => {\n request.result.close();\n // delete database only when it doesn't pre-exist\n if (!preExist) {\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n }\n resolve(true);\n };\n request.onupgradeneeded = () => {\n preExist = false;\n };\n\n request.onerror = () => {\n reject(request.error?.message || '');\n };\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nexport function areCookiesEnabled(): boolean {\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n return false;\n }\n return true;\n}\n", "/**\n * @license\n * Copyright 2017 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 * http://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 * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // TypeScript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n // which we can now use since we no longer target ES5.\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap\n ) {}\n\n create(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n", "/**\n * @license\n * Copyright 2017 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 * http://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 * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nexport function jsonEval(str: string): unknown {\n return JSON.parse(str);\n}\n\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data JavaScript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nexport function stringify(data: unknown): string {\n return JSON.stringify(data);\n}\n", "/**\n * @license\n * Copyright 2017 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 * http://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 { base64Decode } from './crypt';\nimport { jsonEval } from './json';\n\ninterface Claims {\n [key: string]: {};\n}\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const decode = function (token: string): DecodedToken {\n let header = {},\n claims: Claims = {},\n data = {},\n signature = '';\n\n try {\n const parts = token.split('.');\n header = jsonEval(base64Decode(parts[0]) || '') as object;\n claims = jsonEval(base64Decode(parts[1]) || '') as Claims;\n signature = parts[2];\n data = claims['d'] || {};\n delete claims['d'];\n } catch (e) {}\n\n return {\n header,\n claims,\n data,\n signature\n };\n};\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidTimestamp = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n const now: number = Math.floor(new Date().getTime() / 1000);\n let validSince: number = 0,\n validUntil: number = 0;\n\n if (typeof claims === 'object') {\n if (claims.hasOwnProperty('nbf')) {\n validSince = claims['nbf'] as number;\n } else if (claims.hasOwnProperty('iat')) {\n validSince = claims['iat'] as number;\n }\n\n if (claims.hasOwnProperty('exp')) {\n validUntil = claims['exp'] as number;\n } else {\n // token will expire after 24h by default\n validUntil = validSince + 86400;\n }\n }\n\n return (\n !!now &&\n !!validSince &&\n !!validUntil &&\n now >= validSince &&\n now <= validUntil\n );\n};\n\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const issuedAtTime = function (token: string): number | null {\n const claims: Claims = decode(token).claims;\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n return claims['iat'] as number;\n }\n return null;\n};\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidFormat = function (token: string): boolean {\n const decoded = decode(token),\n claims = decoded.claims;\n\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\n};\n\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isAdmin = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n return typeof claims === 'object' && claims['admin'] === true;\n};\n", "/**\n * @license\n * Copyright 2017 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 * http://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\nexport function contains(obj: T, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function safeGet(\n obj: T,\n key: K\n): T[K] | undefined {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return obj[key];\n } else {\n return undefined;\n }\n}\n\nexport function isEmpty(obj: object): obj is {} {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function map(\n obj: { [key in K]: V },\n fn: (value: V, key: K, obj: { [key in K]: V }) => U,\n contextObj?: unknown\n): { [key in K]: U } {\n const res: Partial<{ [key in K]: U }> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n res[key] = fn.call(contextObj, obj[key], key, obj);\n }\n }\n return res as { [key in K]: U };\n}\n\n/**\n * Deep equal two objects. Support Arrays and Objects.\n */\nexport function deepEqual(a: object, b: object): boolean {\n if (a === b) {\n return true;\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n for (const k of aKeys) {\n if (!bKeys.includes(k)) {\n return false;\n }\n\n const aProp = (a as Record)[k];\n const bProp = (b as Record)[k];\n if (isObject(aProp) && isObject(bProp)) {\n if (!deepEqual(aProp, bProp)) {\n return false;\n }\n } else if (aProp !== bProp) {\n return false;\n }\n }\n\n for (const k of bKeys) {\n if (!aKeys.includes(k)) {\n return false;\n }\n }\n return true;\n}\n\nfunction isObject(thing: unknown): thing is object {\n return thing !== null && typeof thing === 'object';\n}\n", "/**\n * @license\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 * http://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 { Deferred } from './deferred';\n\n/**\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\n * @internal\n */\nexport function promiseWithTimeout(\n promise: Promise,\n timeInMS = 2000\n): Promise {\n const deferredPromise = new Deferred();\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\n promise.then(deferredPromise.resolve, deferredPromise.reject);\n return deferredPromise.promise;\n}\n", "/**\n * @license\n * Copyright 2017 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 * http://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 * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\n * params object (e.g. {arg: 'val', arg2: 'val2'})\n * Note: You must prepend it with ? when adding it to a URL.\n */\nexport function querystring(querystringParams: {\n [key: string]: string | number;\n}): string {\n const params = [];\n for (const [key, value] of Object.entries(querystringParams)) {\n if (Array.isArray(value)) {\n value.forEach(arrayVal => {\n params.push(\n encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)\n );\n });\n } else {\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n }\n }\n return params.length ? '&' + params.join('&') : '';\n}\n\n/**\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\n * (e.g. {arg: 'val', arg2: 'val2'})\n */\nexport function querystringDecode(querystring: string): Record {\n const obj: Record = {};\n const tokens = querystring.replace(/^\\?/, '').split('&');\n\n tokens.forEach(token => {\n if (token) {\n const [key, value] = token.split('=');\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\n }\n });\n return obj;\n}\n\n/**\n * Extract the query string part of a URL, including the leading question mark (if present).\n */\nexport function extractQuerystring(url: string): string {\n const queryStart = url.indexOf('?');\n if (!queryStart) {\n return '';\n }\n const fragmentStart = url.indexOf('#', queryStart);\n return url.substring(\n queryStart,\n fragmentStart > 0 ? fragmentStart : undefined\n );\n}\n", "/**\n * @license\n * Copyright 2017 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 * http://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 * @fileoverview SHA-1 cryptographic hash.\n * Variable names follow the notation in FIPS PUB 180-3:\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\n *\n * Usage:\n * var sha1 = new sha1();\n * sha1.update(bytes);\n * var hash = sha1.digest();\n *\n * Performance:\n * Chrome 23: ~400 Mbit/s\n * Firefox 16: ~250 Mbit/s\n *\n */\n\n/**\n * SHA-1 cryptographic hash constructor.\n *\n * The properties declared here are discussed in the above algorithm document.\n * @constructor\n * @final\n * @struct\n */\nexport class Sha1 {\n /**\n * Holds the previous values of accumulated variables a-e in the compress_\n * function.\n * @private\n */\n private chain_: number[] = [];\n\n /**\n * A buffer holding the partially computed hash result.\n * @private\n */\n private buf_: number[] = [];\n\n /**\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\n * as the message schedule in the docs.\n * @private\n */\n private W_: number[] = [];\n\n /**\n * Contains data needed to pad messages less than 64 bytes.\n * @private\n */\n private pad_: number[] = [];\n\n /**\n * @private {number}\n */\n private inbuf_: number = 0;\n\n /**\n * @private {number}\n */\n private total_: number = 0;\n\n blockSize: number;\n\n constructor() {\n this.blockSize = 512 / 8;\n\n this.pad_[0] = 128;\n for (let i = 1; i < this.blockSize; ++i) {\n this.pad_[i] = 0;\n }\n\n this.reset();\n }\n\n reset(): void {\n this.chain_[0] = 0x67452301;\n this.chain_[1] = 0xefcdab89;\n this.chain_[2] = 0x98badcfe;\n this.chain_[3] = 0x10325476;\n this.chain_[4] = 0xc3d2e1f0;\n\n this.inbuf_ = 0;\n this.total_ = 0;\n }\n\n /**\n * Internal compress helper function.\n * @param buf Block to compress.\n * @param offset Offset of the block in the buffer.\n * @private\n */\n compress_(buf: number[] | Uint8Array | string, offset?: number): void {\n if (!offset) {\n offset = 0;\n }\n\n const W = this.W_;\n\n // get 16 big endian words\n if (typeof buf === 'string') {\n for (let i = 0; i < 16; i++) {\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\n // have a bug that turns the post-increment ++ operator into pre-increment\n // during JIT compilation. We have code that depends heavily on SHA-1 for\n // correctness and which is affected by this bug, so I've removed all uses\n // of post-increment ++ in which the result value is used. We can revert\n // this change once the Safari bug\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\n // most clients have been updated.\n W[i] =\n (buf.charCodeAt(offset) << 24) |\n (buf.charCodeAt(offset + 1) << 16) |\n (buf.charCodeAt(offset + 2) << 8) |\n buf.charCodeAt(offset + 3);\n offset += 4;\n }\n } else {\n for (let i = 0; i < 16; i++) {\n W[i] =\n (buf[offset] << 24) |\n (buf[offset + 1] << 16) |\n (buf[offset + 2] << 8) |\n buf[offset + 3];\n offset += 4;\n }\n }\n\n // expand to 80 words\n for (let i = 16; i < 80; i++) {\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\n }\n\n let a = this.chain_[0];\n let b = this.chain_[1];\n let c = this.chain_[2];\n let d = this.chain_[3];\n let e = this.chain_[4];\n let f, k;\n\n // TODO(user): Try to unroll this loop to speed up the computation.\n for (let i = 0; i < 80; i++) {\n if (i < 40) {\n if (i < 20) {\n f = d ^ (b & (c ^ d));\n k = 0x5a827999;\n } else {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n }\n } else {\n if (i < 60) {\n f = (b & c) | (d & (b | c));\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n }\n\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\n e = d;\n d = c;\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\n b = a;\n a = t;\n }\n\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\n }\n\n update(bytes?: number[] | Uint8Array | string, length?: number): void {\n // TODO(johnlenz): tighten the function signature and remove this check\n if (bytes == null) {\n return;\n }\n\n if (length === undefined) {\n length = bytes.length;\n }\n\n const lengthMinusBlock = length - this.blockSize;\n let n = 0;\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\n const buf = this.buf_;\n let inbuf = this.inbuf_;\n\n // The outer while loop should execute at most twice.\n while (n < length) {\n // When we have no data in the block to top up, we can directly process the\n // input buffer (assuming it contains sufficient data). This gives ~25%\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\n // the data is provided in large chunks (or in multiples of 64 bytes).\n if (inbuf === 0) {\n while (n <= lengthMinusBlock) {\n this.compress_(bytes, n);\n n += this.blockSize;\n }\n }\n\n if (typeof bytes === 'string') {\n while (n < length) {\n buf[inbuf] = bytes.charCodeAt(n);\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n } else {\n while (n < length) {\n buf[inbuf] = bytes[n];\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n }\n }\n\n this.inbuf_ = inbuf;\n this.total_ += length;\n }\n\n /** @override */\n digest(): number[] {\n const digest: number[] = [];\n let totalBits = this.total_ * 8;\n\n // Add pad 0x80 0x00*.\n if (this.inbuf_ < 56) {\n this.update(this.pad_, 56 - this.inbuf_);\n } else {\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\n }\n\n // Add # bits.\n for (let i = this.blockSize - 1; i >= 56; i--) {\n this.buf_[i] = totalBits & 255;\n totalBits /= 256; // Don't use bit-shifting here!\n }\n\n this.compress_(this.buf_);\n\n let n = 0;\n for (let i = 0; i < 5; i++) {\n for (let j = 24; j >= 0; j -= 8) {\n digest[n] = (this.chain_[i] >> j) & 255;\n ++n;\n }\n }\n return digest;\n }\n}\n", "/**\n * @license\n * Copyright 2017 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 * http://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 */\nexport type NextFn = (value: T) => void;\nexport type ErrorFn = (error: Error) => void;\nexport type CompleteFn = () => void;\n\nexport interface Observer {\n // Called once for each value in a stream of values.\n next: NextFn;\n\n // A stream terminates by a single call to EITHER error() or complete().\n error: ErrorFn;\n\n // No events will be sent to next() once complete() is called.\n complete: CompleteFn;\n}\n\nexport type PartialObserver = Partial>;\n\n// TODO: Support also Unsubscribe.unsubscribe?\nexport type Unsubscribe = () => void;\n\n/**\n * The Subscribe interface has two forms - passing the inline function\n * callbacks, or a object interface with callback properties.\n */\nexport interface Subscribe {\n (next?: NextFn, error?: ErrorFn, complete?: CompleteFn): Unsubscribe;\n (observer: PartialObserver): Unsubscribe;\n}\n\nexport interface Observable {\n // Subscribe method\n subscribe: Subscribe;\n}\n\nexport type Executor = (observer: Observer) => void;\n\n/**\n * Helper to make a Subscribe function (just like Promise helps make a\n * Thenable).\n *\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\nexport function createSubscribe(\n executor: Executor,\n onNoObservers?: Executor\n): Subscribe {\n const proxy = new ObserverProxy(executor, onNoObservers);\n return proxy.subscribe.bind(proxy);\n}\n\n/**\n * Implement fan-out for any number of Observers attached via a subscribe\n * function.\n */\nclass ObserverProxy implements Observer {\n private observers: Array> | undefined = [];\n private unsubscribes: Unsubscribe[] = [];\n private onNoObservers: Executor | undefined;\n private observerCount = 0;\n // Micro-task scheduling by calling task.then().\n private task = Promise.resolve();\n private finalized = false;\n private finalError?: Error;\n\n /**\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\n constructor(executor: Executor, onNoObservers?: Executor) {\n this.onNoObservers = onNoObservers;\n // Call the executor asynchronously so subscribers that are called\n // synchronously after the creation of the subscribe function\n // can still receive the very first value generated in the executor.\n this.task\n .then(() => {\n executor(this);\n })\n .catch(e => {\n this.error(e);\n });\n }\n\n next(value: T): void {\n this.forEachObserver((observer: Observer) => {\n observer.next(value);\n });\n }\n\n error(error: Error): void {\n this.forEachObserver((observer: Observer) => {\n observer.error(error);\n });\n this.close(error);\n }\n\n complete(): void {\n this.forEachObserver((observer: Observer) => {\n observer.complete();\n });\n this.close();\n }\n\n /**\n * Subscribe function that can be used to add an Observer to the fan-out list.\n *\n * - We require that no event is sent to a subscriber synchronously to their\n * call to subscribe().\n */\n subscribe(\n nextOrObserver?: NextFn | PartialObserver,\n error?: ErrorFn,\n complete?: CompleteFn\n ): Unsubscribe {\n let observer: Observer;\n\n if (\n nextOrObserver === undefined &&\n error === undefined &&\n complete === undefined\n ) {\n throw new Error('Missing Observer.');\n }\n\n // Assemble an Observer object when passed as callback functions.\n if (\n implementsAnyMethods(nextOrObserver as { [key: string]: unknown }, [\n 'next',\n 'error',\n 'complete'\n ])\n ) {\n observer = nextOrObserver as Observer;\n } else {\n observer = {\n next: nextOrObserver as NextFn,\n error,\n complete\n } as Observer;\n }\n\n if (observer.next === undefined) {\n observer.next = noop as NextFn;\n }\n if (observer.error === undefined) {\n observer.error = noop as ErrorFn;\n }\n if (observer.complete === undefined) {\n observer.complete = noop as CompleteFn;\n }\n\n const unsub = this.unsubscribeOne.bind(this, this.observers!.length);\n\n // Attempt to subscribe to a terminated Observable - we\n // just respond to the Observer with the final error or complete\n // event.\n if (this.finalized) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n try {\n if (this.finalError) {\n observer.error(this.finalError);\n } else {\n observer.complete();\n }\n } catch (e) {\n // nothing\n }\n return;\n });\n }\n\n this.observers!.push(observer as Observer);\n\n return unsub;\n }\n\n // Unsubscribe is synchronous - we guarantee that no events are sent to\n // any unsubscribed Observer.\n private unsubscribeOne(i: number): void {\n if (this.observers === undefined || this.observers[i] === undefined) {\n return;\n }\n\n delete this.observers[i];\n\n this.observerCount -= 1;\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\n this.onNoObservers(this);\n }\n }\n\n private forEachObserver(fn: (observer: Observer) => void): void {\n if (this.finalized) {\n // Already closed by previous event....just eat the additional values.\n return;\n }\n\n // Since sendOne calls asynchronously - there is no chance that\n // this.observers will become undefined.\n for (let i = 0; i < this.observers!.length; i++) {\n this.sendOne(i, fn);\n }\n }\n\n // Call the Observer via one of it's callback function. We are careful to\n // confirm that the observe has not been unsubscribed since this asynchronous\n // function had been queued.\n private sendOne(i: number, fn: (observer: Observer) => void): void {\n // Execute the callback asynchronously\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n if (this.observers !== undefined && this.observers[i] !== undefined) {\n try {\n fn(this.observers[i]);\n } catch (e) {\n // Ignore exceptions raised in Observers or missing methods of an\n // Observer.\n // Log error to console. b/31404806\n if (typeof console !== 'undefined' && console.error) {\n console.error(e);\n }\n }\n }\n });\n }\n\n private close(err?: Error): void {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n if (err !== undefined) {\n this.finalError = err;\n }\n // Proxy is no longer needed - garbage collect references\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n this.observers = undefined;\n this.onNoObservers = undefined;\n });\n }\n}\n\n/** Turn synchronous function into one called asynchronously. */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function async(fn: Function, onError?: ErrorFn): Function {\n return (...args: unknown[]) => {\n Promise.resolve(true)\n .then(() => {\n fn(...args);\n })\n .catch((error: Error) => {\n if (onError) {\n onError(error);\n }\n });\n };\n}\n\n/**\n * Return true if the object passed in implements any of the named methods.\n */\nfunction implementsAnyMethods(\n obj: { [key: string]: unknown },\n methods: string[]\n): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n for (const method of methods) {\n if (method in obj && typeof obj[method] === 'function') {\n return true;\n }\n }\n\n return false;\n}\n\nfunction noop(): void {\n // do nothing\n}\n", "/**\n * @license\n * Copyright 2017 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 * http://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 * Check to make sure the appropriate number of arguments are provided for a public function.\n * Throws an error if it fails.\n *\n * @param fnName The function name\n * @param minCount The minimum number of arguments to allow for the function call\n * @param maxCount The maximum number of argument to allow for the function call\n * @param argCount The actual number of arguments provided.\n */\nexport const validateArgCount = function (\n fnName: string,\n minCount: number,\n maxCount: number,\n argCount: number\n): void {\n let argError;\n if (argCount < minCount) {\n argError = 'at least ' + minCount;\n } else if (argCount > maxCount) {\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\n }\n if (argError) {\n const error =\n fnName +\n ' failed: Was called with ' +\n argCount +\n (argCount === 1 ? ' argument.' : ' arguments.') +\n ' Expects ' +\n argError +\n '.';\n throw new Error(error);\n }\n};\n\n/**\n * Generates a string to prefix an error message about failed argument validation\n *\n * @param fnName The function name\n * @param argName The name of the argument\n * @return The prefix to add to the error thrown for validation.\n */\nexport function errorPrefix(fnName: string, argName: string): string {\n return `${fnName} failed: ${argName} argument `;\n}\n\n/**\n * @param fnName\n * @param argumentNumber\n * @param namespace\n * @param optional\n */\nexport function validateNamespace(\n fnName: string,\n namespace: string,\n optional: boolean\n): void {\n if (optional && !namespace) {\n return;\n }\n if (typeof namespace !== 'string') {\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\n throw new Error(\n errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.'\n );\n }\n}\n\nexport function validateCallback(\n fnName: string,\n argumentName: string,\n // eslint-disable-next-line @typescript-eslint/ban-types\n callback: Function,\n optional: boolean\n): void {\n if (optional && !callback) {\n return;\n }\n if (typeof callback !== 'function') {\n throw new Error(\n errorPrefix(fnName, argumentName) + 'must be a valid function.'\n );\n }\n}\n\nexport function validateContextObject(\n fnName: string,\n argumentName: string,\n context: unknown,\n optional: boolean\n): void {\n if (optional && !context) {\n return;\n }\n if (typeof context !== 'object' || context === null) {\n throw new Error(\n errorPrefix(fnName, argumentName) + 'must be a valid context object.'\n );\n }\n}\n", "/**\n * @license\n * Copyright 2017 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 * http://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 { assert } from './assert';\n\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\n// so it's been modified.\n\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\n// use 2 characters in JavaScript. All 4-byte UTF-8 characters begin with a first\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\n// pair).\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\n\n/**\n * @param {string} str\n * @return {Array}\n */\nexport const stringToByteArray = function (str: string): number[] {\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n\n // Is this the lead surrogate in a surrogate pair?\n if (c >= 0xd800 && c <= 0xdbff) {\n const high = c - 0xd800; // the high 10 bits.\n i++;\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\n c = 0x10000 + (high << 10) + low;\n }\n\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (c < 65536) {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Calculate length without actually converting; useful for doing cheaper validation.\n * @param {string} str\n * @return {number}\n */\nexport const stringLength = function (str: string): number {\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n const c = str.charCodeAt(i);\n if (c < 128) {\n p++;\n } else if (c < 2048) {\n p += 2;\n } else if (c >= 0xd800 && c <= 0xdbff) {\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\n p += 4;\n i++; // skip trail surrogate.\n } else {\n p += 3;\n }\n }\n return p;\n};\n", "/**\n * @license\n * Copyright 2019 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 * http://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 * The amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * The maximum milliseconds to increase to.\n *\n *

Visible for testing\n */\nexport const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n *

Visible for testing\n */\nexport const RANDOM_FACTOR = 0.5;\n\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nexport function calculateBackoffMillis(\n backoffCount: number,\n intervalMillis: number = DEFAULT_INTERVAL_MILLIS,\n backoffFactor: number = DEFAULT_BACKOFF_FACTOR\n): number {\n // Calculates an exponentially increasing value.\n // Deviation: calculates value from count and a constant interval, so we only need to save value\n // and count to restore state.\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\n\n // A random \"fuzz\" to avoid waves of retries.\n // Deviation: randomFactor is required.\n const randomWait = Math.round(\n // A fraction of the backoff value to add/subtract.\n // Deviation: changes multiplication order to improve readability.\n RANDOM_FACTOR *\n currBaseValue *\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n // if we add or subtract.\n (Math.random() - 0.5) *\n 2\n );\n\n // Limits backoff to max to avoid effectively permanent backoff.\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\n}\n", "/**\n * @license\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 * http://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 * Provide English ordinal letters after a number\n */\nexport function ordinal(i: number): string {\n if (!Number.isFinite(i)) {\n return `${i}`;\n }\n return i + indicator(i);\n}\n\nfunction indicator(i: number): string {\n i = Math.abs(i);\n const cent = i % 100;\n if (cent >= 10 && cent <= 20) {\n return 'th';\n }\n const dec = i % 10;\n if (dec === 1) {\n return 'st';\n }\n if (dec === 2) {\n return 'nd';\n }\n if (dec === 3) {\n return 'rd';\n }\n return 'th';\n}\n", "/**\n * @license\n * Copyright 2021 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 * http://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\nexport interface Compat {\n _delegate: T;\n}\n\nexport function getModularInstance(\n service: Compat | ExpService\n): ExpService {\n if (service && (service as Compat)._delegate) {\n return (service as Compat)._delegate;\n } else {\n return service as ExpService;\n }\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n onInstanceCreated: onInstanceCreatedCallback | null = null;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n\n setInstanceCreatedCallback(callback: onInstanceCreatedCallback): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { Deferred } from '@firebase/util';\nimport { ComponentContainer } from './component_container';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport {\n InitializeOptions,\n InstantiationMode,\n Name,\n NameServiceMapping,\n OnInitCallBack\n} from './types';\nimport { Component } from './component';\n\n/**\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\n * NameServiceMapping[T] is an alias for the type of the instance\n */\nexport class Provider {\n private component: Component | null = null;\n private readonly instances: Map = new Map();\n private readonly instancesDeferred: Map<\n string,\n Deferred\n > = new Map();\n private readonly instancesOptions: Map> =\n new Map();\n private onInitCallbacks: Map>> = new Map();\n\n constructor(\n private readonly name: T,\n private readonly container: ComponentContainer\n ) {}\n\n /**\n * @param identifier A provider can provide multiple instances of a service\n * if this.component.multipleInstances is true.\n */\n get(identifier?: string): Promise {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\n const deferred = new Deferred();\n this.instancesDeferred.set(normalizedIdentifier, deferred);\n\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n // initialize the service if it can be auto-initialized\n try {\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n if (instance) {\n deferred.resolve(instance);\n }\n } catch (e) {\n // when the instance factory throws an exception during get(), it should not cause\n // a fatal error. We just return the unresolved promise in this case.\n }\n }\n }\n\n return this.instancesDeferred.get(normalizedIdentifier)!.promise;\n }\n\n /**\n *\n * @param options.identifier A provider can provide multiple instances of a service\n * if this.component.multipleInstances is true.\n * @param options.optional If optional is false or not provided, the method throws an error when\n * the service is not immediately available.\n * If optional is true, the method returns null if the service is not immediately available.\n */\n getImmediate(options: {\n identifier?: string;\n optional: true;\n }): NameServiceMapping[T] | null;\n getImmediate(options?: {\n identifier?: string;\n optional?: false;\n }): NameServiceMapping[T];\n getImmediate(options?: {\n identifier?: string;\n optional?: boolean;\n }): NameServiceMapping[T] | null {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n options?.identifier\n );\n const optional = options?.optional ?? false;\n\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n try {\n return this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n } catch (e) {\n if (optional) {\n return null;\n } else {\n throw e;\n }\n }\n } else {\n // In case a component is not initialized and should/cannot be auto-initialized at the moment, return null if the optional flag is set, or throw\n if (optional) {\n return null;\n } else {\n throw Error(`Service ${this.name} is not available`);\n }\n }\n }\n\n getComponent(): Component | null {\n return this.component;\n }\n\n setComponent(component: Component): void {\n if (component.name !== this.name) {\n throw Error(\n `Mismatching Component ${component.name} for Provider ${this.name}.`\n );\n }\n\n if (this.component) {\n throw Error(`Component for ${this.name} has already been provided`);\n }\n\n this.component = component;\n\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\n if (!this.shouldAutoInitialize()) {\n return;\n }\n\n // if the service is eager, initialize the default instance\n if (isComponentEager(component)) {\n try {\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\n } catch (e) {\n // when the instance factory for an eager Component throws an exception during the eager\n // initialization, it should not cause a fatal error.\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\n // a fatal error in this case?\n }\n }\n\n // Create service instances for the pending promises and resolve them\n // NOTE: if this.multipleInstances is false, only the default instance will be created\n // and all promises with resolve with it regardless of the identifier.\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedIdentifier =\n this.normalizeInstanceIdentifier(instanceIdentifier);\n\n try {\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n })!;\n instanceDeferred.resolve(instance);\n } catch (e) {\n // when the instance factory throws an exception, it should not cause\n // a fatal error. We just leave the promise unresolved.\n }\n }\n }\n\n clearInstance(identifier: string = DEFAULT_ENTRY_NAME): void {\n this.instancesDeferred.delete(identifier);\n this.instancesOptions.delete(identifier);\n this.instances.delete(identifier);\n }\n\n // app.delete() will call this method on every provider to delete the services\n // TODO: should we mark the provider as deleted?\n async delete(): Promise {\n const services = Array.from(this.instances.values());\n\n await Promise.all([\n ...services\n .filter(service => 'INTERNAL' in service) // legacy services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any).INTERNAL!.delete()),\n ...services\n .filter(service => '_delete' in service) // modularized services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any)._delete())\n ]);\n }\n\n isComponentSet(): boolean {\n return this.component != null;\n }\n\n isInitialized(identifier: string = DEFAULT_ENTRY_NAME): boolean {\n return this.instances.has(identifier);\n }\n\n getOptions(identifier: string = DEFAULT_ENTRY_NAME): Record {\n return this.instancesOptions.get(identifier) || {};\n }\n\n initialize(opts: InitializeOptions = {}): NameServiceMapping[T] {\n const { options = {} } = opts;\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n opts.instanceIdentifier\n );\n if (this.isInitialized(normalizedIdentifier)) {\n throw Error(\n `${this.name}(${normalizedIdentifier}) has already been initialized`\n );\n }\n\n if (!this.isComponentSet()) {\n throw Error(`Component ${this.name} has not been registered yet`);\n }\n\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier,\n options\n })!;\n\n // resolve any pending promise waiting for the service instance\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedDeferredIdentifier =\n this.normalizeInstanceIdentifier(instanceIdentifier);\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\n instanceDeferred.resolve(instance);\n }\n }\n\n return instance;\n }\n\n /**\n *\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\n *\n * @param identifier An optional instance identifier\n * @returns a function to unregister the callback\n */\n onInit(callback: OnInitCallBack, identifier?: string): () => void {\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n const existingCallbacks =\n this.onInitCallbacks.get(normalizedIdentifier) ??\n new Set>();\n existingCallbacks.add(callback);\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\n\n const existingInstance = this.instances.get(normalizedIdentifier);\n if (existingInstance) {\n callback(existingInstance, normalizedIdentifier);\n }\n\n return () => {\n existingCallbacks.delete(callback);\n };\n }\n\n /**\n * Invoke onInit callbacks synchronously\n * @param instance the service instance`\n */\n private invokeOnInitCallbacks(\n instance: NameServiceMapping[T],\n identifier: string\n ): void {\n const callbacks = this.onInitCallbacks.get(identifier);\n if (!callbacks) {\n return;\n }\n for (const callback of callbacks) {\n try {\n callback(instance, identifier);\n } catch {\n // ignore errors in the onInit callback\n }\n }\n }\n\n private getOrInitializeService({\n instanceIdentifier,\n options = {}\n }: {\n instanceIdentifier: string;\n options?: Record;\n }): NameServiceMapping[T] | null {\n let instance = this.instances.get(instanceIdentifier);\n if (!instance && this.component) {\n instance = this.component.instanceFactory(this.container, {\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\n options\n });\n this.instances.set(instanceIdentifier, instance!);\n this.instancesOptions.set(instanceIdentifier, options);\n\n /**\n * Invoke onInit listeners.\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\n * while onInit listeners are registered by consumers of the provider.\n */\n this.invokeOnInitCallbacks(instance!, instanceIdentifier);\n\n /**\n * Order is important\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\n * makes `isInitialized()` return true.\n */\n if (this.component.onInstanceCreated) {\n try {\n this.component.onInstanceCreated(\n this.container,\n instanceIdentifier,\n instance!\n );\n } catch {\n // ignore errors in the onInstanceCreatedCallback\n }\n }\n }\n\n return instance || null;\n }\n\n private normalizeInstanceIdentifier(\n identifier: string = DEFAULT_ENTRY_NAME\n ): string {\n if (this.component) {\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\n } else {\n return identifier; // assume multiple instances are supported before the component is provided.\n }\n }\n\n private shouldAutoInitialize(): boolean {\n return (\n !!this.component &&\n this.component.instantiationMode !== InstantiationMode.EXPLICIT\n );\n }\n}\n\n// undefined should be passed to the service factory for the default instance\nfunction normalizeIdentifierForFactory(identifier: string): string | undefined {\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\n}\n\nfunction isComponentEager(component: Component): boolean {\n return component.instantiationMode === InstantiationMode.EAGER;\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { Provider } from './provider';\nimport { Component } from './component';\nimport { Name } from './types';\n\n/**\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\n */\nexport class ComponentContainer {\n private readonly providers = new Map>();\n\n constructor(private readonly name: string) {}\n\n /**\n *\n * @param component Component being added\n * @param overwrite When a component with the same name has already been registered,\n * if overwrite is true: overwrite the existing component with the new component and create a new\n * provider with the new component. It can be useful in tests where you want to use different mocks\n * for different tests.\n * if overwrite is false: throw an exception\n */\n addComponent(component: Component): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n throw new Error(\n `Component ${component.name} has already been registered with ${this.name}`\n );\n }\n\n provider.setComponent(component);\n }\n\n addOrOverwriteComponent(component: Component): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n // delete the existing provider from the container, so we can register the new component\n this.providers.delete(component.name);\n }\n\n this.addComponent(component);\n }\n\n /**\n * getProvider provides a type safe interface where it can only be called with a field name\n * present in NameServiceMapping interface.\n *\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\n * themselves.\n */\n getProvider(name: T): Provider {\n if (this.providers.has(name)) {\n return this.providers.get(name) as unknown as Provider;\n }\n\n // create a Provider for a service that hasn't registered with Firebase\n const provider = new Provider(name, this);\n this.providers.set(name, provider as unknown as Provider);\n\n return provider as Provider;\n }\n\n getProviders(): Array> {\n return Array.from(this.providers.values());\n }\n}\n", "/**\n * @license\n * Copyright 2017 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 * http://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\nexport type LogLevelString =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val: LogLevel | LogLevelString): void {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n", "const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n", "import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n", "/**\n * @license\n * Copyright 2019 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 * http://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 {\n ComponentContainer,\n ComponentType,\n Provider,\n Name\n} from '@firebase/component';\nimport { PlatformLoggerService, VersionService } from './types';\n\nexport class PlatformLoggerServiceImpl implements PlatformLoggerService {\n constructor(private readonly container: ComponentContainer) {}\n // In initial implementation, this will be called by installations on\n // auth token refresh, and installations will send this string.\n getPlatformInfoString(): string {\n const providers = this.container.getProviders();\n // Loop through providers and get library/version pairs from any that are\n // version components.\n return providers\n .map(provider => {\n if (isVersionServiceProvider(provider)) {\n const service = provider.getImmediate() as VersionService;\n return `${service.library}/${service.version}`;\n } else {\n return null;\n }\n })\n .filter(logString => logString)\n .join(' ');\n }\n}\n/**\n *\n * @param provider check if this provider provides a VersionService\n *\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\n * provides VersionService. The provider is not necessarily a 'app-version'\n * provider.\n */\nfunction isVersionServiceProvider(provider: Provider): boolean {\n const component = provider.getComponent();\n return component?.type === ComponentType.VERSION;\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app');\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { name as appName } from '../package.json';\nimport { name as appCompatName } from '../../app-compat/package.json';\nimport { name as analyticsCompatName } from '../../../packages/analytics-compat/package.json';\nimport { name as analyticsName } from '../../../packages/analytics/package.json';\nimport { name as appCheckCompatName } from '../../../packages/app-check-compat/package.json';\nimport { name as appCheckName } from '../../../packages/app-check/package.json';\nimport { name as authName } from '../../../packages/auth/package.json';\nimport { name as authCompatName } from '../../../packages/auth-compat/package.json';\nimport { name as databaseName } from '../../../packages/database/package.json';\nimport { name as dataconnectName } from '../../../packages/data-connect/package.json';\nimport { name as databaseCompatName } from '../../../packages/database-compat/package.json';\nimport { name as functionsName } from '../../../packages/functions/package.json';\nimport { name as functionsCompatName } from '../../../packages/functions-compat/package.json';\nimport { name as installationsName } from '../../../packages/installations/package.json';\nimport { name as installationsCompatName } from '../../../packages/installations-compat/package.json';\nimport { name as messagingName } from '../../../packages/messaging/package.json';\nimport { name as messagingCompatName } from '../../../packages/messaging-compat/package.json';\nimport { name as performanceName } from '../../../packages/performance/package.json';\nimport { name as performanceCompatName } from '../../../packages/performance-compat/package.json';\nimport { name as remoteConfigName } from '../../../packages/remote-config/package.json';\nimport { name as remoteConfigCompatName } from '../../../packages/remote-config-compat/package.json';\nimport { name as storageName } from '../../../packages/storage/package.json';\nimport { name as storageCompatName } from '../../../packages/storage-compat/package.json';\nimport { name as firestoreName } from '../../../packages/firestore/package.json';\nimport { name as aiName } from '../../../packages/ai/package.json';\nimport { name as firestoreCompatName } from '../../../packages/firestore-compat/package.json';\nimport { name as packageName } from '../../../packages/firebase/package.json';\n\n/**\n * The default app name\n *\n * @internal\n */\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\nexport const PLATFORM_LOG_STRING = {\n [appName]: 'fire-core',\n [appCompatName]: 'fire-core-compat',\n [analyticsName]: 'fire-analytics',\n [analyticsCompatName]: 'fire-analytics-compat',\n [appCheckName]: 'fire-app-check',\n [appCheckCompatName]: 'fire-app-check-compat',\n [authName]: 'fire-auth',\n [authCompatName]: 'fire-auth-compat',\n [databaseName]: 'fire-rtdb',\n [dataconnectName]: 'fire-data-connect',\n [databaseCompatName]: 'fire-rtdb-compat',\n [functionsName]: 'fire-fn',\n [functionsCompatName]: 'fire-fn-compat',\n [installationsName]: 'fire-iid',\n [installationsCompatName]: 'fire-iid-compat',\n [messagingName]: 'fire-fcm',\n [messagingCompatName]: 'fire-fcm-compat',\n [performanceName]: 'fire-perf',\n [performanceCompatName]: 'fire-perf-compat',\n [remoteConfigName]: 'fire-rc',\n [remoteConfigCompatName]: 'fire-rc-compat',\n [storageName]: 'fire-gcs',\n [storageCompatName]: 'fire-gcs-compat',\n [firestoreName]: 'fire-fst',\n [firestoreCompatName]: 'fire-fst-compat',\n [aiName]: 'fire-vertex',\n 'fire-js': 'fire-js', // Platform identifier for JS SDK.\n [packageName]: 'fire-js-all'\n} as const;\n", "/**\n * @license\n * Copyright 2019 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 * http://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 {\n FirebaseApp,\n FirebaseAppSettings,\n FirebaseServerAppSettings,\n FirebaseOptions,\n FirebaseServerApp\n} from './public-types';\nimport { Component, Provider, Name } from '@firebase/component';\nimport { logger } from './logger';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { FirebaseServerAppImpl } from './firebaseServerApp';\n\n/**\n * @internal\n */\nexport const _apps = new Map();\n\n/**\n * @internal\n */\nexport const _serverApps = new Map();\n\n/**\n * Registered components.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const _components = new Map>();\n\n/**\n * @param component - the component being added to this app's container\n *\n * @internal\n */\nexport function _addComponent(\n app: FirebaseApp,\n component: Component\n): void {\n try {\n (app as FirebaseAppImpl).container.addComponent(component);\n } catch (e) {\n logger.debug(\n `Component ${component.name} failed to register with FirebaseApp ${app.name}`,\n e\n );\n }\n}\n\n/**\n *\n * @internal\n */\nexport function _addOrOverwriteComponent(\n app: FirebaseApp,\n component: Component\n): void {\n (app as FirebaseAppImpl).container.addOrOverwriteComponent(component);\n}\n\n/**\n *\n * @param component - the component to register\n * @returns whether or not the component is registered successfully\n *\n * @internal\n */\nexport function _registerComponent(\n component: Component\n): boolean {\n const componentName = component.name;\n if (_components.has(componentName)) {\n logger.debug(\n `There were multiple attempts to register component ${componentName}.`\n );\n\n return false;\n }\n\n _components.set(componentName, component);\n\n // add the component to existing app instances\n for (const app of _apps.values()) {\n _addComponent(app as FirebaseAppImpl, component);\n }\n\n for (const serverApp of _serverApps.values()) {\n _addComponent(serverApp as FirebaseServerAppImpl, component);\n }\n\n return true;\n}\n\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n *\n * @returns the provider for the service with the matching name\n *\n * @internal\n */\nexport function _getProvider(\n app: FirebaseApp,\n name: T\n): Provider {\n const heartbeatController = (app as FirebaseAppImpl).container\n .getProvider('heartbeat')\n .getImmediate({ optional: true });\n if (heartbeatController) {\n void heartbeatController.triggerHeartbeat();\n }\n return (app as FirebaseAppImpl).container.getProvider(name);\n}\n\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\n *\n * @internal\n */\nexport function _removeServiceInstance(\n app: FirebaseApp,\n name: T,\n instanceIdentifier: string = DEFAULT_ENTRY_NAME\n): void {\n _getProvider(app, name).clearInstance(instanceIdentifier);\n}\n\n/**\n *\n * @param obj - an object of type FirebaseApp, FirebaseOptions or FirebaseAppSettings.\n *\n * @returns true if the provide object is of type FirebaseApp.\n *\n * @internal\n */\nexport function _isFirebaseApp(\n obj: FirebaseApp | FirebaseOptions | FirebaseAppSettings\n): obj is FirebaseApp {\n return (obj as FirebaseApp).options !== undefined;\n}\n\n/**\n *\n * @param obj - an object of type FirebaseApp, FirebaseOptions or FirebaseAppSettings.\n *\n * @returns true if the provided object is of type FirebaseServerAppImpl.\n *\n * @internal\n */\nexport function _isFirebaseServerAppSettings(\n obj: FirebaseApp | FirebaseOptions | FirebaseAppSettings\n): obj is FirebaseServerAppSettings {\n if (_isFirebaseApp(obj)) {\n return false;\n }\n return (\n 'authIdToken' in obj ||\n 'appCheckToken' in obj ||\n 'releaseOnDeref' in obj ||\n 'automaticDataCollectionEnabled' in obj\n );\n}\n\n/**\n *\n * @param obj - an object of type FirebaseApp.\n *\n * @returns true if the provided object is of type FirebaseServerAppImpl.\n *\n * @internal\n */\nexport function _isFirebaseServerApp(\n obj: FirebaseApp | FirebaseServerApp | null | undefined\n): obj is FirebaseServerApp {\n if (obj === null || obj === undefined) {\n return false;\n }\n return (obj as FirebaseServerApp).settings !== undefined;\n}\n\n/**\n * Test only\n *\n * @internal\n */\nexport function _clearComponents(): void {\n _components.clear();\n}\n\n/**\n * Exported in order to be used in app-compat package\n */\nexport { DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME };\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppError {\n NO_APP = 'no-app',\n BAD_APP_NAME = 'bad-app-name',\n DUPLICATE_APP = 'duplicate-app',\n APP_DELETED = 'app-deleted',\n SERVER_APP_DELETED = 'server-app-deleted',\n NO_OPTIONS = 'no-options',\n INVALID_APP_ARGUMENT = 'invalid-app-argument',\n INVALID_LOG_ARGUMENT = 'invalid-log-argument',\n IDB_OPEN = 'idb-open',\n IDB_GET = 'idb-get',\n IDB_WRITE = 'idb-set',\n IDB_DELETE = 'idb-delete',\n FINALIZATION_REGISTRY_NOT_SUPPORTED = 'finalization-registry-not-supported',\n INVALID_SERVER_APP_ENVIRONMENT = 'invalid-server-app-environment'\n}\n\nconst ERRORS: ErrorMap = {\n [AppError.NO_APP]:\n \"No Firebase App '{$appName}' has been created - \" +\n 'call initializeApp() first',\n [AppError.BAD_APP_NAME]: \"Illegal App name: '{$appName}'\",\n [AppError.DUPLICATE_APP]:\n \"Firebase App named '{$appName}' already exists with different options or config\",\n [AppError.APP_DELETED]: \"Firebase App named '{$appName}' already deleted\",\n [AppError.SERVER_APP_DELETED]: 'Firebase Server App has been deleted',\n [AppError.NO_OPTIONS]:\n 'Need to provide options, when not being deployed to hosting via source.',\n [AppError.INVALID_APP_ARGUMENT]:\n 'firebase.{$appName}() takes either no argument or a ' +\n 'Firebase App instance.',\n [AppError.INVALID_LOG_ARGUMENT]:\n 'First argument to `onLog` must be null or a function.',\n [AppError.IDB_OPEN]:\n 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_GET]:\n 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_WRITE]:\n 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_DELETE]:\n 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED]:\n 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',\n [AppError.INVALID_SERVER_APP_ENVIRONMENT]:\n 'FirebaseServerApp is not for use in browser environments.'\n};\n\ninterface ErrorParams {\n [AppError.NO_APP]: { appName: string };\n [AppError.BAD_APP_NAME]: { appName: string };\n [AppError.DUPLICATE_APP]: { appName: string };\n [AppError.APP_DELETED]: { appName: string };\n [AppError.INVALID_APP_ARGUMENT]: { appName: string };\n [AppError.IDB_OPEN]: { originalErrorMessage?: string };\n [AppError.IDB_GET]: { originalErrorMessage?: string };\n [AppError.IDB_WRITE]: { originalErrorMessage?: string };\n [AppError.IDB_DELETE]: { originalErrorMessage?: string };\n [AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED]: { appName?: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory(\n 'app',\n 'Firebase',\n ERRORS\n);\n", "/**\n * @license\n * Copyright 2019 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 * http://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 {\n FirebaseApp,\n FirebaseOptions,\n FirebaseAppSettings\n} from './public-types';\nimport {\n ComponentContainer,\n Component,\n ComponentType\n} from '@firebase/component';\nimport { ERROR_FACTORY, AppError } from './errors';\n\nexport class FirebaseAppImpl implements FirebaseApp {\n protected readonly _options: FirebaseOptions;\n protected readonly _name: string;\n /**\n * Original config values passed in as a constructor parameter.\n * It is only used to compare with another config object to support idempotent initializeApp().\n *\n * Updating automaticDataCollectionEnabled on the App instance will not change its value in _config.\n */\n private readonly _config: Required;\n private _automaticDataCollectionEnabled: boolean;\n protected _isDeleted = false;\n private readonly _container: ComponentContainer;\n\n constructor(\n options: FirebaseOptions,\n config: Required,\n container: ComponentContainer\n ) {\n this._options = { ...options };\n this._config = { ...config };\n this._name = config.name;\n this._automaticDataCollectionEnabled =\n config.automaticDataCollectionEnabled;\n this._container = container;\n this.container.addComponent(\n new Component('app', () => this, ComponentType.PUBLIC)\n );\n }\n\n get automaticDataCollectionEnabled(): boolean {\n this.checkDestroyed();\n return this._automaticDataCollectionEnabled;\n }\n\n set automaticDataCollectionEnabled(val: boolean) {\n this.checkDestroyed();\n this._automaticDataCollectionEnabled = val;\n }\n\n get name(): string {\n this.checkDestroyed();\n return this._name;\n }\n\n get options(): FirebaseOptions {\n this.checkDestroyed();\n return this._options;\n }\n\n get config(): Required {\n this.checkDestroyed();\n return this._config;\n }\n\n get container(): ComponentContainer {\n return this._container;\n }\n\n get isDeleted(): boolean {\n return this._isDeleted;\n }\n\n set isDeleted(val: boolean) {\n this._isDeleted = val;\n }\n\n /**\n * This function will throw an Error if the App has already been deleted -\n * use before performing API actions on the App.\n */\n protected checkDestroyed(): void {\n if (this.isDeleted) {\n throw ERROR_FACTORY.create(AppError.APP_DELETED, { appName: this._name });\n }\n }\n}\n", "/**\n * @license\n * Copyright 2023 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 * http://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 {\n FirebaseAppSettings,\n FirebaseServerApp,\n FirebaseServerAppSettings,\n FirebaseOptions\n} from './public-types';\nimport { deleteApp, registerVersion } from './api';\nimport { ComponentContainer } from '@firebase/component';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { ERROR_FACTORY, AppError } from './errors';\nimport { name as packageName, version } from '../package.json';\nimport { base64Decode } from '@firebase/util';\n\n// Parse the token and check to see if the `exp` claim is in the future.\n// Reports an error to the console if the token or claim could not be parsed, or if `exp` is in\n// the past.\nfunction validateTokenTTL(base64Token: string, tokenName: string): void {\n const secondPart = base64Decode(base64Token.split('.')[1]);\n if (secondPart === null) {\n console.error(\n `FirebaseServerApp ${tokenName} is invalid: second part could not be parsed.`\n );\n return;\n }\n const expClaim = JSON.parse(secondPart).exp;\n if (expClaim === undefined) {\n console.error(\n `FirebaseServerApp ${tokenName} is invalid: expiration claim could not be parsed`\n );\n return;\n }\n const exp = JSON.parse(secondPart).exp * 1000;\n const now = new Date().getTime();\n const diff = exp - now;\n if (diff <= 0) {\n console.error(\n `FirebaseServerApp ${tokenName} is invalid: the token has expired.`\n );\n }\n}\n\nexport class FirebaseServerAppImpl\n extends FirebaseAppImpl\n implements FirebaseServerApp\n{\n private readonly _serverConfig: FirebaseServerAppSettings;\n private _finalizationRegistry: FinalizationRegistry | null;\n private _refCount: number;\n\n constructor(\n options: FirebaseOptions | FirebaseAppImpl,\n serverConfig: FirebaseServerAppSettings,\n name: string,\n container: ComponentContainer\n ) {\n // Build configuration parameters for the FirebaseAppImpl base class.\n const automaticDataCollectionEnabled =\n serverConfig.automaticDataCollectionEnabled !== undefined\n ? serverConfig.automaticDataCollectionEnabled\n : true;\n\n // Create the FirebaseAppSettings object for the FirebaseAppImp constructor.\n const config: Required = {\n name,\n automaticDataCollectionEnabled\n };\n\n if ((options as FirebaseOptions).apiKey !== undefined) {\n // Construct the parent FirebaseAppImp object.\n super(options as FirebaseOptions, config, container);\n } else {\n const appImpl: FirebaseAppImpl = options as FirebaseAppImpl;\n super(appImpl.options, config, container);\n }\n\n // Now construct the data for the FirebaseServerAppImpl.\n this._serverConfig = {\n automaticDataCollectionEnabled,\n ...serverConfig\n };\n\n // Ensure that the current time is within the `authIdtoken` window of validity.\n if (this._serverConfig.authIdToken) {\n validateTokenTTL(this._serverConfig.authIdToken, 'authIdToken');\n }\n\n // Ensure that the current time is within the `appCheckToken` window of validity.\n if (this._serverConfig.appCheckToken) {\n validateTokenTTL(this._serverConfig.appCheckToken, 'appCheckToken');\n }\n\n this._finalizationRegistry = null;\n if (typeof FinalizationRegistry !== 'undefined') {\n this._finalizationRegistry = new FinalizationRegistry(() => {\n this.automaticCleanup();\n });\n }\n\n this._refCount = 0;\n this.incRefCount(this._serverConfig.releaseOnDeref);\n\n // Do not retain a hard reference to the dref object, otherwise the FinalizationRegistry\n // will never trigger.\n this._serverConfig.releaseOnDeref = undefined;\n serverConfig.releaseOnDeref = undefined;\n\n registerVersion(packageName, version, 'serverapp');\n }\n\n toJSON(): undefined {\n return undefined;\n }\n\n get refCount(): number {\n return this._refCount;\n }\n\n // Increment the reference count of this server app. If an object is provided, register it\n // with the finalization registry.\n incRefCount(obj: object | undefined): void {\n if (this.isDeleted) {\n return;\n }\n this._refCount++;\n if (obj !== undefined && this._finalizationRegistry !== null) {\n this._finalizationRegistry.register(obj, this);\n }\n }\n\n // Decrement the reference count.\n decRefCount(): number {\n if (this.isDeleted) {\n return 0;\n }\n return --this._refCount;\n }\n\n // Invoked by the FinalizationRegistry callback to note that this app should go through its\n // reference counts and delete itself if no reference count remain. The coordinating logic that\n // handles this is in deleteApp(...).\n private automaticCleanup(): void {\n void deleteApp(this);\n }\n\n get settings(): FirebaseServerAppSettings {\n this.checkDestroyed();\n return this._serverConfig;\n }\n\n /**\n * This function will throw an Error if the App has already been deleted -\n * use before performing API actions on the App.\n */\n protected checkDestroyed(): void {\n if (this.isDeleted) {\n throw ERROR_FACTORY.create(AppError.SERVER_APP_DELETED);\n }\n }\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 {\n FirebaseApp,\n FirebaseServerApp,\n FirebaseOptions,\n FirebaseAppSettings,\n FirebaseServerAppSettings\n} from './public-types';\nimport { DEFAULT_ENTRY_NAME, PLATFORM_LOG_STRING } from './constants';\nimport { ERROR_FACTORY, AppError } from './errors';\nimport {\n ComponentContainer,\n Component,\n Name,\n ComponentType\n} from '@firebase/component';\nimport { version } from '../../firebase/package.json';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { FirebaseServerAppImpl } from './firebaseServerApp';\nimport {\n _apps,\n _components,\n _isFirebaseApp,\n _isFirebaseServerAppSettings,\n _registerComponent,\n _serverApps\n} from './internal';\nimport { logger } from './logger';\nimport {\n LogLevelString,\n setLogLevel as setLogLevelImpl,\n LogCallback,\n LogOptions,\n setUserLogHandler\n} from '@firebase/logger';\nimport {\n deepEqual,\n getDefaultAppConfig,\n isBrowser,\n isWebWorker\n} from '@firebase/util';\n\nexport { FirebaseError } from '@firebase/util';\n\n/**\n * The current SDK version.\n *\n * @public\n */\nexport const SDK_VERSION = version;\n\n/**\n * Creates and initializes a {@link @firebase/app#FirebaseApp} instance.\n *\n * See\n * {@link\n * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app\n * | Add Firebase to your app} and\n * {@link\n * https://firebase.google.com/docs/web/setup#multiple-projects\n * | Initialize multiple projects} for detailed documentation.\n *\n * @example\n * ```javascript\n *\n * // Initialize default app\n * // Retrieve your own options values by adding a web app on\n * // https://console.firebase.google.com\n * initializeApp({\n * apiKey: \"AIza....\", // Auth / General Use\n * authDomain: \"YOUR_APP.firebaseapp.com\", // Auth with popup/redirect\n * databaseURL: \"https://YOUR_APP.firebaseio.com\", // Realtime Database\n * storageBucket: \"YOUR_APP.appspot.com\", // Storage\n * messagingSenderId: \"123456789\" // Cloud Messaging\n * });\n * ```\n *\n * @example\n * ```javascript\n *\n * // Initialize another app\n * const otherApp = initializeApp({\n * databaseURL: \"https://.firebaseio.com\",\n * storageBucket: \".appspot.com\"\n * }, \"otherApp\");\n * ```\n *\n * @param options - Options to configure the app's services.\n * @param name - Optional name of the app to initialize. If no name\n * is provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The initialized app.\n *\n * @throws If the optional `name` parameter is malformed or empty.\n *\n * @throws If a `FirebaseApp` already exists with the same name but with a different configuration.\n *\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n name?: string\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @param options - Options to configure the app's services.\n * @param config - FirebaseApp Configuration\n *\n * @throws If {@link FirebaseAppSettings.name} is defined but the value is malformed or empty.\n *\n * @throws If a `FirebaseApp` already exists with the same name but with a different configuration.\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n config?: FirebaseAppSettings\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @public\n */\nexport function initializeApp(): FirebaseApp;\nexport function initializeApp(\n _options?: FirebaseOptions,\n rawConfig = {}\n): FirebaseApp {\n let options = _options;\n\n if (typeof rawConfig !== 'object') {\n const name = rawConfig;\n rawConfig = { name };\n }\n\n const config: Required = {\n name: DEFAULT_ENTRY_NAME,\n automaticDataCollectionEnabled: true,\n ...rawConfig\n };\n const name = config.name;\n\n if (typeof name !== 'string' || !name) {\n throw ERROR_FACTORY.create(AppError.BAD_APP_NAME, {\n appName: String(name)\n });\n }\n\n options ||= getDefaultAppConfig();\n\n if (!options) {\n throw ERROR_FACTORY.create(AppError.NO_OPTIONS);\n }\n\n const existingApp = _apps.get(name) as FirebaseAppImpl;\n if (existingApp) {\n // return the existing app if options and config deep equal the ones in the existing app.\n if (\n deepEqual(options, existingApp.options) &&\n deepEqual(config, existingApp.config)\n ) {\n return existingApp;\n } else {\n throw ERROR_FACTORY.create(AppError.DUPLICATE_APP, { appName: name });\n }\n }\n\n const container = new ComponentContainer(name);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n\n const newApp = new FirebaseAppImpl(options, config, container);\n\n _apps.set(name, newApp);\n\n return newApp;\n}\n\n/**\n * Creates and initializes a {@link @firebase/app#FirebaseServerApp} instance.\n *\n * The `FirebaseServerApp` is similar to `FirebaseApp`, but is intended for execution in\n * server side rendering environments only. Initialization will fail if invoked from a\n * browser environment.\n *\n * See\n * {@link\n * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app\n * | Add Firebase to your app} and\n * {@link\n * https://firebase.google.com/docs/web/setup#multiple-projects\n * | Initialize multiple projects} for detailed documentation.\n *\n * @example\n * ```javascript\n *\n * // Initialize an instance of `FirebaseServerApp`.\n * // Retrieve your own options values by adding a web app on\n * // https://console.firebase.google.com\n * initializeServerApp({\n * apiKey: \"AIza....\", // Auth / General Use\n * authDomain: \"YOUR_APP.firebaseapp.com\", // Auth with popup/redirect\n * databaseURL: \"https://YOUR_APP.firebaseio.com\", // Realtime Database\n * storageBucket: \"YOUR_APP.appspot.com\", // Storage\n * messagingSenderId: \"123456789\" // Cloud Messaging\n * },\n * {\n * authIdToken: \"Your Auth ID Token\"\n * });\n * ```\n *\n * @param options - `Firebase.AppOptions` to configure the app's services, or a\n * a `FirebaseApp` instance which contains the `AppOptions` within.\n * @param config - Optional `FirebaseServerApp` settings.\n *\n * @returns The initialized `FirebaseServerApp`.\n *\n * @throws If invoked in an unsupported non-server environment such as a browser.\n *\n * @throws If {@link FirebaseServerAppSettings.releaseOnDeref} is defined but the runtime doesn't\n * provide Finalization Registry support.\n *\n * @public\n */\nexport function initializeServerApp(\n options: FirebaseOptions | FirebaseApp,\n config?: FirebaseServerAppSettings\n): FirebaseServerApp;\n\n/**\n * Creates and initializes a {@link @firebase/app#FirebaseServerApp} instance.\n *\n * @param config - Optional `FirebaseServerApp` settings.\n *\n * @returns The initialized `FirebaseServerApp`.\n *\n * @throws If invoked in an unsupported non-server environment such as a browser.\n * @throws If {@link FirebaseServerAppSettings.releaseOnDeref} is defined but the runtime doesn't\n * provide Finalization Registry support.\n * @throws If the `FIREBASE_OPTIONS` environment variable does not contain a valid project\n * configuration required for auto-initialization.\n *\n * @public\n */\nexport function initializeServerApp(\n config?: FirebaseServerAppSettings\n): FirebaseServerApp;\nexport function initializeServerApp(\n _options?: FirebaseApp | FirebaseServerAppSettings | FirebaseOptions,\n _serverAppConfig: FirebaseServerAppSettings = {}\n): FirebaseServerApp {\n if (isBrowser() && !isWebWorker()) {\n // FirebaseServerApp isn't designed to be run in browsers.\n throw ERROR_FACTORY.create(AppError.INVALID_SERVER_APP_ENVIRONMENT);\n }\n\n let firebaseOptions: FirebaseOptions | undefined;\n let serverAppSettings: FirebaseServerAppSettings = _serverAppConfig || {};\n\n if (_options) {\n if (_isFirebaseApp(_options)) {\n firebaseOptions = _options.options;\n } else if (_isFirebaseServerAppSettings(_options)) {\n serverAppSettings = _options;\n } else {\n firebaseOptions = _options;\n }\n }\n\n if (serverAppSettings.automaticDataCollectionEnabled === undefined) {\n serverAppSettings.automaticDataCollectionEnabled = true;\n }\n\n firebaseOptions ||= getDefaultAppConfig();\n if (!firebaseOptions) {\n throw ERROR_FACTORY.create(AppError.NO_OPTIONS);\n }\n\n // Build an app name based on a hash of the configuration options.\n const nameObj = {\n ...serverAppSettings,\n ...firebaseOptions\n };\n\n // However, Do not mangle the name based on releaseOnDeref, since it will vary between the\n // construction of FirebaseServerApp instances. For example, if the object is the request headers.\n if (nameObj.releaseOnDeref !== undefined) {\n delete nameObj.releaseOnDeref;\n }\n\n const hashCode = (s: string): number => {\n return [...s].reduce(\n (hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0,\n 0\n );\n };\n\n if (serverAppSettings.releaseOnDeref !== undefined) {\n if (typeof FinalizationRegistry === 'undefined') {\n throw ERROR_FACTORY.create(\n AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED,\n {}\n );\n }\n }\n\n const nameString = '' + hashCode(JSON.stringify(nameObj));\n const existingApp = _serverApps.get(nameString) as FirebaseServerApp;\n if (existingApp) {\n (existingApp as FirebaseServerAppImpl).incRefCount(\n serverAppSettings.releaseOnDeref\n );\n return existingApp;\n }\n\n const container = new ComponentContainer(nameString);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n\n const newApp = new FirebaseServerAppImpl(\n firebaseOptions,\n serverAppSettings,\n nameString,\n container\n );\n\n _serverApps.set(nameString, newApp);\n\n return newApp;\n}\n\n/**\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\n *\n * When called with no arguments, the default app is returned. When an app name\n * is provided, the app corresponding to that name is returned.\n *\n * An exception is thrown if the app being retrieved has not yet been\n * initialized.\n *\n * @example\n * ```javascript\n * // Return the default app\n * const app = getApp();\n * ```\n *\n * @example\n * ```javascript\n * // Return a named app\n * const otherApp = getApp(\"otherApp\");\n * ```\n *\n * @param name - Optional name of the app to return. If no name is\n * provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The app corresponding to the provided app name.\n * If no app name is provided, the default app is returned.\n *\n * @public\n */\nexport function getApp(name: string = DEFAULT_ENTRY_NAME): FirebaseApp {\n const app = _apps.get(name);\n if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\n return initializeApp();\n }\n if (!app) {\n throw ERROR_FACTORY.create(AppError.NO_APP, { appName: name });\n }\n\n return app;\n}\n\n/**\n * A (read-only) array of all initialized apps.\n * @public\n */\nexport function getApps(): FirebaseApp[] {\n return Array.from(_apps.values());\n}\n\n/**\n * Renders this app unusable and frees the resources of all associated\n * services.\n *\n * @example\n * ```javascript\n * deleteApp(app)\n * .then(function() {\n * console.log(\"App deleted successfully\");\n * })\n * .catch(function(error) {\n * console.log(\"Error deleting app:\", error);\n * });\n * ```\n *\n * @public\n */\nexport async function deleteApp(app: FirebaseApp): Promise {\n let cleanupProviders = false;\n const name = app.name;\n if (_apps.has(name)) {\n cleanupProviders = true;\n _apps.delete(name);\n } else if (_serverApps.has(name)) {\n const firebaseServerApp = app as FirebaseServerAppImpl;\n if (firebaseServerApp.decRefCount() <= 0) {\n _serverApps.delete(name);\n cleanupProviders = true;\n }\n }\n\n if (cleanupProviders) {\n await Promise.all(\n (app as FirebaseAppImpl).container\n .getProviders()\n .map(provider => provider.delete())\n );\n (app as FirebaseAppImpl).isDeleted = true;\n }\n}\n\n/**\n * Registers a library's name and version for platform logging purposes.\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\n * @param version - Current version of that library.\n * @param variant - Bundle variant, e.g., node, rn, etc.\n *\n * @public\n */\nexport function registerVersion(\n libraryKeyOrName: string,\n version: string,\n variant?: string\n): void {\n // TODO: We can use this check to whitelist strings when/if we set up\n // a good whitelist system.\n let library = PLATFORM_LOG_STRING[libraryKeyOrName] ?? libraryKeyOrName;\n if (variant) {\n library += `-${variant}`;\n }\n const libraryMismatch = library.match(/\\s|\\//);\n const versionMismatch = version.match(/\\s|\\//);\n if (libraryMismatch || versionMismatch) {\n const warning = [\n `Unable to register library \"${library}\" with version \"${version}\":`\n ];\n if (libraryMismatch) {\n warning.push(\n `library name \"${library}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n if (libraryMismatch && versionMismatch) {\n warning.push('and');\n }\n if (versionMismatch) {\n warning.push(\n `version name \"${version}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n logger.warn(warning.join(' '));\n return;\n }\n _registerComponent(\n new Component(\n `${library}-version` as Name,\n () => ({ library, version }),\n ComponentType.VERSION\n )\n );\n}\n\n/**\n * Sets log handler for all Firebase SDKs.\n * @param logCallback - An optional custom log handler that executes user code whenever\n * the Firebase SDK makes a logging call.\n *\n * @public\n */\nexport function onLog(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n if (logCallback !== null && typeof logCallback !== 'function') {\n throw ERROR_FACTORY.create(AppError.INVALID_LOG_ARGUMENT);\n }\n setUserLogHandler(logCallback, options);\n}\n\n/**\n * Sets log level for all Firebase SDKs.\n *\n * All of the log types above the current log level are captured (i.e. if\n * you set the log level to `info`, errors are logged, but `debug` and\n * `verbose` logs are not).\n *\n * @public\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n setLogLevelImpl(logLevel);\n}\n", "/**\n * @license\n * Copyright 2021 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 * http://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 { FirebaseError } from '@firebase/util';\nimport { DBSchema, openDB, IDBPDatabase } from 'idb';\nimport { AppError, ERROR_FACTORY } from './errors';\nimport { FirebaseApp } from './public-types';\nimport { HeartbeatsInIndexedDB } from './types';\nimport { logger } from './logger';\n\nconst DB_NAME = 'firebase-heartbeat-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-heartbeat-store';\n\ninterface AppDB extends DBSchema {\n 'firebase-heartbeat-store': {\n key: string;\n value: HeartbeatsInIndexedDB;\n };\n}\n\nlet dbPromise: Promise> | null = null;\nfunction getDbPromise(): Promise> {\n if (!dbPromise) {\n dbPromise = openDB(DB_NAME, DB_VERSION, {\n upgrade: (db, oldVersion) => {\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (oldVersion) {\n case 0:\n try {\n db.createObjectStore(STORE_NAME);\n } catch (e) {\n // Safari/iOS browsers throw occasional exceptions on\n // db.createObjectStore() that may be a bug. Avoid blocking\n // the rest of the app functionality.\n console.warn(e);\n }\n }\n }\n }).catch(e => {\n throw ERROR_FACTORY.create(AppError.IDB_OPEN, {\n originalErrorMessage: e.message\n });\n });\n }\n return dbPromise;\n}\n\nexport async function readHeartbeatsFromIndexedDB(\n app: FirebaseApp\n): Promise {\n try {\n const db = await getDbPromise();\n const tx = db.transaction(STORE_NAME);\n const result = await tx.objectStore(STORE_NAME).get(computeKey(app));\n // We already have the value but tx.done can throw,\n // so we need to await it here to catch errors\n await tx.done;\n return result;\n } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_GET, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nexport async function writeHeartbeatsToIndexedDB(\n app: FirebaseApp,\n heartbeatObject: HeartbeatsInIndexedDB\n): Promise {\n try {\n const db = await getDbPromise();\n const tx = db.transaction(STORE_NAME, 'readwrite');\n const objectStore = tx.objectStore(STORE_NAME);\n await objectStore.put(heartbeatObject, computeKey(app));\n await tx.done;\n } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_WRITE, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nfunction computeKey(app: FirebaseApp): string {\n return `${app.name}!${app.options.appId}`;\n}\n", "/**\n * @license\n * Copyright 2021 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 * http://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 { ComponentContainer } from '@firebase/component';\nimport {\n base64urlEncodeWithoutPadding,\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\nimport {\n readHeartbeatsFromIndexedDB,\n writeHeartbeatsToIndexedDB\n} from './indexeddb';\nimport { FirebaseApp } from './public-types';\nimport {\n HeartbeatsByUserAgent,\n HeartbeatService,\n HeartbeatsInIndexedDB,\n HeartbeatStorage,\n SingleDateHeartbeat\n} from './types';\nimport { logger } from './logger';\n\nconst MAX_HEADER_BYTES = 1024;\nexport const MAX_NUM_STORED_HEARTBEATS = 30;\n\nexport class HeartbeatServiceImpl implements HeartbeatService {\n /**\n * The persistence layer for heartbeats\n * Leave public for easier testing.\n */\n _storage: HeartbeatStorageImpl;\n\n /**\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\n * the header string.\n * Stores one record per date. This will be consolidated into the standard\n * format of one record per user agent string before being sent as a header.\n * Populated from indexedDB when the controller is instantiated and should\n * be kept in sync with indexedDB.\n * Leave public for easier testing.\n */\n _heartbeatsCache: HeartbeatsInIndexedDB | null = null;\n\n /**\n * the initialization promise for populating heartbeatCache.\n * If getHeartbeatsHeader() is called before the promise resolves\n * (heartbeatsCache == null), it should wait for this promise\n * Leave public for easier testing.\n */\n _heartbeatsCachePromise: Promise;\n constructor(private readonly container: ComponentContainer) {\n const app = this.container.getProvider('app').getImmediate();\n this._storage = new HeartbeatStorageImpl(app);\n this._heartbeatsCachePromise = this._storage.read().then(result => {\n this._heartbeatsCache = result;\n return result;\n });\n }\n\n /**\n * Called to report a heartbeat. The function will generate\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\n * to IndexedDB.\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\n * already logged, subsequent calls to this function in the same day will be ignored.\n */\n async triggerHeartbeat(): Promise {\n try {\n const platformLogger = this.container\n .getProvider('platform-logger')\n .getImmediate();\n\n // This is the \"Firebase user agent\" string from the platform logger\n // service, not the browser user agent.\n const agent = platformLogger.getPlatformInfoString();\n const date = getUTCDateString();\n if (this._heartbeatsCache?.heartbeats == null) {\n this._heartbeatsCache = await this._heartbeatsCachePromise;\n // If we failed to construct a heartbeats cache, then return immediately.\n if (this._heartbeatsCache?.heartbeats == null) {\n return;\n }\n }\n // Do not store a heartbeat if one is already stored for this day\n // or if a header has already been sent today.\n if (\n this._heartbeatsCache.lastSentHeartbeatDate === date ||\n this._heartbeatsCache.heartbeats.some(\n singleDateHeartbeat => singleDateHeartbeat.date === date\n )\n ) {\n return;\n } else {\n // There is no entry for this date. Create one.\n this._heartbeatsCache.heartbeats.push({ date, agent });\n\n // If the number of stored heartbeats exceeds the maximum number of stored heartbeats, remove the heartbeat with the earliest date.\n // Since this is executed each time a heartbeat is pushed, the limit can only be exceeded by one, so only one needs to be removed.\n if (\n this._heartbeatsCache.heartbeats.length > MAX_NUM_STORED_HEARTBEATS\n ) {\n const earliestHeartbeatIdx = getEarliestHeartbeatIdx(\n this._heartbeatsCache.heartbeats\n );\n this._heartbeatsCache.heartbeats.splice(earliestHeartbeatIdx, 1);\n }\n }\n\n return this._storage.overwrite(this._heartbeatsCache);\n } catch (e) {\n logger.warn(e);\n }\n }\n\n /**\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\n * It also clears all heartbeats from memory as well as in IndexedDB.\n *\n * NOTE: Consuming product SDKs should not send the header if this method\n * returns an empty string.\n */\n async getHeartbeatsHeader(): Promise {\n try {\n if (this._heartbeatsCache === null) {\n await this._heartbeatsCachePromise;\n }\n // If it's still null or the array is empty, there is no data to send.\n if (\n this._heartbeatsCache?.heartbeats == null ||\n this._heartbeatsCache.heartbeats.length === 0\n ) {\n return '';\n }\n const date = getUTCDateString();\n // Extract as many heartbeats from the cache as will fit under the size limit.\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(\n this._heartbeatsCache.heartbeats\n );\n const headerString = base64urlEncodeWithoutPadding(\n JSON.stringify({ version: 2, heartbeats: heartbeatsToSend })\n );\n // Store last sent date to prevent another being logged/sent for the same day.\n this._heartbeatsCache.lastSentHeartbeatDate = date;\n if (unsentEntries.length > 0) {\n // Store any unsent entries if they exist.\n this._heartbeatsCache.heartbeats = unsentEntries;\n // This seems more likely than emptying the array (below) to lead to some odd state\n // since the cache isn't empty and this will be called again on the next request,\n // and is probably safest if we await it.\n await this._storage.overwrite(this._heartbeatsCache);\n } else {\n this._heartbeatsCache.heartbeats = [];\n // Do not wait for this, to reduce latency.\n void this._storage.overwrite(this._heartbeatsCache);\n }\n return headerString;\n } catch (e) {\n logger.warn(e);\n return '';\n }\n }\n}\n\nfunction getUTCDateString(): string {\n const today = new Date();\n // Returns date format 'YYYY-MM-DD'\n return today.toISOString().substring(0, 10);\n}\n\nexport function extractHeartbeatsForHeader(\n heartbeatsCache: SingleDateHeartbeat[],\n maxSize = MAX_HEADER_BYTES\n): {\n heartbeatsToSend: HeartbeatsByUserAgent[];\n unsentEntries: SingleDateHeartbeat[];\n} {\n // Heartbeats grouped by user agent in the standard format to be sent in\n // the header.\n const heartbeatsToSend: HeartbeatsByUserAgent[] = [];\n // Single date format heartbeats that are not sent.\n let unsentEntries = heartbeatsCache.slice();\n for (const singleDateHeartbeat of heartbeatsCache) {\n // Look for an existing entry with the same user agent.\n const heartbeatEntry = heartbeatsToSend.find(\n hb => hb.agent === singleDateHeartbeat.agent\n );\n if (!heartbeatEntry) {\n // If no entry for this user agent exists, create one.\n heartbeatsToSend.push({\n agent: singleDateHeartbeat.agent,\n dates: [singleDateHeartbeat.date]\n });\n if (countBytes(heartbeatsToSend) > maxSize) {\n // If the header would exceed max size, remove the added heartbeat\n // entry and stop adding to the header.\n heartbeatsToSend.pop();\n break;\n }\n } else {\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\n // If the header would exceed max size, remove the added date\n // and stop adding to the header.\n if (countBytes(heartbeatsToSend) > maxSize) {\n heartbeatEntry.dates.pop();\n break;\n }\n }\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\n // quota and the loop breaks early.)\n unsentEntries = unsentEntries.slice(1);\n }\n return {\n heartbeatsToSend,\n unsentEntries\n };\n}\n\nexport class HeartbeatStorageImpl implements HeartbeatStorage {\n private _canUseIndexedDBPromise: Promise;\n constructor(public app: FirebaseApp) {\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\n }\n async runIndexedDBEnvironmentCheck(): Promise {\n if (!isIndexedDBAvailable()) {\n return false;\n } else {\n return validateIndexedDBOpenable()\n .then(() => true)\n .catch(() => false);\n }\n }\n /**\n * Read all heartbeats.\n */\n async read(): Promise {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return { heartbeats: [] };\n } else {\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\n if (idbHeartbeatObject?.heartbeats) {\n return idbHeartbeatObject;\n } else {\n return { heartbeats: [] };\n }\n }\n }\n // overwrite the storage with the provided heartbeats\n async overwrite(heartbeatsObject: HeartbeatsInIndexedDB): Promise {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: heartbeatsObject.heartbeats\n });\n }\n }\n // add heartbeats\n async add(heartbeatsObject: HeartbeatsInIndexedDB): Promise {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: [\n ...existingHeartbeatsObject.heartbeats,\n ...heartbeatsObject.heartbeats\n ]\n });\n }\n }\n}\n\n/**\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\n * in a platform logging header JSON object, stringified, and converted\n * to base 64.\n */\nexport function countBytes(heartbeatsCache: HeartbeatsByUserAgent[]): number {\n // base64 has a restricted set of characters, all of which should be 1 byte.\n return base64urlEncodeWithoutPadding(\n // heartbeatsCache wrapper properties\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })\n ).length;\n}\n\n/**\n * Returns the index of the heartbeat with the earliest date.\n * If the heartbeats array is empty, -1 is returned.\n */\nexport function getEarliestHeartbeatIdx(\n heartbeats: SingleDateHeartbeat[]\n): number {\n if (heartbeats.length === 0) {\n return -1;\n }\n\n let earliestHeartbeatIdx = 0;\n let earliestHeartbeatDate = heartbeats[0].date;\n\n for (let i = 1; i < heartbeats.length; i++) {\n if (heartbeats[i].date < earliestHeartbeatDate) {\n earliestHeartbeatDate = heartbeats[i].date;\n earliestHeartbeatIdx = i;\n }\n }\n\n return earliestHeartbeatIdx;\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { Component, ComponentType } from '@firebase/component';\nimport { PlatformLoggerServiceImpl } from './platformLoggerService';\nimport { name, version } from '../package.json';\nimport { _registerComponent } from './internal';\nimport { registerVersion } from './api';\nimport { HeartbeatServiceImpl } from './heartbeatService';\n\nexport function registerCoreComponents(variant?: string): void {\n _registerComponent(\n new Component(\n 'platform-logger',\n container => new PlatformLoggerServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n _registerComponent(\n new Component(\n 'heartbeat',\n container => new HeartbeatServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n\n // Register `app` package.\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n // Register platform SDK identifier (no version).\n registerVersion('fire-js', '');\n}\n", "/**\n * Firebase App\n *\n * @remarks This package coordinates the communication between the different Firebase components\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 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 * http://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 { registerCoreComponents } from './registerCoreComponents';\n\nexport * from './api';\nexport * from './internal';\nexport * from './public-types';\n\nregisterCoreComponents('__RUNTIME_ENV__');\n", "/**\n * @license\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 * http://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 */\nimport { registerVersion } from '@firebase/app';\nimport { name, version } from '../package.json';\n\nregisterVersion(name, version, 'app');\nexport * from '@firebase/app';\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { version } from '../../package.json';\n\nexport const PENDING_TIMEOUT_MS = 10000;\n\nexport const PACKAGE_VERSION = `w:${version}`;\nexport const INTERNAL_AUTH_VERSION = 'FIS_v2';\n\nexport const INSTALLATIONS_API_URL =\n 'https://firebaseinstallations.googleapis.com/v1';\n\nexport const TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\n\nexport const SERVICE = 'installations';\nexport const SERVICE_NAME = 'Installations';\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { SERVICE, SERVICE_NAME } from './constants';\n\nexport const enum ErrorCode {\n MISSING_APP_CONFIG_VALUES = 'missing-app-config-values',\n NOT_REGISTERED = 'not-registered',\n INSTALLATION_NOT_FOUND = 'installation-not-found',\n REQUEST_FAILED = 'request-failed',\n APP_OFFLINE = 'app-offline',\n DELETE_PENDING_REGISTRATION = 'delete-pending-registration'\n}\n\nconst ERROR_DESCRIPTION_MAP: { readonly [key in ErrorCode]: string } = {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]:\n 'Missing App configuration value: \"{$valueName}\"',\n [ErrorCode.NOT_REGISTERED]: 'Firebase Installation is not registered.',\n [ErrorCode.INSTALLATION_NOT_FOUND]: 'Firebase Installation not found.',\n [ErrorCode.REQUEST_FAILED]:\n '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\n [ErrorCode.APP_OFFLINE]: 'Could not process request. Application offline.',\n [ErrorCode.DELETE_PENDING_REGISTRATION]:\n \"Can't delete installation while there is a pending registration request.\"\n};\n\ninterface ErrorParams {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]: {\n valueName: string;\n };\n [ErrorCode.REQUEST_FAILED]: {\n requestName: string;\n [index: string]: string | number; // to make TypeScript 3.8 happy\n } & ServerErrorData;\n}\n\nexport const ERROR_FACTORY = new ErrorFactory(\n SERVICE,\n SERVICE_NAME,\n ERROR_DESCRIPTION_MAP\n);\n\nexport interface ServerErrorData {\n serverCode: number;\n serverMessage: string;\n serverStatus: string;\n}\n\nexport type ServerError = FirebaseError & { customData: ServerErrorData };\n\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\nexport function isServerError(error: unknown): error is ServerError {\n return (\n error instanceof FirebaseError &&\n error.code.includes(ErrorCode.REQUEST_FAILED)\n );\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { FirebaseError } from '@firebase/util';\nimport { GenerateAuthTokenResponse } from '../interfaces/api-response';\nimport {\n CompletedAuthToken,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport {\n INSTALLATIONS_API_URL,\n INTERNAL_AUTH_VERSION\n} from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { AppConfig } from '../interfaces/installation-impl';\n\nexport function getInstallationsEndpoint({ projectId }: AppConfig): string {\n return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;\n}\n\nexport function extractAuthTokenInfoFromResponse(\n response: GenerateAuthTokenResponse\n): CompletedAuthToken {\n return {\n token: response.token,\n requestStatus: RequestStatus.COMPLETED,\n expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\n creationTime: Date.now()\n };\n}\n\nexport async function getErrorFromResponse(\n requestName: string,\n response: Response\n): Promise {\n const responseJson: ErrorResponse = await response.json();\n const errorData = responseJson.error;\n return ERROR_FACTORY.create(ErrorCode.REQUEST_FAILED, {\n requestName,\n serverCode: errorData.code,\n serverMessage: errorData.message,\n serverStatus: errorData.status\n });\n}\n\nexport function getHeaders({ apiKey }: AppConfig): Headers {\n return new Headers({\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-goog-api-key': apiKey\n });\n}\n\nexport function getHeadersWithAuth(\n appConfig: AppConfig,\n { refreshToken }: RegisteredInstallationEntry\n): Headers {\n const headers = getHeaders(appConfig);\n headers.append('Authorization', getAuthorizationHeader(refreshToken));\n return headers;\n}\n\nexport interface ErrorResponse {\n error: {\n code: number;\n message: string;\n status: string;\n };\n}\n\n/**\n * Calls the passed in fetch wrapper and returns the response.\n * If the returned response has a status of 5xx, re-runs the function once and\n * returns the response.\n */\nexport async function retryIfServerError(\n fn: () => Promise\n): Promise {\n const result = await fn();\n\n if (result.status >= 500 && result.status < 600) {\n // Internal Server Error. Retry request.\n return fn();\n }\n\n return result;\n}\n\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn: string): number {\n // This works because the server will never respond with fractions of a second.\n return Number(responseExpiresIn.replace('s', '000'));\n}\n\nfunction getAuthorizationHeader(refreshToken: string): string {\n return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { CreateInstallationResponse } from '../interfaces/api-response';\nimport {\n InProgressInstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { INTERNAL_AUTH_VERSION, PACKAGE_VERSION } from '../util/constants';\nimport {\n extractAuthTokenInfoFromResponse,\n getErrorFromResponse,\n getHeaders,\n getInstallationsEndpoint,\n retryIfServerError\n} from './common';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\n\nexport async function createInstallationRequest(\n { appConfig, heartbeatServiceProvider }: FirebaseInstallationsImpl,\n { fid }: InProgressInstallationEntry\n): Promise {\n const endpoint = getInstallationsEndpoint(appConfig);\n\n const headers = getHeaders(appConfig);\n\n // If heartbeat service exists, add the heartbeat string to the header.\n const heartbeatService = heartbeatServiceProvider.getImmediate({\n optional: true\n });\n if (heartbeatService) {\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers.append('x-firebase-client', heartbeatsHeader);\n }\n }\n\n const body = {\n fid,\n authVersion: INTERNAL_AUTH_VERSION,\n appId: appConfig.appId,\n sdkVersion: PACKAGE_VERSION\n };\n\n const request: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify(body)\n };\n\n const response = await retryIfServerError(() => fetch(endpoint, request));\n if (response.ok) {\n const responseValue: CreateInstallationResponse = await response.json();\n const registeredInstallationEntry: RegisteredInstallationEntry = {\n fid: responseValue.fid || fid,\n registrationStatus: RequestStatus.COMPLETED,\n refreshToken: responseValue.refreshToken,\n authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\n };\n return registeredInstallationEntry;\n } else {\n throw await getErrorFromResponse('Create Installation', response);\n }\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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/** Returns a promise that resolves after given time passes. */\nexport function sleep(ms: number): Promise {\n return new Promise(resolve => {\n setTimeout(resolve, ms);\n });\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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\nexport function bufferToBase64UrlSafe(array: Uint8Array): string {\n const b64 = btoa(String.fromCharCode(...array));\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { bufferToBase64UrlSafe } from './buffer-to-base64-url-safe';\n\nexport const VALID_FID_PATTERN = /^[cdef][\\w-]{21}$/;\nexport const INVALID_FID = '';\n\n/**\n * Generates a new FID using random values from Web Crypto API.\n * Returns an empty string if FID generation fails for any reason.\n */\nexport function generateFid(): string {\n try {\n // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\n // bytes. our implementation generates a 17 byte array instead.\n const fidByteArray = new Uint8Array(17);\n const crypto =\n self.crypto || (self as unknown as { msCrypto: Crypto }).msCrypto;\n crypto.getRandomValues(fidByteArray);\n\n // Replace the first 4 random bits with the constant FID header of 0b0111.\n fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);\n\n const fid = encode(fidByteArray);\n\n return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;\n } catch {\n // FID generation errored\n return INVALID_FID;\n }\n}\n\n/** Converts a FID Uint8Array to a base64 string representation. */\nfunction encode(fidByteArray: Uint8Array): string {\n const b64String = bufferToBase64UrlSafe(fidByteArray);\n\n // Remove the 23rd character that was added because of the extra 4 bits at the\n // end of our 17 byte array, and the '=' padding.\n return b64String.substr(0, 22);\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { AppConfig } from '../interfaces/installation-impl';\n\n/** Returns a string key that can be used to identify the app. */\nexport function getKey(appConfig: AppConfig): string {\n return `${appConfig.appName}!${appConfig.appId}`;\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { getKey } from '../util/get-key';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { IdChangeCallbackFn } from '../api';\n\nconst fidChangeCallbacks: Map> = new Map();\n\n/**\n * Calls the onIdChange callbacks with the new FID value, and broadcasts the\n * change to other tabs.\n */\nexport function fidChanged(appConfig: AppConfig, fid: string): void {\n const key = getKey(appConfig);\n\n callFidChangeCallbacks(key, fid);\n broadcastFidChange(key, fid);\n}\n\nexport function addCallback(\n appConfig: AppConfig,\n callback: IdChangeCallbackFn\n): void {\n // Open the broadcast channel if it's not already open,\n // to be able to listen to change events from other tabs.\n getBroadcastChannel();\n\n const key = getKey(appConfig);\n\n let callbackSet = fidChangeCallbacks.get(key);\n if (!callbackSet) {\n callbackSet = new Set();\n fidChangeCallbacks.set(key, callbackSet);\n }\n callbackSet.add(callback);\n}\n\nexport function removeCallback(\n appConfig: AppConfig,\n callback: IdChangeCallbackFn\n): void {\n const key = getKey(appConfig);\n\n const callbackSet = fidChangeCallbacks.get(key);\n\n if (!callbackSet) {\n return;\n }\n\n callbackSet.delete(callback);\n if (callbackSet.size === 0) {\n fidChangeCallbacks.delete(key);\n }\n\n // Close broadcast channel if there are no more callbacks.\n closeBroadcastChannel();\n}\n\nfunction callFidChangeCallbacks(key: string, fid: string): void {\n const callbacks = fidChangeCallbacks.get(key);\n if (!callbacks) {\n return;\n }\n\n for (const callback of callbacks) {\n callback(fid);\n }\n}\n\nfunction broadcastFidChange(key: string, fid: string): void {\n const channel = getBroadcastChannel();\n if (channel) {\n channel.postMessage({ key, fid });\n }\n closeBroadcastChannel();\n}\n\nlet broadcastChannel: BroadcastChannel | null = null;\n/** Opens and returns a BroadcastChannel if it is supported by the browser. */\nfunction getBroadcastChannel(): BroadcastChannel | null {\n if (!broadcastChannel && 'BroadcastChannel' in self) {\n broadcastChannel = new BroadcastChannel('[Firebase] FID Change');\n broadcastChannel.onmessage = e => {\n callFidChangeCallbacks(e.data.key, e.data.fid);\n };\n }\n return broadcastChannel;\n}\n\nfunction closeBroadcastChannel(): void {\n if (fidChangeCallbacks.size === 0 && broadcastChannel) {\n broadcastChannel.close();\n broadcastChannel = null;\n }\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { DBSchema, IDBPDatabase, openDB } from 'idb';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { InstallationEntry } from '../interfaces/installation-entry';\nimport { getKey } from '../util/get-key';\nimport { fidChanged } from './fid-changed';\n\nconst DATABASE_NAME = 'firebase-installations-database';\nconst DATABASE_VERSION = 1;\nconst OBJECT_STORE_NAME = 'firebase-installations-store';\n\ninterface InstallationsDB extends DBSchema {\n 'firebase-installations-store': {\n key: string;\n value: InstallationEntry | undefined;\n };\n}\n\nlet dbPromise: Promise> | null = null;\nfunction getDbPromise(): Promise> {\n if (!dbPromise) {\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\n upgrade: (db, oldVersion) => {\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (oldVersion) {\n case 0:\n db.createObjectStore(OBJECT_STORE_NAME);\n }\n }\n });\n }\n return dbPromise;\n}\n\n/** Gets record(s) from the objectStore that match the given key. */\nexport async function get(\n appConfig: AppConfig\n): Promise {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n return db\n .transaction(OBJECT_STORE_NAME)\n .objectStore(OBJECT_STORE_NAME)\n .get(key) as Promise;\n}\n\n/** Assigns or overwrites the record for the given key with the given value. */\nexport async function set(\n appConfig: AppConfig,\n value: ValueType\n): Promise {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n const objectStore = tx.objectStore(OBJECT_STORE_NAME);\n const oldValue = (await objectStore.get(key)) as InstallationEntry;\n await objectStore.put(value, key);\n await tx.done;\n\n if (!oldValue || oldValue.fid !== value.fid) {\n fidChanged(appConfig, value.fid);\n }\n\n return value;\n}\n\n/** Removes record(s) from the objectStore that match the given key. */\nexport async function remove(appConfig: AppConfig): Promise {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\n await tx.done;\n}\n\n/**\n * Atomically updates a record with the result of updateFn, which gets\n * called with the current value. If newValue is undefined, the record is\n * deleted instead.\n * @return Updated value\n */\nexport async function update(\n appConfig: AppConfig,\n updateFn: (previousValue: InstallationEntry | undefined) => ValueType\n): Promise {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n const store = tx.objectStore(OBJECT_STORE_NAME);\n const oldValue: InstallationEntry | undefined = (await store.get(\n key\n )) as InstallationEntry;\n const newValue = updateFn(oldValue);\n\n if (newValue === undefined) {\n await store.delete(key);\n } else {\n await store.put(newValue, key);\n }\n await tx.done;\n\n if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {\n fidChanged(appConfig, newValue.fid);\n }\n\n return newValue;\n}\n\nexport async function clear(): Promise {\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).clear();\n await tx.done;\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { createInstallationRequest } from '../functions/create-installation-request';\nimport {\n AppConfig,\n FirebaseInstallationsImpl\n} from '../interfaces/installation-impl';\nimport {\n InProgressInstallationEntry,\n InstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { PENDING_TIMEOUT_MS } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode, isServerError } from '../util/errors';\nimport { sleep } from '../util/sleep';\nimport { generateFid, INVALID_FID } from './generate-fid';\nimport { remove, set, update } from './idb-manager';\n\nexport interface InstallationEntryWithRegistrationPromise {\n installationEntry: InstallationEntry;\n /** Exist iff the installationEntry is not registered. */\n registrationPromise?: Promise;\n}\n\n/**\n * Updates and returns the InstallationEntry from the database.\n * Also triggers a registration request if it is necessary and possible.\n */\nexport async function getInstallationEntry(\n installations: FirebaseInstallationsImpl\n): Promise {\n let registrationPromise: Promise | undefined;\n\n const installationEntry = await update(installations.appConfig, oldEntry => {\n const installationEntry = updateOrCreateInstallationEntry(oldEntry);\n const entryWithPromise = triggerRegistrationIfNecessary(\n installations,\n installationEntry\n );\n registrationPromise = entryWithPromise.registrationPromise;\n return entryWithPromise.installationEntry;\n });\n\n if (installationEntry.fid === INVALID_FID) {\n // FID generation failed. Waiting for the FID from the server.\n return { installationEntry: await registrationPromise! };\n }\n\n return {\n installationEntry,\n registrationPromise\n };\n}\n\n/**\n * Creates a new Installation Entry if one does not exist.\n * Also clears timed out pending requests.\n */\nfunction updateOrCreateInstallationEntry(\n oldEntry: InstallationEntry | undefined\n): InstallationEntry {\n const entry: InstallationEntry = oldEntry || {\n fid: generateFid(),\n registrationStatus: RequestStatus.NOT_STARTED\n };\n\n return clearTimedOutRequest(entry);\n}\n\n/**\n * If the Firebase Installation is not registered yet, this will trigger the\n * registration and return an InProgressInstallationEntry.\n *\n * If registrationPromise does not exist, the installationEntry is guaranteed\n * to be registered.\n */\nfunction triggerRegistrationIfNecessary(\n installations: FirebaseInstallationsImpl,\n installationEntry: InstallationEntry\n): InstallationEntryWithRegistrationPromise {\n if (installationEntry.registrationStatus === RequestStatus.NOT_STARTED) {\n if (!navigator.onLine) {\n // Registration required but app is offline.\n const registrationPromiseWithError = Promise.reject(\n ERROR_FACTORY.create(ErrorCode.APP_OFFLINE)\n );\n return {\n installationEntry,\n registrationPromise: registrationPromiseWithError\n };\n }\n\n // Try registering. Change status to IN_PROGRESS.\n const inProgressEntry: InProgressInstallationEntry = {\n fid: installationEntry.fid,\n registrationStatus: RequestStatus.IN_PROGRESS,\n registrationTime: Date.now()\n };\n const registrationPromise = registerInstallation(\n installations,\n inProgressEntry\n );\n return { installationEntry: inProgressEntry, registrationPromise };\n } else if (\n installationEntry.registrationStatus === RequestStatus.IN_PROGRESS\n ) {\n return {\n installationEntry,\n registrationPromise: waitUntilFidRegistration(installations)\n };\n } else {\n return { installationEntry };\n }\n}\n\n/** This will be executed only once for each new Firebase Installation. */\nasync function registerInstallation(\n installations: FirebaseInstallationsImpl,\n installationEntry: InProgressInstallationEntry\n): Promise {\n try {\n const registeredInstallationEntry = await createInstallationRequest(\n installations,\n installationEntry\n );\n return set(installations.appConfig, registeredInstallationEntry);\n } catch (e) {\n if (isServerError(e) && e.customData.serverCode === 409) {\n // Server returned a \"FID cannot be used\" error.\n // Generate a new ID next time.\n await remove(installations.appConfig);\n } else {\n // Registration failed. Set FID as not registered.\n await set(installations.appConfig, {\n fid: installationEntry.fid,\n registrationStatus: RequestStatus.NOT_STARTED\n });\n }\n throw e;\n }\n}\n\n/** Call if FID registration is pending in another request. */\nasync function waitUntilFidRegistration(\n installations: FirebaseInstallationsImpl\n): Promise {\n // Unfortunately, there is no way of reliably observing when a value in\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\n // so we need to poll.\n\n let entry: InstallationEntry = await updateInstallationRequest(\n installations.appConfig\n );\n while (entry.registrationStatus === RequestStatus.IN_PROGRESS) {\n // createInstallation request still in progress.\n await sleep(100);\n\n entry = await updateInstallationRequest(installations.appConfig);\n }\n\n if (entry.registrationStatus === RequestStatus.NOT_STARTED) {\n // The request timed out or failed in a different call. Try again.\n const { installationEntry, registrationPromise } =\n await getInstallationEntry(installations);\n\n if (registrationPromise) {\n return registrationPromise;\n } else {\n // if there is no registrationPromise, entry is registered.\n return installationEntry as RegisteredInstallationEntry;\n }\n }\n\n return entry;\n}\n\n/**\n * Called only if there is a CreateInstallation request in progress.\n *\n * Updates the InstallationEntry in the DB based on the status of the\n * CreateInstallation request.\n *\n * Returns the updated InstallationEntry.\n */\nfunction updateInstallationRequest(\n appConfig: AppConfig\n): Promise {\n return update(appConfig, oldEntry => {\n if (!oldEntry) {\n throw ERROR_FACTORY.create(ErrorCode.INSTALLATION_NOT_FOUND);\n }\n return clearTimedOutRequest(oldEntry);\n });\n}\n\nfunction clearTimedOutRequest(entry: InstallationEntry): InstallationEntry {\n if (hasInstallationRequestTimedOut(entry)) {\n return {\n fid: entry.fid,\n registrationStatus: RequestStatus.NOT_STARTED\n };\n }\n\n return entry;\n}\n\nfunction hasInstallationRequestTimedOut(\n installationEntry: InstallationEntry\n): boolean {\n return (\n installationEntry.registrationStatus === RequestStatus.IN_PROGRESS &&\n installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now()\n );\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { GenerateAuthTokenResponse } from '../interfaces/api-response';\nimport {\n CompletedAuthToken,\n RegisteredInstallationEntry\n} from '../interfaces/installation-entry';\nimport { PACKAGE_VERSION } from '../util/constants';\nimport {\n extractAuthTokenInfoFromResponse,\n getErrorFromResponse,\n getHeadersWithAuth,\n getInstallationsEndpoint,\n retryIfServerError\n} from './common';\nimport {\n FirebaseInstallationsImpl,\n AppConfig\n} from '../interfaces/installation-impl';\n\nexport async function generateAuthTokenRequest(\n { appConfig, heartbeatServiceProvider }: FirebaseInstallationsImpl,\n installationEntry: RegisteredInstallationEntry\n): Promise {\n const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\n\n const headers = getHeadersWithAuth(appConfig, installationEntry);\n\n // If heartbeat service exists, add the heartbeat string to the header.\n const heartbeatService = heartbeatServiceProvider.getImmediate({\n optional: true\n });\n if (heartbeatService) {\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers.append('x-firebase-client', heartbeatsHeader);\n }\n }\n\n const body = {\n installation: {\n sdkVersion: PACKAGE_VERSION,\n appId: appConfig.appId\n }\n };\n\n const request: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify(body)\n };\n\n const response = await retryIfServerError(() => fetch(endpoint, request));\n if (response.ok) {\n const responseValue: GenerateAuthTokenResponse = await response.json();\n const completedAuthToken: CompletedAuthToken =\n extractAuthTokenInfoFromResponse(responseValue);\n return completedAuthToken;\n } else {\n throw await getErrorFromResponse('Generate Auth Token', response);\n }\n}\n\nfunction getGenerateAuthTokenEndpoint(\n appConfig: AppConfig,\n { fid }: RegisteredInstallationEntry\n): string {\n return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { generateAuthTokenRequest } from '../functions/generate-auth-token-request';\nimport {\n AppConfig,\n FirebaseInstallationsImpl\n} from '../interfaces/installation-impl';\nimport {\n AuthToken,\n CompletedAuthToken,\n InProgressAuthToken,\n InstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { PENDING_TIMEOUT_MS, TOKEN_EXPIRATION_BUFFER } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode, isServerError } from '../util/errors';\nimport { sleep } from '../util/sleep';\nimport { remove, set, update } from './idb-manager';\n\n/**\n * Returns a valid authentication token for the installation. Generates a new\n * token if one doesn't exist, is expired or about to expire.\n *\n * Should only be called if the Firebase Installation is registered.\n */\nexport async function refreshAuthToken(\n installations: FirebaseInstallationsImpl,\n forceRefresh = false\n): Promise {\n let tokenPromise: Promise | undefined;\n const entry = await update(installations.appConfig, oldEntry => {\n if (!isEntryRegistered(oldEntry)) {\n throw ERROR_FACTORY.create(ErrorCode.NOT_REGISTERED);\n }\n\n const oldAuthToken = oldEntry.authToken;\n if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {\n // There is a valid token in the DB.\n return oldEntry;\n } else if (oldAuthToken.requestStatus === RequestStatus.IN_PROGRESS) {\n // There already is a token request in progress.\n tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);\n return oldEntry;\n } else {\n // No token or token expired.\n if (!navigator.onLine) {\n throw ERROR_FACTORY.create(ErrorCode.APP_OFFLINE);\n }\n\n const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\n tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);\n return inProgressEntry;\n }\n });\n\n const authToken = tokenPromise\n ? await tokenPromise\n : (entry.authToken as CompletedAuthToken);\n return authToken;\n}\n\n/**\n * Call only if FID is registered and Auth Token request is in progress.\n *\n * Waits until the current pending request finishes. If the request times out,\n * tries once in this thread as well.\n */\nasync function waitUntilAuthTokenRequest(\n installations: FirebaseInstallationsImpl,\n forceRefresh: boolean\n): Promise {\n // Unfortunately, there is no way of reliably observing when a value in\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\n // so we need to poll.\n\n let entry = await updateAuthTokenRequest(installations.appConfig);\n while (entry.authToken.requestStatus === RequestStatus.IN_PROGRESS) {\n // generateAuthToken still in progress.\n await sleep(100);\n\n entry = await updateAuthTokenRequest(installations.appConfig);\n }\n\n const authToken = entry.authToken;\n if (authToken.requestStatus === RequestStatus.NOT_STARTED) {\n // The request timed out or failed in a different call. Try again.\n return refreshAuthToken(installations, forceRefresh);\n } else {\n return authToken;\n }\n}\n\n/**\n * Called only if there is a GenerateAuthToken request in progress.\n *\n * Updates the InstallationEntry in the DB based on the status of the\n * GenerateAuthToken request.\n *\n * Returns the updated InstallationEntry.\n */\nfunction updateAuthTokenRequest(\n appConfig: AppConfig\n): Promise {\n return update(appConfig, oldEntry => {\n if (!isEntryRegistered(oldEntry)) {\n throw ERROR_FACTORY.create(ErrorCode.NOT_REGISTERED);\n }\n\n const oldAuthToken = oldEntry.authToken;\n if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\n return {\n ...oldEntry,\n authToken: { requestStatus: RequestStatus.NOT_STARTED }\n };\n }\n\n return oldEntry;\n });\n}\n\nasync function fetchAuthTokenFromServer(\n installations: FirebaseInstallationsImpl,\n installationEntry: RegisteredInstallationEntry\n): Promise {\n try {\n const authToken = await generateAuthTokenRequest(\n installations,\n installationEntry\n );\n const updatedInstallationEntry: RegisteredInstallationEntry = {\n ...installationEntry,\n authToken\n };\n await set(installations.appConfig, updatedInstallationEntry);\n return authToken;\n } catch (e) {\n if (\n isServerError(e) &&\n (e.customData.serverCode === 401 || e.customData.serverCode === 404)\n ) {\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\n // Generate a new ID next time.\n await remove(installations.appConfig);\n } else {\n const updatedInstallationEntry: RegisteredInstallationEntry = {\n ...installationEntry,\n authToken: { requestStatus: RequestStatus.NOT_STARTED }\n };\n await set(installations.appConfig, updatedInstallationEntry);\n }\n throw e;\n }\n}\n\nfunction isEntryRegistered(\n installationEntry: InstallationEntry | undefined\n): installationEntry is RegisteredInstallationEntry {\n return (\n installationEntry !== undefined &&\n installationEntry.registrationStatus === RequestStatus.COMPLETED\n );\n}\n\nfunction isAuthTokenValid(authToken: AuthToken): boolean {\n return (\n authToken.requestStatus === RequestStatus.COMPLETED &&\n !isAuthTokenExpired(authToken)\n );\n}\n\nfunction isAuthTokenExpired(authToken: CompletedAuthToken): boolean {\n const now = Date.now();\n return (\n now < authToken.creationTime ||\n authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER\n );\n}\n\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\nfunction makeAuthTokenRequestInProgressEntry(\n oldEntry: RegisteredInstallationEntry\n): RegisteredInstallationEntry {\n const inProgressAuthToken: InProgressAuthToken = {\n requestStatus: RequestStatus.IN_PROGRESS,\n requestTime: Date.now()\n };\n return {\n ...oldEntry,\n authToken: inProgressAuthToken\n };\n}\n\nfunction hasAuthTokenRequestTimedOut(authToken: AuthToken): boolean {\n return (\n authToken.requestStatus === RequestStatus.IN_PROGRESS &&\n authToken.requestTime + PENDING_TIMEOUT_MS < Date.now()\n );\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Creates a Firebase Installation if there isn't one for the app and\n * returns the Installation ID.\n * @param installations - The `Installations` instance.\n *\n * @public\n */\nexport async function getId(installations: Installations): Promise {\n const installationsImpl = installations as FirebaseInstallationsImpl;\n const { installationEntry, registrationPromise } = await getInstallationEntry(\n installationsImpl\n );\n\n if (registrationPromise) {\n registrationPromise.catch(console.error);\n } else {\n // If the installation is already registered, update the authentication\n // token if needed.\n refreshAuthToken(installationsImpl).catch(console.error);\n }\n\n return installationEntry.fid;\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Returns a Firebase Installations auth token, identifying the current\n * Firebase Installation.\n * @param installations - The `Installations` instance.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getToken(\n installations: Installations,\n forceRefresh = false\n): Promise {\n const installationsImpl = installations as FirebaseInstallationsImpl;\n await completeInstallationRegistration(installationsImpl);\n\n // At this point we either have a Registered Installation in the DB, or we've\n // already thrown an error.\n const authToken = await refreshAuthToken(installationsImpl, forceRefresh);\n return authToken.token;\n}\n\nasync function completeInstallationRegistration(\n installations: FirebaseInstallationsImpl\n): Promise {\n const { registrationPromise } = await getInstallationEntry(installations);\n\n if (registrationPromise) {\n // A createInstallation request is in progress. Wait until it finishes.\n await registrationPromise;\n }\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { AppConfig } from '../interfaces/installation-impl';\nimport { RegisteredInstallationEntry } from '../interfaces/installation-entry';\nimport {\n getErrorFromResponse,\n getHeadersWithAuth,\n getInstallationsEndpoint,\n retryIfServerError\n} from './common';\n\nexport async function deleteInstallationRequest(\n appConfig: AppConfig,\n installationEntry: RegisteredInstallationEntry\n): Promise {\n const endpoint = getDeleteEndpoint(appConfig, installationEntry);\n\n const headers = getHeadersWithAuth(appConfig, installationEntry);\n const request: RequestInit = {\n method: 'DELETE',\n headers\n };\n\n const response = await retryIfServerError(() => fetch(endpoint, request));\n if (!response.ok) {\n throw await getErrorFromResponse('Delete Installation', response);\n }\n}\n\nfunction getDeleteEndpoint(\n appConfig: AppConfig,\n { fid }: RegisteredInstallationEntry\n): string {\n return `${getInstallationsEndpoint(appConfig)}/${fid}`;\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { deleteInstallationRequest } from '../functions/delete-installation-request';\nimport { remove, update } from '../helpers/idb-manager';\nimport { RequestStatus } from '../interfaces/installation-entry';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Deletes the Firebase Installation and all associated data.\n * @param installations - The `Installations` instance.\n *\n * @public\n */\nexport async function deleteInstallations(\n installations: Installations\n): Promise {\n const { appConfig } = installations as FirebaseInstallationsImpl;\n\n const entry = await update(appConfig, oldEntry => {\n if (oldEntry && oldEntry.registrationStatus === RequestStatus.NOT_STARTED) {\n // Delete the unregistered entry without sending a deleteInstallation request.\n return undefined;\n }\n return oldEntry;\n });\n\n if (entry) {\n if (entry.registrationStatus === RequestStatus.IN_PROGRESS) {\n // Can't delete while trying to register.\n throw ERROR_FACTORY.create(ErrorCode.DELETE_PENDING_REGISTRATION);\n } else if (entry.registrationStatus === RequestStatus.COMPLETED) {\n if (!navigator.onLine) {\n throw ERROR_FACTORY.create(ErrorCode.APP_OFFLINE);\n } else {\n await deleteInstallationRequest(appConfig, entry);\n await remove(appConfig);\n }\n }\n }\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { addCallback, removeCallback } from '../helpers/fid-changed';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * An user defined callback function that gets called when Installations ID changes.\n *\n * @public\n */\nexport type IdChangeCallbackFn = (installationId: string) => void;\n/**\n * Unsubscribe a callback function previously added via {@link IdChangeCallbackFn}.\n *\n * @public\n */\nexport type IdChangeUnsubscribeFn = () => void;\n\n/**\n * Sets a new callback that will get called when Installation ID changes.\n * Returns an unsubscribe function that will remove the callback when called.\n * @param installations - The `Installations` instance.\n * @param callback - The callback function that is invoked when FID changes.\n * @returns A function that can be called to unsubscribe.\n *\n * @public\n */\nexport function onIdChange(\n installations: Installations,\n callback: IdChangeCallbackFn\n): IdChangeUnsubscribeFn {\n const { appConfig } = installations as FirebaseInstallationsImpl;\n\n addCallback(appConfig, callback);\n return () => {\n removeCallback(appConfig, callback);\n };\n}\n", "/**\n * @license\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 * http://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 { FirebaseApp, getApp, _getProvider } from '@firebase/app';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Returns an instance of {@link Installations} associated with the given\n * {@link @firebase/app#FirebaseApp} instance.\n * @param app - The {@link @firebase/app#FirebaseApp} instance.\n *\n * @public\n */\nexport function getInstallations(app: FirebaseApp = getApp()): Installations {\n const installationsImpl = _getProvider(app, 'installations').getImmediate();\n return installationsImpl;\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { FirebaseApp, FirebaseOptions } from '@firebase/app';\nimport { FirebaseError } from '@firebase/util';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nexport function extractAppConfig(app: FirebaseApp): AppConfig {\n if (!app || !app.options) {\n throw getMissingValueError('App Configuration');\n }\n\n if (!app.name) {\n throw getMissingValueError('App Name');\n }\n\n // Required app config keys\n const configKeys: Array = [\n 'projectId',\n 'apiKey',\n 'appId'\n ];\n\n for (const keyName of configKeys) {\n if (!app.options[keyName]) {\n throw getMissingValueError(keyName);\n }\n }\n\n return {\n appName: app.name,\n projectId: app.options.projectId!,\n apiKey: app.options.apiKey!,\n appId: app.options.appId!\n };\n}\n\nfunction getMissingValueError(valueName: string): FirebaseError {\n return ERROR_FACTORY.create(ErrorCode.MISSING_APP_CONFIG_VALUES, {\n valueName\n });\n}\n", "/**\n * @license\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 * http://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 { _registerComponent, _getProvider } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstanceFactory,\n ComponentContainer\n} from '@firebase/component';\nimport { getId, getToken } from '../api/index';\nimport { _FirebaseInstallationsInternal } from '../interfaces/public-types';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { extractAppConfig } from '../helpers/extract-app-config';\n\nconst INSTALLATIONS_NAME = 'installations';\nconst INSTALLATIONS_NAME_INTERNAL = 'installations-internal';\n\nconst publicFactory: InstanceFactory<'installations'> = (\n container: ComponentContainer\n) => {\n const app = container.getProvider('app').getImmediate();\n // Throws if app isn't configured properly.\n const appConfig = extractAppConfig(app);\n const heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n\n const installationsImpl: FirebaseInstallationsImpl = {\n app,\n appConfig,\n heartbeatServiceProvider,\n _delete: () => Promise.resolve()\n };\n return installationsImpl;\n};\n\nconst internalFactory: InstanceFactory<'installations-internal'> = (\n container: ComponentContainer\n) => {\n const app = container.getProvider('app').getImmediate();\n // Internal FIS instance relies on public FIS instance.\n const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();\n\n const installationsInternal: _FirebaseInstallationsInternal = {\n getId: () => getId(installations),\n getToken: (forceRefresh?: boolean) => getToken(installations, forceRefresh)\n };\n return installationsInternal;\n};\n\nexport function registerInstallations(): void {\n _registerComponent(\n new Component(INSTALLATIONS_NAME, publicFactory, ComponentType.PUBLIC)\n );\n _registerComponent(\n new Component(\n INSTALLATIONS_NAME_INTERNAL,\n internalFactory,\n ComponentType.PRIVATE\n )\n );\n}\n", "/**\n * The Firebase Installations Web SDK.\n * This SDK does not work in a Node.js environment.\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 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 * http://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 { registerInstallations } from './functions/config';\nimport { registerVersion } from '@firebase/app';\nimport { name, version } from '../package.json';\n\nexport * from './api';\nexport * from './interfaces/public-types';\n\nregisterInstallations();\nregisterVersion(name, version);\n// BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\nregisterVersion(name, version, '__BUILD_TARGET__');\n", "/**\n * @license\n * Copyright 2019 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 * http://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\nexport const DEFAULT_SW_PATH = '/firebase-messaging-sw.js';\nexport const DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';\n\nexport const DEFAULT_VAPID_KEY =\n 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';\n\nexport const ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';\n\n/** Key of FCM Payload in Notification's data field. */\nexport const FCM_MSG = 'FCM_MSG';\n\nexport const CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';\nexport const CONSOLE_CAMPAIGN_NAME = 'google.c.a.c_l';\nexport const CONSOLE_CAMPAIGN_TIME = 'google.c.a.ts';\n/** Set to '1' if Analytics is enabled for the campaign */\nexport const CONSOLE_CAMPAIGN_ANALYTICS_ENABLED = 'google.c.a.e';\nexport const TAG = 'FirebaseMessaging: ';\nexport const MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST = 1000;\nexport const MAX_RETRIES = 3;\nexport const LOG_INTERVAL_IN_MS = 86400000; //24 hour\nexport const DEFAULT_BACKOFF_TIME_MS = 5000;\nexport const DEFAULT_REGISTRATION_TIMEOUT = 10000;\n\n// FCM log source name registered at Firelog: 'FCM_CLIENT_EVENT_LOGGING'. It uniquely identifies\n// FCM's logging configuration.\nexport const FCM_LOG_SOURCE = 1249;\n\n// Defined as in proto/messaging_event.proto. Neglecting fields that are supported.\nexport const SDK_PLATFORM_WEB = 3;\nexport const EVENT_MESSAGE_DELIVERED = 1;\n\nexport enum MessageType {\n DATA_MESSAGE = 1,\n DISPLAY_NOTIFICATION = 3\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */\n\nimport {\n CONSOLE_CAMPAIGN_ANALYTICS_ENABLED,\n CONSOLE_CAMPAIGN_ID,\n CONSOLE_CAMPAIGN_NAME,\n CONSOLE_CAMPAIGN_TIME\n} from '../util/constants';\n\nexport interface MessagePayloadInternal {\n notification?: NotificationPayloadInternal;\n data?: unknown;\n fcmOptions?: FcmOptionsInternal;\n messageType?: MessageType;\n isFirebaseMessaging?: boolean;\n from: string;\n fcmMessageId: string;\n productId: number;\n // eslint-disable-next-line camelcase\n collapse_key: string;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Notification/actions\ninterface NotificationAction {\n action: string;\n icon?: string;\n title: string;\n}\n\n/**\n * This interface defines experimental properties of NotificationOptions, that are not part of\n * the interface in the generated DOM types at https://github.com/microsoft/TypeScript-DOM-lib-generator/blob/179bdd84a944933a3103f29c2274c9f5a857b693/baselines/dom.generated.d.ts#L1012\n * https://developer.mozilla.org/en-US/docs/Web/API/Notification\n */\ninterface NotificationOptionsExperimental extends NotificationOptions {\n readonly maxActions?: number;\n readonly actions?: NotificationAction[];\n readonly image?: string;\n readonly renotify?: boolean;\n readonly timestamp?: EpochTimeStamp;\n readonly vibrate?: VibratePattern;\n}\n\nexport interface NotificationPayloadInternal\n extends NotificationOptionsExperimental {\n title: string;\n // Supported in the Legacy Send API.\n // See:https://firebase.google.com/docs/cloud-messaging/xmpp-server-ref.\n // eslint-disable-next-line camelcase\n click_action?: string;\n icon?: string;\n}\n\n// Defined in\n// https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushfcmoptions. Note\n// that the keys are sent to the clients in snake cases which we need to convert to camel so it can\n// be exposed as a type to match the Firebase API convention.\nexport interface FcmOptionsInternal {\n link?: string;\n\n // eslint-disable-next-line camelcase\n analytics_label?: string;\n}\n\nexport enum MessageType {\n PUSH_RECEIVED = 'push-received',\n NOTIFICATION_CLICKED = 'notification-clicked'\n}\n\n/** Additional data of a message sent from the FN Console. */\nexport interface ConsoleMessageData {\n [CONSOLE_CAMPAIGN_ID]: string;\n [CONSOLE_CAMPAIGN_TIME]: string;\n [CONSOLE_CAMPAIGN_NAME]?: string;\n [CONSOLE_CAMPAIGN_ANALYTICS_ENABLED]?: '1';\n}\n", "/**\n * @license\n * Copyright 2017 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 * http://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\nexport function arrayToBase64(array: Uint8Array | ArrayBuffer): string {\n const uint8Array = new Uint8Array(array);\n const base64String = btoa(String.fromCharCode(...uint8Array));\n return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n\nexport function base64ToArray(base64String: string): Uint8Array {\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4);\n const base64 = (base64String + padding)\n .replace(/\\-/g, '+')\n .replace(/_/g, '/');\n\n const rawData = atob(base64);\n const outputArray = new Uint8Array(rawData.length);\n\n for (let i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i);\n }\n return outputArray;\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { deleteDB, openDB } from 'idb';\n\nimport { TokenDetails } from '../interfaces/token-details';\nimport { arrayToBase64 } from './array-base64-translator';\n\n// https://github.com/firebase/firebase-js-sdk/blob/7857c212f944a2a9eb421fd4cb7370181bc034b5/packages/messaging/src/interfaces/token-details.ts\nexport interface V2TokenDetails {\n fcmToken: string;\n swScope: string;\n vapidKey: string | Uint8Array;\n subscription: PushSubscription;\n fcmSenderId: string;\n fcmPushSet: string;\n createTime?: number;\n endpoint?: string;\n auth?: string;\n p256dh?: string;\n}\n\n// https://github.com/firebase/firebase-js-sdk/blob/6b5b15ce4ea3df5df5df8a8b33a4e41e249c7715/packages/messaging/src/interfaces/token-details.ts\nexport interface V3TokenDetails {\n fcmToken: string;\n swScope: string;\n vapidKey: Uint8Array;\n fcmSenderId: string;\n fcmPushSet: string;\n endpoint: string;\n auth: ArrayBuffer;\n p256dh: ArrayBuffer;\n createTime: number;\n}\n\n// https://github.com/firebase/firebase-js-sdk/blob/9567dba664732f681fa7fe60f5b7032bb1daf4c9/packages/messaging/src/interfaces/token-details.ts\nexport interface V4TokenDetails {\n fcmToken: string;\n swScope: string;\n vapidKey: Uint8Array;\n fcmSenderId: string;\n endpoint: string;\n auth: ArrayBufferLike;\n p256dh: ArrayBufferLike;\n createTime: number;\n}\n\nconst OLD_DB_NAME = 'fcm_token_details_db';\n/**\n * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade\n * callback is called for all versions of the old DB.\n */\nconst OLD_DB_VERSION = 5;\nconst OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\n\nexport async function migrateOldDatabase(\n senderId: string\n): Promise {\n if ('databases' in indexedDB) {\n // indexedDb.databases() is an IndexedDB v3 API and does not exist in all browsers. TODO: Remove\n // typecast when it lands in TS types.\n const databases = await (\n indexedDB as {\n databases(): Promise>;\n }\n ).databases();\n const dbNames = databases.map(db => db.name);\n\n if (!dbNames.includes(OLD_DB_NAME)) {\n // old DB didn't exist, no need to open.\n return null;\n }\n }\n\n let tokenDetails: TokenDetails | null = null;\n\n const db = await openDB(OLD_DB_NAME, OLD_DB_VERSION, {\n upgrade: async (db, oldVersion, newVersion, upgradeTransaction) => {\n if (oldVersion < 2) {\n // Database too old, skip migration.\n return;\n }\n\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\n // Database did not exist. Nothing to do.\n return;\n }\n\n const objectStore = upgradeTransaction.objectStore(OLD_OBJECT_STORE_NAME);\n const value = await objectStore.index('fcmSenderId').get(senderId);\n await objectStore.clear();\n\n if (!value) {\n // No entry in the database, nothing to migrate.\n return;\n }\n\n if (oldVersion === 2) {\n const oldDetails = value as V2TokenDetails;\n\n if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {\n return;\n }\n\n tokenDetails = {\n token: oldDetails.fcmToken,\n createTime: oldDetails.createTime ?? Date.now(),\n subscriptionOptions: {\n auth: oldDetails.auth,\n p256dh: oldDetails.p256dh,\n endpoint: oldDetails.endpoint,\n swScope: oldDetails.swScope,\n vapidKey:\n typeof oldDetails.vapidKey === 'string'\n ? oldDetails.vapidKey\n : arrayToBase64(oldDetails.vapidKey)\n }\n };\n } else if (oldVersion === 3) {\n const oldDetails = value as V3TokenDetails;\n\n tokenDetails = {\n token: oldDetails.fcmToken,\n createTime: oldDetails.createTime,\n subscriptionOptions: {\n auth: arrayToBase64(oldDetails.auth),\n p256dh: arrayToBase64(oldDetails.p256dh),\n endpoint: oldDetails.endpoint,\n swScope: oldDetails.swScope,\n vapidKey: arrayToBase64(oldDetails.vapidKey)\n }\n };\n } else if (oldVersion === 4) {\n const oldDetails = value as V4TokenDetails;\n\n tokenDetails = {\n token: oldDetails.fcmToken,\n createTime: oldDetails.createTime,\n subscriptionOptions: {\n auth: arrayToBase64(oldDetails.auth),\n p256dh: arrayToBase64(oldDetails.p256dh),\n endpoint: oldDetails.endpoint,\n swScope: oldDetails.swScope,\n vapidKey: arrayToBase64(oldDetails.vapidKey)\n }\n };\n }\n }\n });\n db.close();\n\n // Delete all old databases.\n await deleteDB(OLD_DB_NAME);\n await deleteDB('fcm_vapid_details_db');\n await deleteDB('undefined');\n\n return checkTokenDetails(tokenDetails) ? tokenDetails : null;\n}\n\nfunction checkTokenDetails(\n tokenDetails: TokenDetails | null\n): tokenDetails is TokenDetails {\n if (!tokenDetails || !tokenDetails.subscriptionOptions) {\n return false;\n }\n const { subscriptionOptions } = tokenDetails;\n return (\n typeof tokenDetails.createTime === 'number' &&\n tokenDetails.createTime > 0 &&\n typeof tokenDetails.token === 'string' &&\n tokenDetails.token.length > 0 &&\n typeof subscriptionOptions.auth === 'string' &&\n subscriptionOptions.auth.length > 0 &&\n typeof subscriptionOptions.p256dh === 'string' &&\n subscriptionOptions.p256dh.length > 0 &&\n typeof subscriptionOptions.endpoint === 'string' &&\n subscriptionOptions.endpoint.length > 0 &&\n typeof subscriptionOptions.swScope === 'string' &&\n subscriptionOptions.swScope.length > 0 &&\n typeof subscriptionOptions.vapidKey === 'string' &&\n subscriptionOptions.vapidKey.length > 0\n );\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { DBSchema, IDBPDatabase, deleteDB, openDB } from 'idb';\n\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\nimport { TokenDetails } from '../interfaces/token-details';\nimport { migrateOldDatabase } from '../helpers/migrate-old-database';\n\n// Exported for tests.\nexport const DATABASE_NAME = 'firebase-messaging-database';\nconst DATABASE_VERSION = 1;\nconst OBJECT_STORE_NAME = 'firebase-messaging-store';\n\ninterface MessagingDB extends DBSchema {\n 'firebase-messaging-store': {\n key: string;\n value: TokenDetails;\n };\n}\n\nlet dbPromise: Promise> | null = null;\nfunction getDbPromise(): Promise> {\n if (!dbPromise) {\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\n upgrade: (upgradeDb, oldVersion) => {\n // We don't use 'break' in this switch statement, the fall-through behavior is what we want,\n // because if there are multiple versions between the old version and the current version, we\n // want ALL the migrations that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (oldVersion) {\n case 0:\n upgradeDb.createObjectStore(OBJECT_STORE_NAME);\n }\n }\n });\n }\n return dbPromise;\n}\n\n/** Gets record(s) from the objectStore that match the given key. */\nexport async function dbGet(\n firebaseDependencies: FirebaseInternalDependencies\n): Promise {\n const key = getKey(firebaseDependencies);\n const db = await getDbPromise();\n const tokenDetails = (await db\n .transaction(OBJECT_STORE_NAME)\n .objectStore(OBJECT_STORE_NAME)\n .get(key)) as TokenDetails;\n\n if (tokenDetails) {\n return tokenDetails;\n } else {\n // Check if there is a tokenDetails object in the old DB.\n const oldTokenDetails = await migrateOldDatabase(\n firebaseDependencies.appConfig.senderId\n );\n if (oldTokenDetails) {\n await dbSet(firebaseDependencies, oldTokenDetails);\n return oldTokenDetails;\n }\n }\n}\n\n/** Assigns or overwrites the record for the given key with the given value. */\nexport async function dbSet(\n firebaseDependencies: FirebaseInternalDependencies,\n tokenDetails: TokenDetails\n): Promise {\n const key = getKey(firebaseDependencies);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key);\n await tx.done;\n return tokenDetails;\n}\n\n/** Removes record(s) from the objectStore that match the given key. */\nexport async function dbRemove(\n firebaseDependencies: FirebaseInternalDependencies\n): Promise {\n const key = getKey(firebaseDependencies);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\n await tx.done;\n}\n\n/** Deletes the DB. Useful for tests. */\nexport async function dbDelete(): Promise {\n if (dbPromise) {\n (await dbPromise).close();\n await deleteDB(DATABASE_NAME);\n dbPromise = null;\n }\n}\n\nfunction getKey({ appConfig }: FirebaseInternalDependencies): string {\n return appConfig.appId;\n}\n", "/**\n * @license\n * Copyright 2017 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 * http://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 { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum ErrorCode {\n MISSING_APP_CONFIG_VALUES = 'missing-app-config-values',\n AVAILABLE_IN_WINDOW = 'only-available-in-window',\n AVAILABLE_IN_SW = 'only-available-in-sw',\n PERMISSION_DEFAULT = 'permission-default',\n PERMISSION_BLOCKED = 'permission-blocked',\n UNSUPPORTED_BROWSER = 'unsupported-browser',\n INDEXED_DB_UNSUPPORTED = 'indexed-db-unsupported',\n FAILED_DEFAULT_REGISTRATION = 'failed-service-worker-registration',\n TOKEN_SUBSCRIBE_FAILED = 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN = 'token-subscribe-no-token',\n TOKEN_UNSUBSCRIBE_FAILED = 'token-unsubscribe-failed',\n TOKEN_UPDATE_FAILED = 'token-update-failed',\n TOKEN_UPDATE_NO_TOKEN = 'token-update-no-token',\n INVALID_BG_HANDLER = 'invalid-bg-handler',\n USE_SW_AFTER_GET_TOKEN = 'use-sw-after-get-token',\n INVALID_SW_REGISTRATION = 'invalid-sw-registration',\n USE_VAPID_KEY_AFTER_GET_TOKEN = 'use-vapid-key-after-get-token',\n INVALID_VAPID_KEY = 'invalid-vapid-key'\n}\n\nexport const ERROR_MAP: ErrorMap = {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]:\n 'Missing App configuration value: \"{$valueName}\"',\n [ErrorCode.AVAILABLE_IN_WINDOW]:\n 'This method is available in a Window context.',\n [ErrorCode.AVAILABLE_IN_SW]:\n 'This method is available in a service worker context.',\n [ErrorCode.PERMISSION_DEFAULT]:\n 'The notification permission was not granted and dismissed instead.',\n [ErrorCode.PERMISSION_BLOCKED]:\n 'The notification permission was not granted and blocked instead.',\n [ErrorCode.UNSUPPORTED_BROWSER]:\n \"This browser doesn't support the API's required to use the Firebase SDK.\",\n [ErrorCode.INDEXED_DB_UNSUPPORTED]:\n \"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)\",\n [ErrorCode.FAILED_DEFAULT_REGISTRATION]:\n 'We are unable to register the default service worker. {$browserErrorMessage}',\n [ErrorCode.TOKEN_SUBSCRIBE_FAILED]:\n 'A problem occurred while subscribing the user to FCM: {$errorInfo}',\n [ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN]:\n 'FCM returned no token when subscribing the user to push.',\n [ErrorCode.TOKEN_UNSUBSCRIBE_FAILED]:\n 'A problem occurred while unsubscribing the ' +\n 'user from FCM: {$errorInfo}',\n [ErrorCode.TOKEN_UPDATE_FAILED]:\n 'A problem occurred while updating the user from FCM: {$errorInfo}',\n [ErrorCode.TOKEN_UPDATE_NO_TOKEN]:\n 'FCM returned no token when updating the user to push.',\n [ErrorCode.USE_SW_AFTER_GET_TOKEN]:\n 'The useServiceWorker() method may only be called once and must be ' +\n 'called before calling getToken() to ensure your service worker is used.',\n [ErrorCode.INVALID_SW_REGISTRATION]:\n 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',\n [ErrorCode.INVALID_BG_HANDLER]:\n 'The input to setBackgroundMessageHandler() must be a function.',\n [ErrorCode.INVALID_VAPID_KEY]: 'The public VAPID key must be a string.',\n [ErrorCode.USE_VAPID_KEY_AFTER_GET_TOKEN]:\n 'The usePublicVapidKey() method may only be called once and must be ' +\n 'called before calling getToken() to ensure your VAPID key is used.'\n};\n\ninterface ErrorParams {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]: {\n valueName: string;\n };\n [ErrorCode.FAILED_DEFAULT_REGISTRATION]: { browserErrorMessage: string };\n [ErrorCode.TOKEN_SUBSCRIBE_FAILED]: { errorInfo: string };\n [ErrorCode.TOKEN_UNSUBSCRIBE_FAILED]: { errorInfo: string };\n [ErrorCode.TOKEN_UPDATE_FAILED]: { errorInfo: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory(\n 'messaging',\n 'Messaging',\n ERROR_MAP\n);\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { DEFAULT_VAPID_KEY, ENDPOINT } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { SubscriptionOptions, TokenDetails } from '../interfaces/token-details';\n\nimport { AppConfig } from '../interfaces/app-config';\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\n\nexport interface ApiResponse {\n token?: string;\n error?: { message: string };\n}\n\nexport interface ApiRequestBody {\n web: {\n endpoint: string;\n p256dh: string;\n auth: string;\n applicationPubKey?: string;\n };\n}\n\nexport async function requestGetToken(\n firebaseDependencies: FirebaseInternalDependencies,\n subscriptionOptions: SubscriptionOptions\n): Promise {\n const headers = await getHeaders(firebaseDependencies);\n const body = getBody(subscriptionOptions);\n\n const subscribeOptions = {\n method: 'POST',\n headers,\n body: JSON.stringify(body)\n };\n\n let responseData: ApiResponse;\n try {\n const response = await fetch(\n getEndpoint(firebaseDependencies.appConfig),\n subscribeOptions\n );\n responseData = await response.json();\n } catch (err) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_SUBSCRIBE_FAILED, {\n errorInfo: (err as Error)?.toString()\n });\n }\n\n if (responseData.error) {\n const message = responseData.error.message;\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_SUBSCRIBE_FAILED, {\n errorInfo: message\n });\n }\n\n if (!responseData.token) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n\n return responseData.token;\n}\n\nexport async function requestUpdateToken(\n firebaseDependencies: FirebaseInternalDependencies,\n tokenDetails: TokenDetails\n): Promise {\n const headers = await getHeaders(firebaseDependencies);\n const body = getBody(tokenDetails.subscriptionOptions!);\n\n const updateOptions = {\n method: 'PATCH',\n headers,\n body: JSON.stringify(body)\n };\n\n let responseData: ApiResponse;\n try {\n const response = await fetch(\n `${getEndpoint(firebaseDependencies.appConfig)}/${tokenDetails.token}`,\n updateOptions\n );\n responseData = await response.json();\n } catch (err) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UPDATE_FAILED, {\n errorInfo: (err as Error)?.toString()\n });\n }\n\n if (responseData.error) {\n const message = responseData.error.message;\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UPDATE_FAILED, {\n errorInfo: message\n });\n }\n\n if (!responseData.token) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UPDATE_NO_TOKEN);\n }\n\n return responseData.token;\n}\n\nexport async function requestDeleteToken(\n firebaseDependencies: FirebaseInternalDependencies,\n token: string\n): Promise {\n const headers = await getHeaders(firebaseDependencies);\n\n const unsubscribeOptions = {\n method: 'DELETE',\n headers\n };\n\n try {\n const response = await fetch(\n `${getEndpoint(firebaseDependencies.appConfig)}/${token}`,\n unsubscribeOptions\n );\n const responseData: ApiResponse = await response.json();\n if (responseData.error) {\n const message = responseData.error.message;\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED, {\n errorInfo: message\n });\n }\n } catch (err) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED, {\n errorInfo: (err as Error)?.toString()\n });\n }\n}\n\nfunction getEndpoint({ projectId }: AppConfig): string {\n return `${ENDPOINT}/projects/${projectId!}/registrations`;\n}\n\nasync function getHeaders({\n appConfig,\n installations\n}: FirebaseInternalDependencies): Promise {\n const authToken = await installations.getToken();\n\n return new Headers({\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-goog-api-key': appConfig.apiKey!,\n 'x-goog-firebase-installations-auth': `FIS ${authToken}`\n });\n}\n\nfunction getBody({\n p256dh,\n auth,\n endpoint,\n vapidKey\n}: SubscriptionOptions): ApiRequestBody {\n const body: ApiRequestBody = {\n web: {\n endpoint,\n auth,\n p256dh\n }\n };\n\n if (vapidKey !== DEFAULT_VAPID_KEY) {\n body.web.applicationPubKey = vapidKey;\n }\n\n return body;\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { SubscriptionOptions, TokenDetails } from '../interfaces/token-details';\nimport {\n arrayToBase64,\n base64ToArray\n} from '../helpers/array-base64-translator';\nimport { dbGet, dbRemove, dbSet } from './idb-manager';\nimport {\n requestDeleteToken,\n requestGetToken,\n requestUpdateToken\n} from './requests';\n\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\nimport { MessagingService } from '../messaging-service';\n\n// UpdateRegistration will be called once every week.\nconst TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\nexport async function getTokenInternal(\n messaging: MessagingService\n): Promise {\n const pushSubscription = await getPushSubscription(\n messaging.swRegistration!,\n messaging.vapidKey!\n );\n\n const subscriptionOptions: SubscriptionOptions = {\n vapidKey: messaging.vapidKey!,\n swScope: messaging.swRegistration!.scope,\n endpoint: pushSubscription.endpoint,\n auth: arrayToBase64(pushSubscription.getKey('auth')!),\n p256dh: arrayToBase64(pushSubscription.getKey('p256dh')!)\n };\n\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\n if (!tokenDetails) {\n // No token, get a new one.\n return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\n } else if (\n !isTokenValid(tokenDetails.subscriptionOptions!, subscriptionOptions)\n ) {\n // Invalid token, get a new one.\n try {\n await requestDeleteToken(\n messaging.firebaseDependencies!,\n tokenDetails.token\n );\n } catch (e) {\n // Suppress errors because of #2364\n console.warn(e);\n }\n\n return getNewToken(messaging.firebaseDependencies!, subscriptionOptions);\n } else if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {\n // Weekly token refresh\n return updateToken(messaging, {\n token: tokenDetails.token,\n createTime: Date.now(),\n subscriptionOptions\n });\n } else {\n // Valid token, nothing to do.\n return tokenDetails.token;\n }\n}\n\n/**\n * This method deletes the token from the database, unsubscribes the token from FCM, and unregisters\n * the push subscription if it exists.\n */\nexport async function deleteTokenInternal(\n messaging: MessagingService\n): Promise {\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\n if (tokenDetails) {\n await requestDeleteToken(\n messaging.firebaseDependencies,\n tokenDetails.token\n );\n await dbRemove(messaging.firebaseDependencies);\n }\n\n // Unsubscribe from the push subscription.\n const pushSubscription =\n await messaging.swRegistration!.pushManager.getSubscription();\n if (pushSubscription) {\n return pushSubscription.unsubscribe();\n }\n\n // If there's no SW, consider it a success.\n return true;\n}\n\nasync function updateToken(\n messaging: MessagingService,\n tokenDetails: TokenDetails\n): Promise {\n try {\n const updatedToken = await requestUpdateToken(\n messaging.firebaseDependencies,\n tokenDetails\n );\n\n const updatedTokenDetails: TokenDetails = {\n ...tokenDetails,\n token: updatedToken,\n createTime: Date.now()\n };\n\n await dbSet(messaging.firebaseDependencies, updatedTokenDetails);\n return updatedToken;\n } catch (e) {\n throw e;\n }\n}\n\nasync function getNewToken(\n firebaseDependencies: FirebaseInternalDependencies,\n subscriptionOptions: SubscriptionOptions\n): Promise {\n const token = await requestGetToken(\n firebaseDependencies,\n subscriptionOptions\n );\n const tokenDetails: TokenDetails = {\n token,\n createTime: Date.now(),\n subscriptionOptions\n };\n await dbSet(firebaseDependencies, tokenDetails);\n return tokenDetails.token;\n}\n\n/**\n * Gets a PushSubscription for the current user.\n */\nasync function getPushSubscription(\n swRegistration: ServiceWorkerRegistration,\n vapidKey: string\n): Promise {\n const subscription = await swRegistration.pushManager.getSubscription();\n if (subscription) {\n return subscription;\n }\n\n return swRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key\n // submitted to pushManager#subscribe must be of type Uint8Array.\n applicationServerKey: base64ToArray(vapidKey)\n });\n}\n\n/**\n * Checks if the saved tokenDetails object matches the configuration provided.\n */\nfunction isTokenValid(\n dbOptions: SubscriptionOptions,\n currentOptions: SubscriptionOptions\n): boolean {\n const isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;\n const isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;\n const isAuthEqual = currentOptions.auth === dbOptions.auth;\n const isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;\n\n return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;\n}\n", "/**\n * @license\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 * http://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 { MessagePayload } from '../interfaces/public-types';\nimport { MessagePayloadInternal } from '../interfaces/internal-message-payload';\n\nexport function externalizePayload(\n internalPayload: MessagePayloadInternal\n): MessagePayload {\n const payload: MessagePayload = {\n from: internalPayload.from,\n // eslint-disable-next-line camelcase\n collapseKey: internalPayload.collapse_key,\n // eslint-disable-next-line camelcase\n messageId: internalPayload.fcmMessageId\n } as MessagePayload;\n\n propagateNotificationPayload(payload, internalPayload);\n propagateDataPayload(payload, internalPayload);\n propagateFcmOptions(payload, internalPayload);\n\n return payload;\n}\n\nfunction propagateNotificationPayload(\n payload: MessagePayload,\n messagePayloadInternal: MessagePayloadInternal\n): void {\n if (!messagePayloadInternal.notification) {\n return;\n }\n\n payload.notification = {};\n\n const title = messagePayloadInternal.notification!.title;\n if (!!title) {\n payload.notification!.title = title;\n }\n\n const body = messagePayloadInternal.notification!.body;\n if (!!body) {\n payload.notification!.body = body;\n }\n\n const image = messagePayloadInternal.notification!.image;\n if (!!image) {\n payload.notification!.image = image;\n }\n\n const icon = messagePayloadInternal.notification!.icon;\n if (!!icon) {\n payload.notification!.icon = icon;\n }\n}\n\nfunction propagateDataPayload(\n payload: MessagePayload,\n messagePayloadInternal: MessagePayloadInternal\n): void {\n if (!messagePayloadInternal.data) {\n return;\n }\n\n payload.data = messagePayloadInternal.data as { [key: string]: string };\n}\n\nfunction propagateFcmOptions(\n payload: MessagePayload,\n messagePayloadInternal: MessagePayloadInternal\n): void {\n // fcmOptions.link value is written into notification.click_action. see more in b/232072111\n if (\n !messagePayloadInternal.fcmOptions &&\n !messagePayloadInternal.notification?.click_action\n ) {\n return;\n }\n\n payload.fcmOptions = {};\n\n const link =\n messagePayloadInternal.fcmOptions?.link ??\n messagePayloadInternal.notification?.click_action;\n\n if (!!link) {\n payload.fcmOptions!.link = link;\n }\n\n // eslint-disable-next-line camelcase\n const analyticsLabel = messagePayloadInternal.fcmOptions?.analytics_label;\n if (!!analyticsLabel) {\n payload.fcmOptions!.analyticsLabel = analyticsLabel;\n }\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { CONSOLE_CAMPAIGN_ID } from '../util/constants';\nimport { ConsoleMessageData } from '../interfaces/internal-message-payload';\n\nexport function isConsoleMessage(data: unknown): data is ConsoleMessageData {\n // This message has a campaign ID, meaning it was sent using the Firebase Console.\n return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 {\n DEFAULT_BACKOFF_TIME_MS,\n EVENT_MESSAGE_DELIVERED,\n FCM_LOG_SOURCE,\n LOG_INTERVAL_IN_MS,\n MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST,\n MAX_RETRIES,\n MessageType,\n SDK_PLATFORM_WEB\n} from '../util/constants';\nimport {\n FcmEvent,\n LogEvent,\n LogRequest,\n LogResponse,\n ComplianceData\n} from '../interfaces/logging-types';\n\nimport { MessagePayloadInternal } from '../interfaces/internal-message-payload';\nimport { MessagingService } from '../messaging-service';\n\nconst LOG_ENDPOINT = 'https://play.google.com/log?format=json_proto3';\n\nconst FCM_TRANSPORT_KEY = _mergeStrings(\n 'AzSCbw63g1R0nCw85jG8',\n 'Iaya3yLKwmgvh7cF0q4'\n);\n\nexport function startLoggingService(messaging: MessagingService): void {\n if (!messaging.isLogServiceStarted) {\n _processQueue(messaging, LOG_INTERVAL_IN_MS);\n messaging.isLogServiceStarted = true;\n }\n}\n\n/**\n *\n * @param messaging the messaging instance.\n * @param offsetInMs this method execute after `offsetInMs` elapsed .\n */\nexport function _processQueue(\n messaging: MessagingService,\n offsetInMs: number\n): void {\n setTimeout(async () => {\n if (!messaging.deliveryMetricsExportedToBigQueryEnabled) {\n // flush events and terminate logging service\n messaging.logEvents = [];\n messaging.isLogServiceStarted = false;\n\n return;\n }\n\n if (!messaging.logEvents.length) {\n return _processQueue(messaging, LOG_INTERVAL_IN_MS);\n }\n\n await _dispatchLogEvents(messaging);\n }, offsetInMs);\n}\n\nexport async function _dispatchLogEvents(\n messaging: MessagingService\n): Promise {\n for (\n let i = 0, n = messaging.logEvents.length;\n i < n;\n i += MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST\n ) {\n const logRequest = _createLogRequest(\n messaging.logEvents.slice(i, i + MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST)\n );\n\n let retryCount = 0,\n response = {} as Response;\n\n do {\n try {\n response = await fetch(\n LOG_ENDPOINT.concat('&key=', FCM_TRANSPORT_KEY),\n {\n method: 'POST',\n body: JSON.stringify(logRequest)\n }\n );\n\n // don't retry on 200s or non retriable errors\n if (response.ok || (!response.ok && !isRetriableError(response))) {\n break;\n }\n\n if (!response.ok && isRetriableError(response)) {\n // rethrow to retry with quota\n throw new Error(\n 'a retriable Non-200 code is returned in fetch to Firelog endpoint. Retry'\n );\n }\n } catch (error) {\n const isLastAttempt = retryCount === MAX_RETRIES;\n if (isLastAttempt) {\n // existing the do-while interactive retry logic because retry quota has reached.\n break;\n }\n }\n\n let delayInMs: number;\n try {\n delayInMs = Number(\n ((await response.json()) as LogResponse).nextRequestWaitMillis\n );\n } catch (e) {\n delayInMs = DEFAULT_BACKOFF_TIME_MS;\n }\n\n await new Promise(resolve => setTimeout(resolve, delayInMs));\n\n retryCount++;\n } while (retryCount < MAX_RETRIES);\n }\n\n messaging.logEvents = [];\n // schedule for next logging\n _processQueue(messaging, LOG_INTERVAL_IN_MS);\n}\n\nfunction isRetriableError(response: Response): boolean {\n const httpStatus = response.status;\n\n return (\n httpStatus === 429 ||\n httpStatus === 500 ||\n httpStatus === 503 ||\n httpStatus === 504\n );\n}\n\nexport async function stageLog(\n messaging: MessagingService,\n internalPayload: MessagePayloadInternal\n): Promise {\n const fcmEvent = createFcmEvent(\n internalPayload,\n await messaging.firebaseDependencies.installations.getId()\n );\n\n createAndEnqueueLogEvent(messaging, fcmEvent, internalPayload.productId);\n}\n\nfunction createFcmEvent(\n internalPayload: MessagePayloadInternal,\n fid: string\n): FcmEvent {\n const fcmEvent = {} as FcmEvent;\n\n /* eslint-disable camelcase */\n // some fields should always be non-null. Still check to ensure.\n if (!!internalPayload.from) {\n fcmEvent.project_number = internalPayload.from;\n }\n\n if (!!internalPayload.fcmMessageId) {\n fcmEvent.message_id = internalPayload.fcmMessageId;\n }\n\n fcmEvent.instance_id = fid;\n\n if (!!internalPayload.notification) {\n fcmEvent.message_type = MessageType.DISPLAY_NOTIFICATION.toString();\n } else {\n fcmEvent.message_type = MessageType.DATA_MESSAGE.toString();\n }\n\n fcmEvent.sdk_platform = SDK_PLATFORM_WEB.toString();\n fcmEvent.package_name = self.origin.replace(/(^\\w+:|^)\\/\\//, '');\n\n if (!!internalPayload.collapse_key) {\n fcmEvent.collapse_key = internalPayload.collapse_key;\n }\n\n fcmEvent.event = EVENT_MESSAGE_DELIVERED.toString();\n\n if (!!internalPayload.fcmOptions?.analytics_label) {\n fcmEvent.analytics_label = internalPayload.fcmOptions?.analytics_label;\n }\n\n /* eslint-enable camelcase */\n return fcmEvent;\n}\n\nfunction createAndEnqueueLogEvent(\n messaging: MessagingService,\n fcmEvent: FcmEvent,\n productId: number\n): void {\n const logEvent = {} as LogEvent;\n\n /* eslint-disable camelcase */\n logEvent.event_time_ms = Math.floor(Date.now()).toString();\n logEvent.source_extension_json_proto3 = JSON.stringify({\n messaging_client_event: fcmEvent\n });\n\n if (!!productId) {\n logEvent.compliance_data = buildComplianceData(productId);\n }\n // eslint-disable-next-line camelcase\n\n messaging.logEvents.push(logEvent);\n}\n\nfunction buildComplianceData(productId: number): ComplianceData {\n const complianceData: ComplianceData = {\n privacy_context: {\n prequest: {\n origin_associated_product_id: productId\n }\n }\n };\n\n return complianceData;\n}\n\nexport function _createLogRequest(logEventQueue: LogEvent[]): LogRequest {\n const logRequest = {} as LogRequest;\n\n /* eslint-disable camelcase */\n logRequest.log_source = FCM_LOG_SOURCE.toString();\n logRequest.log_event = logEventQueue;\n /* eslint-enable camelcase */\n\n return logRequest;\n}\n\nexport function _mergeStrings(s1: string, s2: string): string {\n const resultArray = [];\n for (let i = 0; i < s1.length; i++) {\n resultArray.push(s1.charAt(i));\n if (i < s2.length) {\n resultArray.push(s2.charAt(i));\n }\n }\n\n return resultArray.join('');\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { FirebaseApp, FirebaseOptions } from '@firebase/app';\n\nimport { AppConfig } from '../interfaces/app-config';\nimport { FirebaseError } from '@firebase/util';\n\nexport function extractAppConfig(app: FirebaseApp): AppConfig {\n if (!app || !app.options) {\n throw getMissingValueError('App Configuration Object');\n }\n\n if (!app.name) {\n throw getMissingValueError('App Name');\n }\n\n // Required app config keys\n const configKeys: ReadonlyArray = [\n 'projectId',\n 'apiKey',\n 'appId',\n 'messagingSenderId'\n ];\n\n const { options } = app;\n for (const keyName of configKeys) {\n if (!options[keyName]) {\n throw getMissingValueError(keyName);\n }\n }\n\n return {\n appName: app.name,\n projectId: options.projectId!,\n apiKey: options.apiKey!,\n appId: options.appId!,\n senderId: options.messagingSenderId!\n };\n}\n\nfunction getMissingValueError(valueName: string): FirebaseError {\n return ERROR_FACTORY.create(ErrorCode.MISSING_APP_CONFIG_VALUES, {\n valueName\n });\n}\n", "/**\n * @license\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 * http://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 { FirebaseApp, _FirebaseService } from '@firebase/app';\nimport { MessagePayload, NextFn, Observer } from './interfaces/public-types';\n\nimport { FirebaseAnalyticsInternalName } from '@firebase/analytics-interop-types';\nimport { FirebaseInternalDependencies } from './interfaces/internal-dependencies';\nimport { LogEvent } from './interfaces/logging-types';\nimport { Provider } from '@firebase/component';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { extractAppConfig } from './helpers/extract-app-config';\n\nexport class MessagingService implements _FirebaseService {\n readonly app!: FirebaseApp;\n readonly firebaseDependencies!: FirebaseInternalDependencies;\n\n swRegistration?: ServiceWorkerRegistration;\n vapidKey?: string;\n // logging is only done with end user consent. Default to false.\n deliveryMetricsExportedToBigQueryEnabled: boolean = false;\n\n onBackgroundMessageHandler:\n | NextFn\n | Observer\n | null = null;\n\n onMessageHandler: NextFn | Observer | null =\n null;\n\n logEvents: LogEvent[] = [];\n isLogServiceStarted: boolean = false;\n\n constructor(\n app: FirebaseApp,\n installations: _FirebaseInstallationsInternal,\n analyticsProvider: Provider\n ) {\n const appConfig = extractAppConfig(app);\n\n this.firebaseDependencies = {\n app,\n appConfig,\n installations,\n analyticsProvider\n };\n }\n\n _delete(): Promise {\n return Promise.resolve();\n }\n}\n", "/**\n * @license\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 * http://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 {\n DEFAULT_REGISTRATION_TIMEOUT,\n DEFAULT_SW_PATH,\n DEFAULT_SW_SCOPE\n} from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\n\nexport async function registerDefaultSw(\n messaging: MessagingService\n): Promise {\n try {\n messaging.swRegistration = await navigator.serviceWorker.register(\n DEFAULT_SW_PATH,\n {\n scope: DEFAULT_SW_SCOPE\n }\n );\n\n // The timing when browser updates sw when sw has an update is unreliable from experiment. It\n // leads to version conflict when the SDK upgrades to a newer version in the main page, but sw\n // is stuck with the old version. For example,\n // https://github.com/firebase/firebase-js-sdk/issues/2590 The following line reliably updates\n // sw if there was an update.\n messaging.swRegistration.update().catch(() => {\n /* it is non blocking and we don't care if it failed */\n });\n await waitForRegistrationActive(messaging.swRegistration);\n } catch (e) {\n throw ERROR_FACTORY.create(ErrorCode.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: (e as Error)?.message\n });\n }\n}\n\n/**\n * Waits for registration to become active. MDN documentation claims that\n * a service worker registration should be ready to use after awaiting\n * navigator.serviceWorker.register() but that doesn't seem to be the case in\n * practice, causing the SDK to throw errors when calling\n * swRegistration.pushManager.subscribe() too soon after register(). The only\n * solution seems to be waiting for the service worker registration `state`\n * to become \"active\".\n */\nasync function waitForRegistrationActive(\n registration: ServiceWorkerRegistration\n): Promise {\n return new Promise((resolve, reject) => {\n const rejectTimeout = setTimeout(\n () =>\n reject(\n new Error(\n `Service worker not registered after ${DEFAULT_REGISTRATION_TIMEOUT} ms`\n )\n ),\n DEFAULT_REGISTRATION_TIMEOUT\n );\n const incomingSw = registration.installing || registration.waiting;\n if (registration.active) {\n clearTimeout(rejectTimeout);\n resolve();\n } else if (incomingSw) {\n incomingSw.onstatechange = ev => {\n if ((ev.target as ServiceWorker)?.state === 'activated') {\n incomingSw.onstatechange = null;\n clearTimeout(rejectTimeout);\n resolve();\n }\n };\n } else {\n clearTimeout(rejectTimeout);\n reject(new Error('No incoming service worker found.'));\n }\n });\n}\n", "/**\n * @license\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 * http://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 { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\nimport { registerDefaultSw } from './registerDefaultSw';\n\nexport async function updateSwReg(\n messaging: MessagingService,\n swRegistration?: ServiceWorkerRegistration | undefined\n): Promise {\n if (!swRegistration && !messaging.swRegistration) {\n await registerDefaultSw(messaging);\n }\n\n if (!swRegistration && !!messaging.swRegistration) {\n return;\n }\n\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_SW_REGISTRATION);\n }\n\n messaging.swRegistration = swRegistration;\n}\n", "/**\n * @license\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 * http://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 { DEFAULT_VAPID_KEY } from '../util/constants';\nimport { MessagingService } from '../messaging-service';\n\nexport async function updateVapidKey(\n messaging: MessagingService,\n vapidKey?: string | undefined\n): Promise {\n if (!!vapidKey) {\n messaging.vapidKey = vapidKey;\n } else if (!messaging.vapidKey) {\n messaging.vapidKey = DEFAULT_VAPID_KEY;\n }\n}\n", "/**\n * @license\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 * http://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 { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\nimport { getTokenInternal } from '../internals/token-manager';\nimport { updateSwReg } from '../helpers/updateSwReg';\nimport { updateVapidKey } from '../helpers/updateVapidKey';\nimport { GetTokenOptions } from '../interfaces/public-types';\n\nexport async function getToken(\n messaging: MessagingService,\n options?: GetTokenOptions\n): Promise {\n if (!navigator) {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n }\n\n if (Notification.permission === 'default') {\n await Notification.requestPermission();\n }\n\n if (Notification.permission !== 'granted') {\n throw ERROR_FACTORY.create(ErrorCode.PERMISSION_BLOCKED);\n }\n\n await updateVapidKey(messaging, options?.vapidKey);\n await updateSwReg(messaging, options?.serviceWorkerRegistration);\n\n return getTokenInternal(messaging);\n}\n", "/**\n * @license\n * Copyright 2019 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 * http://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 {\n CONSOLE_CAMPAIGN_ID,\n CONSOLE_CAMPAIGN_NAME,\n CONSOLE_CAMPAIGN_TIME\n} from '../util/constants';\nimport {\n ConsoleMessageData,\n MessageType\n} from '../interfaces/internal-message-payload';\n\nimport { MessagingService } from '../messaging-service';\n\nexport async function logToScion(\n messaging: MessagingService,\n messageType: MessageType,\n data: ConsoleMessageData\n): Promise {\n const eventType = getEventType(messageType);\n const analytics =\n await messaging.firebaseDependencies.analyticsProvider.get();\n analytics.logEvent(eventType, {\n /* eslint-disable camelcase */\n message_id: data[CONSOLE_CAMPAIGN_ID],\n message_name: data[CONSOLE_CAMPAIGN_NAME],\n message_time: data[CONSOLE_CAMPAIGN_TIME],\n message_device_time: Math.floor(Date.now() / 1000)\n /* eslint-enable camelcase */\n });\n}\n\nfunction getEventType(messageType: MessageType): string {\n switch (messageType) {\n case MessageType.NOTIFICATION_CLICKED:\n return 'notification_open';\n case MessageType.PUSH_RECEIVED:\n return 'notification_foreground';\n default:\n throw new Error();\n }\n}\n", "/**\n * @license\n * Copyright 2017 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 * http://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 {\n MessagePayloadInternal,\n MessageType\n} from '../interfaces/internal-message-payload';\n\nimport { CONSOLE_CAMPAIGN_ANALYTICS_ENABLED } from '../util/constants';\nimport { MessagingService } from '../messaging-service';\nimport { externalizePayload } from '../helpers/externalizePayload';\nimport { isConsoleMessage } from '../helpers/is-console-message';\nimport { logToScion } from '../helpers/logToScion';\n\nexport async function messageEventListener(\n messaging: MessagingService,\n event: MessageEvent\n): Promise {\n const internalPayload = event.data as MessagePayloadInternal;\n\n if (!internalPayload.isFirebaseMessaging) {\n return;\n }\n\n if (\n messaging.onMessageHandler &&\n internalPayload.messageType === MessageType.PUSH_RECEIVED\n ) {\n if (typeof messaging.onMessageHandler === 'function') {\n messaging.onMessageHandler(externalizePayload(internalPayload));\n } else {\n messaging.onMessageHandler.next(externalizePayload(internalPayload));\n }\n }\n\n // Log to Scion if applicable\n const dataPayload = internalPayload.data;\n if (\n isConsoleMessage(dataPayload) &&\n dataPayload[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1'\n ) {\n await logToScion(messaging, internalPayload.messageType!, dataPayload);\n }\n}\n", "/**\n * @license\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 * http://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 {\n Component,\n ComponentContainer,\n ComponentType,\n InstanceFactory\n} from '@firebase/component';\nimport {\n onNotificationClick,\n onPush,\n onSubChange\n} from '../listeners/sw-listeners';\n\nimport { GetTokenOptions } from '../interfaces/public-types';\nimport { MessagingInternal } from '@firebase/messaging-interop-types';\nimport { MessagingService } from '../messaging-service';\nimport { ServiceWorkerGlobalScope } from '../util/sw-types';\nimport { _registerComponent, registerVersion } from '@firebase/app';\nimport { getToken } from '../api/getToken';\nimport { messageEventListener } from '../listeners/window-listener';\n\nimport { name, version } from '../../package.json';\n\nconst WindowMessagingFactory: InstanceFactory<'messaging'> = (\n container: ComponentContainer\n) => {\n const messaging = new MessagingService(\n container.getProvider('app').getImmediate(),\n container.getProvider('installations-internal').getImmediate(),\n container.getProvider('analytics-internal')\n );\n\n navigator.serviceWorker.addEventListener('message', e =>\n messageEventListener(messaging as MessagingService, e)\n );\n\n return messaging;\n};\n\nconst WindowMessagingInternalFactory: InstanceFactory<'messaging-internal'> = (\n container: ComponentContainer\n) => {\n const messaging = container\n .getProvider('messaging')\n .getImmediate() as MessagingService;\n\n const messagingInternal: MessagingInternal = {\n getToken: (options?: GetTokenOptions) => getToken(messaging, options)\n };\n\n return messagingInternal;\n};\n\ndeclare const self: ServiceWorkerGlobalScope;\nconst SwMessagingFactory: InstanceFactory<'messaging'> = (\n container: ComponentContainer\n) => {\n const messaging = new MessagingService(\n container.getProvider('app').getImmediate(),\n container.getProvider('installations-internal').getImmediate(),\n container.getProvider('analytics-internal')\n );\n\n self.addEventListener('push', e => {\n e.waitUntil(onPush(e, messaging as MessagingService));\n });\n self.addEventListener('pushsubscriptionchange', e => {\n e.waitUntil(onSubChange(e, messaging as MessagingService));\n });\n self.addEventListener('notificationclick', e => {\n e.waitUntil(onNotificationClick(e));\n });\n\n return messaging;\n};\n\nexport function registerMessagingInWindow(): void {\n _registerComponent(\n new Component('messaging', WindowMessagingFactory, ComponentType.PUBLIC)\n );\n\n _registerComponent(\n new Component(\n 'messaging-internal',\n WindowMessagingInternalFactory,\n ComponentType.PRIVATE\n )\n );\n\n registerVersion(name, version);\n // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n\n/**\n * The messaging instance registered in sw is named differently than that of in client. This is\n * because both `registerMessagingInWindow` and `registerMessagingInSw` would be called in\n * `messaging-compat` and component with the same name can only be registered once.\n */\nexport function registerMessagingInSw(): void {\n _registerComponent(\n new Component('messaging-sw', SwMessagingFactory, ComponentType.PUBLIC)\n );\n}\n", "/**\n * @license\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 * http://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 {\n areCookiesEnabled,\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\n\n/**\n * Checks if all required APIs exist in the browser.\n * @returns a Promise that resolves to a boolean.\n *\n * @public\n */\nexport async function isWindowSupported(): Promise {\n try {\n // This throws if open() is unsupported, so adding it to the conditional\n // statement below can cause an uncaught error.\n await validateIndexedDBOpenable();\n } catch (e) {\n return false;\n }\n // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing\n // might be prohibited to run. In these contexts, an error would be thrown during the messaging\n // instantiating phase, informing the developers to import/call isSupported for special handling.\n return (\n typeof window !== 'undefined' &&\n isIndexedDBAvailable() &&\n areCookiesEnabled() &&\n 'serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey')\n );\n}\n\n/**\n * Checks whether all required APIs exist within SW Context\n * @returns a Promise that resolves to a boolean.\n *\n * @public\n */\nexport async function isSwSupported(): Promise {\n // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing\n // might be prohibited to run. In these contexts, an error would be thrown during the messaging\n // instantiating phase, informing the developers to import/call isSupported for special handling.\n return (\n isIndexedDBAvailable() &&\n (await validateIndexedDBOpenable()) &&\n 'PushManager' in self &&\n 'Notification' in self &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey')\n );\n}\n", "/**\n * @license\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 * http://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 { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\nimport { deleteTokenInternal } from '../internals/token-manager';\nimport { registerDefaultSw } from '../helpers/registerDefaultSw';\n\nexport async function deleteToken(\n messaging: MessagingService\n): Promise {\n if (!navigator) {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n }\n\n if (!messaging.swRegistration) {\n await registerDefaultSw(messaging);\n }\n\n return deleteTokenInternal(messaging);\n}\n", "/**\n * @license\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 * http://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 { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport {\n MessagePayload,\n NextFn,\n Observer,\n Unsubscribe\n} from '../interfaces/public-types';\nimport { MessagingService } from '../messaging-service';\n\nexport function onMessage(\n messaging: MessagingService,\n nextOrObserver: NextFn | Observer\n): Unsubscribe {\n if (!navigator) {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n }\n\n messaging.onMessageHandler = nextOrObserver;\n\n return () => {\n messaging.onMessageHandler = null;\n };\n}\n", "/**\n * @license\n * Copyright 2017 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 * http://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 { ERROR_FACTORY, ErrorCode } from './util/errors';\nimport { FirebaseApp, _getProvider, getApp } from '@firebase/app';\nimport {\n GetTokenOptions,\n MessagePayload,\n Messaging\n} from './interfaces/public-types';\nimport {\n NextFn,\n Observer,\n Unsubscribe,\n getModularInstance\n} from '@firebase/util';\nimport { isSwSupported, isWindowSupported } from './api/isSupported';\n\nimport { MessagingService } from './messaging-service';\nimport { deleteToken as _deleteToken } from './api/deleteToken';\nimport { getToken as _getToken } from './api/getToken';\nimport { onBackgroundMessage as _onBackgroundMessage } from './api/onBackgroundMessage';\nimport { onMessage as _onMessage } from './api/onMessage';\nimport { _setDeliveryMetricsExportedToBigQueryEnabled } from './api/setDeliveryMetricsExportedToBigQueryEnabled';\n\n/**\n * Retrieves a Firebase Cloud Messaging instance.\n *\n * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.\n *\n * @public\n */\nexport function getMessagingInWindow(app: FirebaseApp = getApp()): Messaging {\n // Conscious decision to make this async check non-blocking during the messaging instance\n // initialization phase for performance consideration. An error would be thrown latter for\n // developer's information. Developers can then choose to import and call `isSupported` for\n // special handling.\n isWindowSupported().then(\n isSupported => {\n // If `isWindowSupported()` resolved, but returned false.\n if (!isSupported) {\n throw ERROR_FACTORY.create(ErrorCode.UNSUPPORTED_BROWSER);\n }\n },\n _ => {\n // If `isWindowSupported()` rejected.\n throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNSUPPORTED);\n }\n );\n return _getProvider(getModularInstance(app), 'messaging').getImmediate();\n}\n\n/**\n * Retrieves a Firebase Cloud Messaging instance.\n *\n * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.\n *\n * @public\n */\nexport function getMessagingInSw(app: FirebaseApp = getApp()): Messaging {\n // Conscious decision to make this async check non-blocking during the messaging instance\n // initialization phase for performance consideration. An error would be thrown latter for\n // developer's information. Developers can then choose to import and call `isSupported` for\n // special handling.\n isSwSupported().then(\n isSupported => {\n // If `isSwSupported()` resolved, but returned false.\n if (!isSupported) {\n throw ERROR_FACTORY.create(ErrorCode.UNSUPPORTED_BROWSER);\n }\n },\n _ => {\n // If `isSwSupported()` rejected.\n throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNSUPPORTED);\n }\n );\n return _getProvider(getModularInstance(app), 'messaging-sw').getImmediate();\n}\n\n/**\n * Subscribes the {@link Messaging} instance to push notifications. Returns a Firebase Cloud\n * Messaging registration token that can be used to send push messages to that {@link Messaging}\n * instance.\n *\n * If notification permission isn't already granted, this method asks the user for permission. The\n * returned promise rejects if the user does not allow the app to show notifications.\n *\n * @param messaging - The {@link Messaging} instance.\n * @param options - Provides an optional vapid key and an optional service worker registration.\n *\n * @returns The promise resolves with an FCM registration token.\n *\n * @public\n */\nexport async function getToken(\n messaging: Messaging,\n options?: GetTokenOptions\n): Promise {\n messaging = getModularInstance(messaging);\n return _getToken(messaging as MessagingService, options);\n}\n\n/**\n * Deletes the registration token associated with this {@link Messaging} instance and unsubscribes\n * the {@link Messaging} instance from the push subscription.\n *\n * @param messaging - The {@link Messaging} instance.\n *\n * @returns The promise resolves when the token has been successfully deleted.\n *\n * @public\n */\nexport function deleteToken(messaging: Messaging): Promise {\n messaging = getModularInstance(messaging);\n return _deleteToken(messaging as MessagingService);\n}\n\n/**\n * When a push message is received and the user is currently on a page for your origin, the\n * message is passed to the page and an `onMessage()` event is dispatched with the payload of\n * the push message.\n *\n *\n * @param messaging - The {@link Messaging} instance.\n * @param nextOrObserver - This function, or observer object with `next` defined,\n * is called when a message is received and the user is currently viewing your page.\n * @returns To stop listening for messages execute this returned function.\n *\n * @public\n */\nexport function onMessage(\n messaging: Messaging,\n nextOrObserver: NextFn | Observer\n): Unsubscribe {\n messaging = getModularInstance(messaging);\n return _onMessage(messaging as MessagingService, nextOrObserver);\n}\n\n/**\n * Called when a message is received while the app is in the background. An app is considered to be\n * in the background if no active window is displayed.\n *\n * @param messaging - The {@link Messaging} instance.\n * @param nextOrObserver - This function, or observer object with `next` defined, is called when a\n * message is received and the app is currently in the background.\n *\n * @returns To stop listening for messages execute this returned function\n *\n * @public\n */\nexport function onBackgroundMessage(\n messaging: Messaging,\n nextOrObserver: NextFn | Observer\n): Unsubscribe {\n messaging = getModularInstance(messaging);\n return _onBackgroundMessage(messaging as MessagingService, nextOrObserver);\n}\n\n/**\n * Enables or disables Firebase Cloud Messaging message delivery metrics export to BigQuery. By\n * default, message delivery metrics are not exported to BigQuery. Use this method to enable or\n * disable the export at runtime.\n *\n * @param messaging - The `FirebaseMessaging` instance.\n * @param enable - Whether Firebase Cloud Messaging should export message delivery metrics to\n * BigQuery.\n *\n * @public\n */\nexport function experimentalSetDeliveryMetricsExportedToBigQueryEnabled(\n messaging: Messaging,\n enable: boolean\n): void {\n messaging = getModularInstance(messaging);\n return _setDeliveryMetricsExportedToBigQueryEnabled(messaging, enable);\n}\n", "/**\n * The Firebase Cloud Messaging Web SDK.\n * This SDK does not work in a Node.js environment.\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2017 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 * http://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 '@firebase/installations';\n\nimport { Messaging } from './interfaces/public-types';\nimport { registerMessagingInWindow } from './helpers/register';\n\nexport {\n getToken,\n deleteToken,\n onMessage,\n getMessagingInWindow as getMessaging\n} from './api';\nexport { isWindowSupported as isSupported } from './api/isSupported';\nexport * from './interfaces/public-types';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'messaging': Messaging;\n }\n}\n\nregisterMessagingInWindow();\n", "import { initializeApp } from \"firebase/app\";\nimport { getMessaging, getToken, onMessage, isSupported } from \"firebase/messaging\";\n\nconst firebaseConfig = {\n apiKey: \"AIzaSyA1jXvxitorTnYPC0hf_Z2mjQ830SiIKnk\",\n authDomain: \"autoraptor-dc0e3.firebaseapp.com\",\n databaseURL: \"https://autoraptor-dc0e3.firebaseio.com\",\n projectId: \"autoraptor-dc0e3\",\n storageBucket: \"autoraptor-dc0e3.appspot.com\",\n messagingSenderId: \"457736802086\",\n appId: \"1:457736802086:web:37b7765a1ce62614647be7\",\n};\n\nconst app = initializeApp(firebaseConfig);\nconst resolveMessaging = async () => {\n const supported = await isSupported();\n\n return supported ? getMessaging(app) : null;\n};\n\nconst requestToken = async () => {\n const messaging = await resolveMessaging();\n\n if (messaging === null) {\n return;\n }\n\n Notification.requestPermission().then((permission) => {\n if (permission === \"granted\") {\n getToken(messaging, {\n vapidKey: \"BHRJTAe9GiKBsdCg8smwMN3-THPTn_EfOEvouv4zAXRofIrq7KTtDH6Fr96iWHqX1jRYlRHdevkBHBWAEX9I7ko\",\n }).then(token => {\n window.dispatchEvent(new CustomEvent(\"register-fcm-token\", {\n detail: { token },\n }));\n }).catch(error => {\n // Some browsers pass isSupported() but still can't complete a push\n // subscription (e.g. Firefox with push disabled), so getToken rejects\n // with \"unsupported browser\". That's expected \u2014 swallow it, but let\n // any other rejection surface so we still hear about real failures.\n if (error?.code !== \"messaging/unsupported-browser\") {\n throw error;\n }\n });\n }\n });\n};\n\n// Web Push\n//\n// Refresh the FCM token on every load when permission is already granted \u2014\n// FCM rotates tokens (data clear, scheduled rotation, server unregister)\n// and stale tokens get deleted on 404 by SendFcmNotificationJob, leaving\n// the user silently broken until re-registered. Only prompt fresh users\n// on the TWA launcher startUrl (`?source=twa`) so we don't pester non-TWA\n// visitors.\nwindow.addEventListener(\"DOMContentLoaded\", () => {\n if (!(\"Notification\" in window) || Notification.permission === \"denied\") {\n return;\n }\n\n const isTwaLoadscreen = new URLSearchParams(window.location.search).get(\"source\") === \"twa\";\n\n if (Notification.permission === \"granted\" || isTwaLoadscreen) {\n requestToken();\n }\n});\n\n/**\n * Register foreground listener\n *\n * Incoming payload\n *\n * {\n * data: {\n * url?: \"https://ar.autoraptor.com/...\",\n * ...\n * },\n * notification: {\n * title: \"Notification Title\",\n * body: \"Notification Body\",\n * }\n * }\n */\n(async () => {\n const messaging = await resolveMessaging();\n\n if (messaging === null) {\n return;\n }\n\n onMessage(messaging, payload => {\n navigator.serviceWorker.getRegistration(\"/firebase-cloud-messaging-push-scope\").then(registration => {\n registration.showNotification(\n payload.notification.title,\n {\n body: payload.notification.body,\n data: payload.data,\n },\n );\n });\n });\n})();\n", "function getFrame(target) {\n const eventElementType = target.tagName.toLowerCase();\n\n if (eventElementType === \"turbo-frame\") {\n return target;\n }\n\n if (target.dataset.turboFrame) {\n return document.querySelector(`#${target.dataset.turboFrame}`);\n }\n}\n\nfunction getTemplate(name) {\n return document.querySelector(`#${name}`)?.content?.cloneNode(true);\n}\n\nwindow.addEventListener(\"turbo:before-fetch-request\", (event) => {\n const target = event.target;\n const frame = getFrame(target);\n const template = getTemplate(\"turbo_loading\");\n const headers = event.detail.fetchOptions.headers;\n const isPrefetch = headers[\"X-Sec-Purpose\"] === \"prefetch\";\n\n if (!frame || !template || isPrefetch) {\n return;\n }\n\n frame.style.setProperty(\"position\", \"relative\");\n frame.style.setProperty(\"min-height\", \"40px\");\n frame.style.setProperty(\"display\", \"block\");\n frame.prepend(template);\n});\n\nwindow.addEventListener(\"turbo:frame-render\", ({ target }) => {\n [\"position\", \"min-height\", \"display\"].forEach(property => target.style.removeProperty(property));\n});\n\nwindow.addEventListener(\"turbo:before-fetch-response\", (event) => {\n /** @param {Response | null} response */\n const response = event.detail?.fetchResponse?.response;\n\n if (!response) {\n return;\n }\n\n if ([404, 500, 503].includes(response.status)) {\n const frame = getFrame(event.target);\n const template = getTemplate(`turbo_frame_${response.status}`);\n\n if (frame && template) {\n const fakeFrame = document.createElement(\"turbo-frame\");\n fakeFrame.id = frame.id;\n fakeFrame.replaceChildren(template);\n\n event.detail.fetchResponse.response = new Response(fakeFrame.outerHTML, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/html\",\n },\n });\n }\n }\n});\n\nwindow.addEventListener(\"turbo:frame-missing\", async (event) => {\n if (!event.detail.response) {\n return;\n }\n\n const response = event.detail.response;\n const frameId = event.target.closest(\"turbo-frame\")?.id ?? \"--unknown--\";\n\n // Prevent normal error\n event.preventDefault();\n\n // Set missing\n if (AR_ENV_DEV) {\n event.target.innerHTML = `\n
\n
A request from this turbo frame did not having a matching frame to extract from in the response.
\n
Make sure the requested page contains a turbo frame with\n ${frameId} in the contents.\n
\n
The response has been logged as well
\n
\n `;\n\n console.error(`This response is missing ${frameId}`, response);\n } else {\n event.target.innerHTML = \"An error has occurred while fetching content.\";\n }\n});\n\n// Tag what append/prepend/before/after streams insert so lib/_motion.css can\n// ease it in. The template itself is marked: `templateContent` hands out a\n// fresh clone on every read.\nconst INSERTING_STREAM_ACTIONS = [\"append\", \"prepend\", \"before\", \"after\"];\n\ndocument.addEventListener(\"turbo:before-stream-render\", ({ target }) => {\n if (!INSERTING_STREAM_ACTIONS.includes(target.action)) {\n return;\n }\n\n for (const element of target.templateElement?.content?.children ?? []) {\n element.setAttribute(\"data-stream-enter\", \"\");\n }\n});\n\n// Page transitions (lib/_motion.css) are skipped in automated browsers: while\n// the overlay runs it takes the clicks a system spec fires right after a visit.\n// Skipping on the outgoing page cancels the whole transition.\nif (navigator.webdriver) {\n window.addEventListener(\"pageswap\", ({ viewTransition }) => viewTransition?.skipTransition());\n}\n\n// The browser aborts a transition when the tab is hidden or the viewport\n// resizes, and rejects `ready`. The page still loads, so nothing to report.\nfor (const event of [\"pageswap\", \"pagereveal\"]) {\n window.addEventListener(event, ({ viewTransition }) => viewTransition?.ready.catch(() => {}));\n}\n", "CKEDITOR.disableAutoInline = true;\nCKEDITOR.config.disableNativeSpellChecker = false;\nCKEDITOR.config.removePlugins = \"liststyle,tableselection,tabletools,contextmenu,uploadimage,uploadwidget\";\nCKEDITOR.config.extraPlugins = \"autolink,videothumb\";\nCKEDITOR.addCss(\".cke_editable { font-size: 16px; }\");\n\njQuery(function ($) {\n CKEDITOR.on(\"instanceReady\", function (ev) {\n $(\".toolbar\").removeClass(\"hide\");\n });\n\n $(\"#content\").on(\"click\", \".cke_toolbox_collapser\", function () {\n if ($(this).hasClass(\"cke_toolbox_collapser_min\")) {\n $(\".toolbar\").addClass(\"hide\");\n } else {\n $(\".toolbar\").removeClass(\"hide\");\n }\n });\n});\n", "const getImageDataUrl = (file) => {\n return new Promise((resolve, reject) => {\n // ensure file is an image\n if (!file.type.startsWith(\"image/\")) {\n resolve(null);\n }\n const reader = new FileReader();\n reader.onload = function (e) {\n resolve(e.target.result);\n };\n reader.onerror = function (e) {\n reject(new Error(\"Failed to read file\"));\n };\n reader.readAsDataURL(file);\n });\n};\n\nconst attachments = {\n FILE_MAX_SIZE: 20 * 1048576,\n\n ALL_FILES_MAX_SIZE: 20 * 1048576,\n\n show () {\n $(\"#attachment_area\").removeClass(\"hidden\");\n $(\"#attachment_link\").addClass(\"hidden\");\n\n if ($(\"#attachments #email-drop-area\").length < 1) {\n this.addClientUpload($(\"#attachments\"));\n }\n },\n\n addClientUpload (root_elem) {\n const form = $(root_elem.parents(\"form:first\"));\n const submitButton = form.find(\"button[type=\\\"submit\\\"]\");\n const spinner = form.find(\"#send_email_spinner\");\n const genericIconUrl = form.data(\"generic-icon-url\");\n\n const span = $(\"
\");\n const thumbnails = $(\"
\");\n span.append(thumbnails);\n const fileInput = $(\"\", { type: \"file\", class: \"file-upload mt-20\", multiple: true });\n const dropZone = $(\"
\",\n {\n id: \"email-drop-area\",\n class: \"droparea\",\n text: \"Drag and drop a file here to upload it to this email\",\n });\n const progressBar = $(\"
\");\n const barContainer = $(\"
\").append(progressBar);\n let validUpload = true;\n\n async function fileDiv(file, key) {\n const src = await getImageDataUrl(file) || genericIconUrl;\n const container = $(\"
\", { class: \"file-attachment-container max-w-[64px]\", id: \"files\" });\n const keyInput = $(\"\", { type: \"hidden\", name: \"remote_attachments[][key]\", value: key });\n const sizeInput = $(\"\",\n {\n type: \"hidden\",\n name: \"remote_attachments[][file_size]\",\n value: file.size,\n class: \"attachment-size\",\n },\n );\n const img = $(\"\", { src, alt: file.name, class: \"file\" });\n const fileNameDiv = $(`
${file.name}
`);\n const removeLink = $(\"\", { class: \"remove-file\", onclick: \"$(this).parent().remove();\", text: \"remove\" });\n return container\n .append(keyInput)\n .append(sizeInput)\n .append(fileNameDiv)\n .append(img)\n .append(removeLink);\n }\n\n function uploadFailed() {\n finishUpload();\n progressBar\n .css(\"width\", \"100%\")\n .css(\"background\", \"#ce0b0b\")\n .text(\"Failed\");\n }\n\n function finishUpload() {\n submitButton.prop(\"disabled\", false);\n spinner.hide();\n fileInput.prop(\"disabled\", false);\n }\n\n function totalFileSizes() {\n const fileSizeArray = $(\"input[name='remote_attachments[][file_size]\")\n .map((_key, element) => parseInt(element.value, 10)).get();\n return fileSizeArray.reduce((a, b) => a + b, 0);\n }\n\n span\n .append(fileInput)\n .append(barContainer)\n .append(dropZone);\n\n root_elem.append(span);\n\n return fileInput.fileupload({\n fileInput,\n url: form.data(\"attachment-url\"),\n method: \"POST\",\n autoUpload: true,\n formData: form.data(\"attachment-data\"),\n paramName: \"file\",\n dropZone,\n dataType: \"XML\",\n replaceFileInput: false,\n\n add: (e, data) => {\n if (validUpload) {\n const file = data.files.first();\n if (file.size === 0) {\n alert(`There was an error processing '${file.name}' as it appears to be empty.`);\n uploadFailed();\n } else if (file.size > this.FILE_MAX_SIZE) {\n alert(`The file '${file.name}' is too large to upload. Please use a file that is 20 MB or smaller.`);\n uploadFailed();\n } else {\n data.process().done(() => data.submit());\n }\n }\n },\n\n progressall (e, data) {\n const progress = parseInt((data.loaded / data.total) * 100, 10);\n if (progress === 100) {\n progressBar.text(\"Uploading done\");\n finishUpload();\n }\n progressBar.css(\"width\", progress + \"%\");\n },\n\n change: (e, data) => {\n validUpload = true;\n const incomingFileSize = data.files\n .map(x => x.size).reduce((a, b) => a + b, 0);\n const currentFileSizes = totalFileSizes();\n if (incomingFileSize + currentFileSizes > this.ALL_FILES_MAX_SIZE) {\n validUpload = false;\n alert(\"The total size of all files is over the 20 MB max.\");\n uploadFailed();\n }\n },\n\n start (e) {\n validUpload = true;\n fileInput.prop(\"disabled\", true);\n submitButton.prop(\"disabled\", true);\n spinner.show();\n\n progressBar\n .css(\"width\", \"0%\")\n .css(\"background\", \"#07892a\")\n .text(\"\");\n },\n\n // called after every completed uploaed\n done: async (e, data) => {\n const key = $(data.jqXHR.responseXML).find(\"Key\").text();\n const file = data.files.first();\n const div = await fileDiv(file, key);\n thumbnails.append(div);\n },\n\n fail: (e, data) => {\n uploadFailed();\n },\n });\n },\n};\n\nexport default attachments;\n", "/*\nStimulus 3.2.1\nCopyright \u00A9 2023 Basecamp, LLC\n */\nclass EventListener {\n constructor(eventTarget, eventName, eventOptions) {\n this.eventTarget = eventTarget;\n this.eventName = eventName;\n this.eventOptions = eventOptions;\n this.unorderedBindings = new Set();\n }\n connect() {\n this.eventTarget.addEventListener(this.eventName, this, this.eventOptions);\n }\n disconnect() {\n this.eventTarget.removeEventListener(this.eventName, this, this.eventOptions);\n }\n bindingConnected(binding) {\n this.unorderedBindings.add(binding);\n }\n bindingDisconnected(binding) {\n this.unorderedBindings.delete(binding);\n }\n handleEvent(event) {\n const extendedEvent = extendEvent(event);\n for (const binding of this.bindings) {\n if (extendedEvent.immediatePropagationStopped) {\n break;\n }\n else {\n binding.handleEvent(extendedEvent);\n }\n }\n }\n hasBindings() {\n return this.unorderedBindings.size > 0;\n }\n get bindings() {\n return Array.from(this.unorderedBindings).sort((left, right) => {\n const leftIndex = left.index, rightIndex = right.index;\n return leftIndex < rightIndex ? -1 : leftIndex > rightIndex ? 1 : 0;\n });\n }\n}\nfunction extendEvent(event) {\n if (\"immediatePropagationStopped\" in event) {\n return event;\n }\n else {\n const { stopImmediatePropagation } = event;\n return Object.assign(event, {\n immediatePropagationStopped: false,\n stopImmediatePropagation() {\n this.immediatePropagationStopped = true;\n stopImmediatePropagation.call(this);\n },\n });\n }\n}\n\nclass Dispatcher {\n constructor(application) {\n this.application = application;\n this.eventListenerMaps = new Map();\n this.started = false;\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.eventListeners.forEach((eventListener) => eventListener.connect());\n }\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.eventListeners.forEach((eventListener) => eventListener.disconnect());\n }\n }\n get eventListeners() {\n return Array.from(this.eventListenerMaps.values()).reduce((listeners, map) => listeners.concat(Array.from(map.values())), []);\n }\n bindingConnected(binding) {\n this.fetchEventListenerForBinding(binding).bindingConnected(binding);\n }\n bindingDisconnected(binding, clearEventListeners = false) {\n this.fetchEventListenerForBinding(binding).bindingDisconnected(binding);\n if (clearEventListeners)\n this.clearEventListenersForBinding(binding);\n }\n handleError(error, message, detail = {}) {\n this.application.handleError(error, `Error ${message}`, detail);\n }\n clearEventListenersForBinding(binding) {\n const eventListener = this.fetchEventListenerForBinding(binding);\n if (!eventListener.hasBindings()) {\n eventListener.disconnect();\n this.removeMappedEventListenerFor(binding);\n }\n }\n removeMappedEventListenerFor(binding) {\n const { eventTarget, eventName, eventOptions } = binding;\n const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);\n const cacheKey = this.cacheKey(eventName, eventOptions);\n eventListenerMap.delete(cacheKey);\n if (eventListenerMap.size == 0)\n this.eventListenerMaps.delete(eventTarget);\n }\n fetchEventListenerForBinding(binding) {\n const { eventTarget, eventName, eventOptions } = binding;\n return this.fetchEventListener(eventTarget, eventName, eventOptions);\n }\n fetchEventListener(eventTarget, eventName, eventOptions) {\n const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);\n const cacheKey = this.cacheKey(eventName, eventOptions);\n let eventListener = eventListenerMap.get(cacheKey);\n if (!eventListener) {\n eventListener = this.createEventListener(eventTarget, eventName, eventOptions);\n eventListenerMap.set(cacheKey, eventListener);\n }\n return eventListener;\n }\n createEventListener(eventTarget, eventName, eventOptions) {\n const eventListener = new EventListener(eventTarget, eventName, eventOptions);\n if (this.started) {\n eventListener.connect();\n }\n return eventListener;\n }\n fetchEventListenerMapForEventTarget(eventTarget) {\n let eventListenerMap = this.eventListenerMaps.get(eventTarget);\n if (!eventListenerMap) {\n eventListenerMap = new Map();\n this.eventListenerMaps.set(eventTarget, eventListenerMap);\n }\n return eventListenerMap;\n }\n cacheKey(eventName, eventOptions) {\n const parts = [eventName];\n Object.keys(eventOptions)\n .sort()\n .forEach((key) => {\n parts.push(`${eventOptions[key] ? \"\" : \"!\"}${key}`);\n });\n return parts.join(\":\");\n }\n}\n\nconst defaultActionDescriptorFilters = {\n stop({ event, value }) {\n if (value)\n event.stopPropagation();\n return true;\n },\n prevent({ event, value }) {\n if (value)\n event.preventDefault();\n return true;\n },\n self({ event, value, element }) {\n if (value) {\n return element === event.target;\n }\n else {\n return true;\n }\n },\n};\nconst descriptorPattern = /^(?:(?:([^.]+?)\\+)?(.+?)(?:\\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;\nfunction parseActionDescriptorString(descriptorString) {\n const source = descriptorString.trim();\n const matches = source.match(descriptorPattern) || [];\n let eventName = matches[2];\n let keyFilter = matches[3];\n if (keyFilter && ![\"keydown\", \"keyup\", \"keypress\"].includes(eventName)) {\n eventName += `.${keyFilter}`;\n keyFilter = \"\";\n }\n return {\n eventTarget: parseEventTarget(matches[4]),\n eventName,\n eventOptions: matches[7] ? parseEventOptions(matches[7]) : {},\n identifier: matches[5],\n methodName: matches[6],\n keyFilter: matches[1] || keyFilter,\n };\n}\nfunction parseEventTarget(eventTargetName) {\n if (eventTargetName == \"window\") {\n return window;\n }\n else if (eventTargetName == \"document\") {\n return document;\n }\n}\nfunction parseEventOptions(eventOptions) {\n return eventOptions\n .split(\":\")\n .reduce((options, token) => Object.assign(options, { [token.replace(/^!/, \"\")]: !/^!/.test(token) }), {});\n}\nfunction stringifyEventTarget(eventTarget) {\n if (eventTarget == window) {\n return \"window\";\n }\n else if (eventTarget == document) {\n return \"document\";\n }\n}\n\nfunction camelize(value) {\n return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());\n}\nfunction namespaceCamelize(value) {\n return camelize(value.replace(/--/g, \"-\").replace(/__/g, \"_\"));\n}\nfunction capitalize(value) {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\nfunction dasherize(value) {\n return value.replace(/([A-Z])/g, (_, char) => `-${char.toLowerCase()}`);\n}\nfunction tokenize(value) {\n return value.match(/[^\\s]+/g) || [];\n}\n\nfunction isSomething(object) {\n return object !== null && object !== undefined;\n}\nfunction hasProperty(object, property) {\n return Object.prototype.hasOwnProperty.call(object, property);\n}\n\nconst allModifiers = [\"meta\", \"ctrl\", \"alt\", \"shift\"];\nclass Action {\n constructor(element, index, descriptor, schema) {\n this.element = element;\n this.index = index;\n this.eventTarget = descriptor.eventTarget || element;\n this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error(\"missing event name\");\n this.eventOptions = descriptor.eventOptions || {};\n this.identifier = descriptor.identifier || error(\"missing identifier\");\n this.methodName = descriptor.methodName || error(\"missing method name\");\n this.keyFilter = descriptor.keyFilter || \"\";\n this.schema = schema;\n }\n static forToken(token, schema) {\n return new this(token.element, token.index, parseActionDescriptorString(token.content), schema);\n }\n toString() {\n const eventFilter = this.keyFilter ? `.${this.keyFilter}` : \"\";\n const eventTarget = this.eventTargetName ? `@${this.eventTargetName}` : \"\";\n return `${this.eventName}${eventFilter}${eventTarget}->${this.identifier}#${this.methodName}`;\n }\n shouldIgnoreKeyboardEvent(event) {\n if (!this.keyFilter) {\n return false;\n }\n const filters = this.keyFilter.split(\"+\");\n if (this.keyFilterDissatisfied(event, filters)) {\n return true;\n }\n const standardFilter = filters.filter((key) => !allModifiers.includes(key))[0];\n if (!standardFilter) {\n return false;\n }\n if (!hasProperty(this.keyMappings, standardFilter)) {\n error(`contains unknown key filter: ${this.keyFilter}`);\n }\n return this.keyMappings[standardFilter].toLowerCase() !== event.key.toLowerCase();\n }\n shouldIgnoreMouseEvent(event) {\n if (!this.keyFilter) {\n return false;\n }\n const filters = [this.keyFilter];\n if (this.keyFilterDissatisfied(event, filters)) {\n return true;\n }\n return false;\n }\n get params() {\n const params = {};\n const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`, \"i\");\n for (const { name, value } of Array.from(this.element.attributes)) {\n const match = name.match(pattern);\n const key = match && match[1];\n if (key) {\n params[camelize(key)] = typecast(value);\n }\n }\n return params;\n }\n get eventTargetName() {\n return stringifyEventTarget(this.eventTarget);\n }\n get keyMappings() {\n return this.schema.keyMappings;\n }\n keyFilterDissatisfied(event, filters) {\n const [meta, ctrl, alt, shift] = allModifiers.map((modifier) => filters.includes(modifier));\n return event.metaKey !== meta || event.ctrlKey !== ctrl || event.altKey !== alt || event.shiftKey !== shift;\n }\n}\nconst defaultEventNames = {\n a: () => \"click\",\n button: () => \"click\",\n form: () => \"submit\",\n details: () => \"toggle\",\n input: (e) => (e.getAttribute(\"type\") == \"submit\" ? \"click\" : \"input\"),\n select: () => \"change\",\n textarea: () => \"input\",\n};\nfunction getDefaultEventNameForElement(element) {\n const tagName = element.tagName.toLowerCase();\n if (tagName in defaultEventNames) {\n return defaultEventNames[tagName](element);\n }\n}\nfunction error(message) {\n throw new Error(message);\n}\nfunction typecast(value) {\n try {\n return JSON.parse(value);\n }\n catch (o_O) {\n return value;\n }\n}\n\nclass Binding {\n constructor(context, action) {\n this.context = context;\n this.action = action;\n }\n get index() {\n return this.action.index;\n }\n get eventTarget() {\n return this.action.eventTarget;\n }\n get eventOptions() {\n return this.action.eventOptions;\n }\n get identifier() {\n return this.context.identifier;\n }\n handleEvent(event) {\n const actionEvent = this.prepareActionEvent(event);\n if (this.willBeInvokedByEvent(event) && this.applyEventModifiers(actionEvent)) {\n this.invokeWithEvent(actionEvent);\n }\n }\n get eventName() {\n return this.action.eventName;\n }\n get method() {\n const method = this.controller[this.methodName];\n if (typeof method == \"function\") {\n return method;\n }\n throw new Error(`Action \"${this.action}\" references undefined method \"${this.methodName}\"`);\n }\n applyEventModifiers(event) {\n const { element } = this.action;\n const { actionDescriptorFilters } = this.context.application;\n const { controller } = this.context;\n let passes = true;\n for (const [name, value] of Object.entries(this.eventOptions)) {\n if (name in actionDescriptorFilters) {\n const filter = actionDescriptorFilters[name];\n passes = passes && filter({ name, value, event, element, controller });\n }\n else {\n continue;\n }\n }\n return passes;\n }\n prepareActionEvent(event) {\n return Object.assign(event, { params: this.action.params });\n }\n invokeWithEvent(event) {\n const { target, currentTarget } = event;\n try {\n this.method.call(this.controller, event);\n this.context.logDebugActivity(this.methodName, { event, target, currentTarget, action: this.methodName });\n }\n catch (error) {\n const { identifier, controller, element, index } = this;\n const detail = { identifier, controller, element, index, event };\n this.context.handleError(error, `invoking action \"${this.action}\"`, detail);\n }\n }\n willBeInvokedByEvent(event) {\n const eventTarget = event.target;\n if (event instanceof KeyboardEvent && this.action.shouldIgnoreKeyboardEvent(event)) {\n return false;\n }\n if (event instanceof MouseEvent && this.action.shouldIgnoreMouseEvent(event)) {\n return false;\n }\n if (this.element === eventTarget) {\n return true;\n }\n else if (eventTarget instanceof Element && this.element.contains(eventTarget)) {\n return this.scope.containsElement(eventTarget);\n }\n else {\n return this.scope.containsElement(this.action.element);\n }\n }\n get controller() {\n return this.context.controller;\n }\n get methodName() {\n return this.action.methodName;\n }\n get element() {\n return this.scope.element;\n }\n get scope() {\n return this.context.scope;\n }\n}\n\nclass ElementObserver {\n constructor(element, delegate) {\n this.mutationObserverInit = { attributes: true, childList: true, subtree: true };\n this.element = element;\n this.started = false;\n this.delegate = delegate;\n this.elements = new Set();\n this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.mutationObserver.observe(this.element, this.mutationObserverInit);\n this.refresh();\n }\n }\n pause(callback) {\n if (this.started) {\n this.mutationObserver.disconnect();\n this.started = false;\n }\n callback();\n if (!this.started) {\n this.mutationObserver.observe(this.element, this.mutationObserverInit);\n this.started = true;\n }\n }\n stop() {\n if (this.started) {\n this.mutationObserver.takeRecords();\n this.mutationObserver.disconnect();\n this.started = false;\n }\n }\n refresh() {\n if (this.started) {\n const matches = new Set(this.matchElementsInTree());\n for (const element of Array.from(this.elements)) {\n if (!matches.has(element)) {\n this.removeElement(element);\n }\n }\n for (const element of Array.from(matches)) {\n this.addElement(element);\n }\n }\n }\n processMutations(mutations) {\n if (this.started) {\n for (const mutation of mutations) {\n this.processMutation(mutation);\n }\n }\n }\n processMutation(mutation) {\n if (mutation.type == \"attributes\") {\n this.processAttributeChange(mutation.target, mutation.attributeName);\n }\n else if (mutation.type == \"childList\") {\n this.processRemovedNodes(mutation.removedNodes);\n this.processAddedNodes(mutation.addedNodes);\n }\n }\n processAttributeChange(element, attributeName) {\n if (this.elements.has(element)) {\n if (this.delegate.elementAttributeChanged && this.matchElement(element)) {\n this.delegate.elementAttributeChanged(element, attributeName);\n }\n else {\n this.removeElement(element);\n }\n }\n else if (this.matchElement(element)) {\n this.addElement(element);\n }\n }\n processRemovedNodes(nodes) {\n for (const node of Array.from(nodes)) {\n const element = this.elementFromNode(node);\n if (element) {\n this.processTree(element, this.removeElement);\n }\n }\n }\n processAddedNodes(nodes) {\n for (const node of Array.from(nodes)) {\n const element = this.elementFromNode(node);\n if (element && this.elementIsActive(element)) {\n this.processTree(element, this.addElement);\n }\n }\n }\n matchElement(element) {\n return this.delegate.matchElement(element);\n }\n matchElementsInTree(tree = this.element) {\n return this.delegate.matchElementsInTree(tree);\n }\n processTree(tree, processor) {\n for (const element of this.matchElementsInTree(tree)) {\n processor.call(this, element);\n }\n }\n elementFromNode(node) {\n if (node.nodeType == Node.ELEMENT_NODE) {\n return node;\n }\n }\n elementIsActive(element) {\n if (element.isConnected != this.element.isConnected) {\n return false;\n }\n else {\n return this.element.contains(element);\n }\n }\n addElement(element) {\n if (!this.elements.has(element)) {\n if (this.elementIsActive(element)) {\n this.elements.add(element);\n if (this.delegate.elementMatched) {\n this.delegate.elementMatched(element);\n }\n }\n }\n }\n removeElement(element) {\n if (this.elements.has(element)) {\n this.elements.delete(element);\n if (this.delegate.elementUnmatched) {\n this.delegate.elementUnmatched(element);\n }\n }\n }\n}\n\nclass AttributeObserver {\n constructor(element, attributeName, delegate) {\n this.attributeName = attributeName;\n this.delegate = delegate;\n this.elementObserver = new ElementObserver(element, this);\n }\n get element() {\n return this.elementObserver.element;\n }\n get selector() {\n return `[${this.attributeName}]`;\n }\n start() {\n this.elementObserver.start();\n }\n pause(callback) {\n this.elementObserver.pause(callback);\n }\n stop() {\n this.elementObserver.stop();\n }\n refresh() {\n this.elementObserver.refresh();\n }\n get started() {\n return this.elementObserver.started;\n }\n matchElement(element) {\n return element.hasAttribute(this.attributeName);\n }\n matchElementsInTree(tree) {\n const match = this.matchElement(tree) ? [tree] : [];\n const matches = Array.from(tree.querySelectorAll(this.selector));\n return match.concat(matches);\n }\n elementMatched(element) {\n if (this.delegate.elementMatchedAttribute) {\n this.delegate.elementMatchedAttribute(element, this.attributeName);\n }\n }\n elementUnmatched(element) {\n if (this.delegate.elementUnmatchedAttribute) {\n this.delegate.elementUnmatchedAttribute(element, this.attributeName);\n }\n }\n elementAttributeChanged(element, attributeName) {\n if (this.delegate.elementAttributeValueChanged && this.attributeName == attributeName) {\n this.delegate.elementAttributeValueChanged(element, attributeName);\n }\n }\n}\n\nfunction add(map, key, value) {\n fetch(map, key).add(value);\n}\nfunction del(map, key, value) {\n fetch(map, key).delete(value);\n prune(map, key);\n}\nfunction fetch(map, key) {\n let values = map.get(key);\n if (!values) {\n values = new Set();\n map.set(key, values);\n }\n return values;\n}\nfunction prune(map, key) {\n const values = map.get(key);\n if (values != null && values.size == 0) {\n map.delete(key);\n }\n}\n\nclass Multimap {\n constructor() {\n this.valuesByKey = new Map();\n }\n get keys() {\n return Array.from(this.valuesByKey.keys());\n }\n get values() {\n const sets = Array.from(this.valuesByKey.values());\n return sets.reduce((values, set) => values.concat(Array.from(set)), []);\n }\n get size() {\n const sets = Array.from(this.valuesByKey.values());\n return sets.reduce((size, set) => size + set.size, 0);\n }\n add(key, value) {\n add(this.valuesByKey, key, value);\n }\n delete(key, value) {\n del(this.valuesByKey, key, value);\n }\n has(key, value) {\n const values = this.valuesByKey.get(key);\n return values != null && values.has(value);\n }\n hasKey(key) {\n return this.valuesByKey.has(key);\n }\n hasValue(value) {\n const sets = Array.from(this.valuesByKey.values());\n return sets.some((set) => set.has(value));\n }\n getValuesForKey(key) {\n const values = this.valuesByKey.get(key);\n return values ? Array.from(values) : [];\n }\n getKeysForValue(value) {\n return Array.from(this.valuesByKey)\n .filter(([_key, values]) => values.has(value))\n .map(([key, _values]) => key);\n }\n}\n\nclass IndexedMultimap extends Multimap {\n constructor() {\n super();\n this.keysByValue = new Map();\n }\n get values() {\n return Array.from(this.keysByValue.keys());\n }\n add(key, value) {\n super.add(key, value);\n add(this.keysByValue, value, key);\n }\n delete(key, value) {\n super.delete(key, value);\n del(this.keysByValue, value, key);\n }\n hasValue(value) {\n return this.keysByValue.has(value);\n }\n getKeysForValue(value) {\n const set = this.keysByValue.get(value);\n return set ? Array.from(set) : [];\n }\n}\n\nclass SelectorObserver {\n constructor(element, selector, delegate, details) {\n this._selector = selector;\n this.details = details;\n this.elementObserver = new ElementObserver(element, this);\n this.delegate = delegate;\n this.matchesByElement = new Multimap();\n }\n get started() {\n return this.elementObserver.started;\n }\n get selector() {\n return this._selector;\n }\n set selector(selector) {\n this._selector = selector;\n this.refresh();\n }\n start() {\n this.elementObserver.start();\n }\n pause(callback) {\n this.elementObserver.pause(callback);\n }\n stop() {\n this.elementObserver.stop();\n }\n refresh() {\n this.elementObserver.refresh();\n }\n get element() {\n return this.elementObserver.element;\n }\n matchElement(element) {\n const { selector } = this;\n if (selector) {\n const matches = element.matches(selector);\n if (this.delegate.selectorMatchElement) {\n return matches && this.delegate.selectorMatchElement(element, this.details);\n }\n return matches;\n }\n else {\n return false;\n }\n }\n matchElementsInTree(tree) {\n const { selector } = this;\n if (selector) {\n const match = this.matchElement(tree) ? [tree] : [];\n const matches = Array.from(tree.querySelectorAll(selector)).filter((match) => this.matchElement(match));\n return match.concat(matches);\n }\n else {\n return [];\n }\n }\n elementMatched(element) {\n const { selector } = this;\n if (selector) {\n this.selectorMatched(element, selector);\n }\n }\n elementUnmatched(element) {\n const selectors = this.matchesByElement.getKeysForValue(element);\n for (const selector of selectors) {\n this.selectorUnmatched(element, selector);\n }\n }\n elementAttributeChanged(element, _attributeName) {\n const { selector } = this;\n if (selector) {\n const matches = this.matchElement(element);\n const matchedBefore = this.matchesByElement.has(selector, element);\n if (matches && !matchedBefore) {\n this.selectorMatched(element, selector);\n }\n else if (!matches && matchedBefore) {\n this.selectorUnmatched(element, selector);\n }\n }\n }\n selectorMatched(element, selector) {\n this.delegate.selectorMatched(element, selector, this.details);\n this.matchesByElement.add(selector, element);\n }\n selectorUnmatched(element, selector) {\n this.delegate.selectorUnmatched(element, selector, this.details);\n this.matchesByElement.delete(selector, element);\n }\n}\n\nclass StringMapObserver {\n constructor(element, delegate) {\n this.element = element;\n this.delegate = delegate;\n this.started = false;\n this.stringMap = new Map();\n this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.mutationObserver.observe(this.element, { attributes: true, attributeOldValue: true });\n this.refresh();\n }\n }\n stop() {\n if (this.started) {\n this.mutationObserver.takeRecords();\n this.mutationObserver.disconnect();\n this.started = false;\n }\n }\n refresh() {\n if (this.started) {\n for (const attributeName of this.knownAttributeNames) {\n this.refreshAttribute(attributeName, null);\n }\n }\n }\n processMutations(mutations) {\n if (this.started) {\n for (const mutation of mutations) {\n this.processMutation(mutation);\n }\n }\n }\n processMutation(mutation) {\n const attributeName = mutation.attributeName;\n if (attributeName) {\n this.refreshAttribute(attributeName, mutation.oldValue);\n }\n }\n refreshAttribute(attributeName, oldValue) {\n const key = this.delegate.getStringMapKeyForAttribute(attributeName);\n if (key != null) {\n if (!this.stringMap.has(attributeName)) {\n this.stringMapKeyAdded(key, attributeName);\n }\n const value = this.element.getAttribute(attributeName);\n if (this.stringMap.get(attributeName) != value) {\n this.stringMapValueChanged(value, key, oldValue);\n }\n if (value == null) {\n const oldValue = this.stringMap.get(attributeName);\n this.stringMap.delete(attributeName);\n if (oldValue)\n this.stringMapKeyRemoved(key, attributeName, oldValue);\n }\n else {\n this.stringMap.set(attributeName, value);\n }\n }\n }\n stringMapKeyAdded(key, attributeName) {\n if (this.delegate.stringMapKeyAdded) {\n this.delegate.stringMapKeyAdded(key, attributeName);\n }\n }\n stringMapValueChanged(value, key, oldValue) {\n if (this.delegate.stringMapValueChanged) {\n this.delegate.stringMapValueChanged(value, key, oldValue);\n }\n }\n stringMapKeyRemoved(key, attributeName, oldValue) {\n if (this.delegate.stringMapKeyRemoved) {\n this.delegate.stringMapKeyRemoved(key, attributeName, oldValue);\n }\n }\n get knownAttributeNames() {\n return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)));\n }\n get currentAttributeNames() {\n return Array.from(this.element.attributes).map((attribute) => attribute.name);\n }\n get recordedAttributeNames() {\n return Array.from(this.stringMap.keys());\n }\n}\n\nclass TokenListObserver {\n constructor(element, attributeName, delegate) {\n this.attributeObserver = new AttributeObserver(element, attributeName, this);\n this.delegate = delegate;\n this.tokensByElement = new Multimap();\n }\n get started() {\n return this.attributeObserver.started;\n }\n start() {\n this.attributeObserver.start();\n }\n pause(callback) {\n this.attributeObserver.pause(callback);\n }\n stop() {\n this.attributeObserver.stop();\n }\n refresh() {\n this.attributeObserver.refresh();\n }\n get element() {\n return this.attributeObserver.element;\n }\n get attributeName() {\n return this.attributeObserver.attributeName;\n }\n elementMatchedAttribute(element) {\n this.tokensMatched(this.readTokensForElement(element));\n }\n elementAttributeValueChanged(element) {\n const [unmatchedTokens, matchedTokens] = this.refreshTokensForElement(element);\n this.tokensUnmatched(unmatchedTokens);\n this.tokensMatched(matchedTokens);\n }\n elementUnmatchedAttribute(element) {\n this.tokensUnmatched(this.tokensByElement.getValuesForKey(element));\n }\n tokensMatched(tokens) {\n tokens.forEach((token) => this.tokenMatched(token));\n }\n tokensUnmatched(tokens) {\n tokens.forEach((token) => this.tokenUnmatched(token));\n }\n tokenMatched(token) {\n this.delegate.tokenMatched(token);\n this.tokensByElement.add(token.element, token);\n }\n tokenUnmatched(token) {\n this.delegate.tokenUnmatched(token);\n this.tokensByElement.delete(token.element, token);\n }\n refreshTokensForElement(element) {\n const previousTokens = this.tokensByElement.getValuesForKey(element);\n const currentTokens = this.readTokensForElement(element);\n const firstDifferingIndex = zip(previousTokens, currentTokens).findIndex(([previousToken, currentToken]) => !tokensAreEqual(previousToken, currentToken));\n if (firstDifferingIndex == -1) {\n return [[], []];\n }\n else {\n return [previousTokens.slice(firstDifferingIndex), currentTokens.slice(firstDifferingIndex)];\n }\n }\n readTokensForElement(element) {\n const attributeName = this.attributeName;\n const tokenString = element.getAttribute(attributeName) || \"\";\n return parseTokenString(tokenString, element, attributeName);\n }\n}\nfunction parseTokenString(tokenString, element, attributeName) {\n return tokenString\n .trim()\n .split(/\\s+/)\n .filter((content) => content.length)\n .map((content, index) => ({ element, attributeName, content, index }));\n}\nfunction zip(left, right) {\n const length = Math.max(left.length, right.length);\n return Array.from({ length }, (_, index) => [left[index], right[index]]);\n}\nfunction tokensAreEqual(left, right) {\n return left && right && left.index == right.index && left.content == right.content;\n}\n\nclass ValueListObserver {\n constructor(element, attributeName, delegate) {\n this.tokenListObserver = new TokenListObserver(element, attributeName, this);\n this.delegate = delegate;\n this.parseResultsByToken = new WeakMap();\n this.valuesByTokenByElement = new WeakMap();\n }\n get started() {\n return this.tokenListObserver.started;\n }\n start() {\n this.tokenListObserver.start();\n }\n stop() {\n this.tokenListObserver.stop();\n }\n refresh() {\n this.tokenListObserver.refresh();\n }\n get element() {\n return this.tokenListObserver.element;\n }\n get attributeName() {\n return this.tokenListObserver.attributeName;\n }\n tokenMatched(token) {\n const { element } = token;\n const { value } = this.fetchParseResultForToken(token);\n if (value) {\n this.fetchValuesByTokenForElement(element).set(token, value);\n this.delegate.elementMatchedValue(element, value);\n }\n }\n tokenUnmatched(token) {\n const { element } = token;\n const { value } = this.fetchParseResultForToken(token);\n if (value) {\n this.fetchValuesByTokenForElement(element).delete(token);\n this.delegate.elementUnmatchedValue(element, value);\n }\n }\n fetchParseResultForToken(token) {\n let parseResult = this.parseResultsByToken.get(token);\n if (!parseResult) {\n parseResult = this.parseToken(token);\n this.parseResultsByToken.set(token, parseResult);\n }\n return parseResult;\n }\n fetchValuesByTokenForElement(element) {\n let valuesByToken = this.valuesByTokenByElement.get(element);\n if (!valuesByToken) {\n valuesByToken = new Map();\n this.valuesByTokenByElement.set(element, valuesByToken);\n }\n return valuesByToken;\n }\n parseToken(token) {\n try {\n const value = this.delegate.parseValueForToken(token);\n return { value };\n }\n catch (error) {\n return { error };\n }\n }\n}\n\nclass BindingObserver {\n constructor(context, delegate) {\n this.context = context;\n this.delegate = delegate;\n this.bindingsByAction = new Map();\n }\n start() {\n if (!this.valueListObserver) {\n this.valueListObserver = new ValueListObserver(this.element, this.actionAttribute, this);\n this.valueListObserver.start();\n }\n }\n stop() {\n if (this.valueListObserver) {\n this.valueListObserver.stop();\n delete this.valueListObserver;\n this.disconnectAllActions();\n }\n }\n get element() {\n return this.context.element;\n }\n get identifier() {\n return this.context.identifier;\n }\n get actionAttribute() {\n return this.schema.actionAttribute;\n }\n get schema() {\n return this.context.schema;\n }\n get bindings() {\n return Array.from(this.bindingsByAction.values());\n }\n connectAction(action) {\n const binding = new Binding(this.context, action);\n this.bindingsByAction.set(action, binding);\n this.delegate.bindingConnected(binding);\n }\n disconnectAction(action) {\n const binding = this.bindingsByAction.get(action);\n if (binding) {\n this.bindingsByAction.delete(action);\n this.delegate.bindingDisconnected(binding);\n }\n }\n disconnectAllActions() {\n this.bindings.forEach((binding) => this.delegate.bindingDisconnected(binding, true));\n this.bindingsByAction.clear();\n }\n parseValueForToken(token) {\n const action = Action.forToken(token, this.schema);\n if (action.identifier == this.identifier) {\n return action;\n }\n }\n elementMatchedValue(element, action) {\n this.connectAction(action);\n }\n elementUnmatchedValue(element, action) {\n this.disconnectAction(action);\n }\n}\n\nclass ValueObserver {\n constructor(context, receiver) {\n this.context = context;\n this.receiver = receiver;\n this.stringMapObserver = new StringMapObserver(this.element, this);\n this.valueDescriptorMap = this.controller.valueDescriptorMap;\n }\n start() {\n this.stringMapObserver.start();\n this.invokeChangedCallbacksForDefaultValues();\n }\n stop() {\n this.stringMapObserver.stop();\n }\n get element() {\n return this.context.element;\n }\n get controller() {\n return this.context.controller;\n }\n getStringMapKeyForAttribute(attributeName) {\n if (attributeName in this.valueDescriptorMap) {\n return this.valueDescriptorMap[attributeName].name;\n }\n }\n stringMapKeyAdded(key, attributeName) {\n const descriptor = this.valueDescriptorMap[attributeName];\n if (!this.hasValue(key)) {\n this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), descriptor.writer(descriptor.defaultValue));\n }\n }\n stringMapValueChanged(value, name, oldValue) {\n const descriptor = this.valueDescriptorNameMap[name];\n if (value === null)\n return;\n if (oldValue === null) {\n oldValue = descriptor.writer(descriptor.defaultValue);\n }\n this.invokeChangedCallback(name, value, oldValue);\n }\n stringMapKeyRemoved(key, attributeName, oldValue) {\n const descriptor = this.valueDescriptorNameMap[key];\n if (this.hasValue(key)) {\n this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), oldValue);\n }\n else {\n this.invokeChangedCallback(key, descriptor.writer(descriptor.defaultValue), oldValue);\n }\n }\n invokeChangedCallbacksForDefaultValues() {\n for (const { key, name, defaultValue, writer } of this.valueDescriptors) {\n if (defaultValue != undefined && !this.controller.data.has(key)) {\n this.invokeChangedCallback(name, writer(defaultValue), undefined);\n }\n }\n }\n invokeChangedCallback(name, rawValue, rawOldValue) {\n const changedMethodName = `${name}Changed`;\n const changedMethod = this.receiver[changedMethodName];\n if (typeof changedMethod == \"function\") {\n const descriptor = this.valueDescriptorNameMap[name];\n try {\n const value = descriptor.reader(rawValue);\n let oldValue = rawOldValue;\n if (rawOldValue) {\n oldValue = descriptor.reader(rawOldValue);\n }\n changedMethod.call(this.receiver, value, oldValue);\n }\n catch (error) {\n if (error instanceof TypeError) {\n error.message = `Stimulus Value \"${this.context.identifier}.${descriptor.name}\" - ${error.message}`;\n }\n throw error;\n }\n }\n }\n get valueDescriptors() {\n const { valueDescriptorMap } = this;\n return Object.keys(valueDescriptorMap).map((key) => valueDescriptorMap[key]);\n }\n get valueDescriptorNameMap() {\n const descriptors = {};\n Object.keys(this.valueDescriptorMap).forEach((key) => {\n const descriptor = this.valueDescriptorMap[key];\n descriptors[descriptor.name] = descriptor;\n });\n return descriptors;\n }\n hasValue(attributeName) {\n const descriptor = this.valueDescriptorNameMap[attributeName];\n const hasMethodName = `has${capitalize(descriptor.name)}`;\n return this.receiver[hasMethodName];\n }\n}\n\nclass TargetObserver {\n constructor(context, delegate) {\n this.context = context;\n this.delegate = delegate;\n this.targetsByName = new Multimap();\n }\n start() {\n if (!this.tokenListObserver) {\n this.tokenListObserver = new TokenListObserver(this.element, this.attributeName, this);\n this.tokenListObserver.start();\n }\n }\n stop() {\n if (this.tokenListObserver) {\n this.disconnectAllTargets();\n this.tokenListObserver.stop();\n delete this.tokenListObserver;\n }\n }\n tokenMatched({ element, content: name }) {\n if (this.scope.containsElement(element)) {\n this.connectTarget(element, name);\n }\n }\n tokenUnmatched({ element, content: name }) {\n this.disconnectTarget(element, name);\n }\n connectTarget(element, name) {\n var _a;\n if (!this.targetsByName.has(name, element)) {\n this.targetsByName.add(name, element);\n (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetConnected(element, name));\n }\n }\n disconnectTarget(element, name) {\n var _a;\n if (this.targetsByName.has(name, element)) {\n this.targetsByName.delete(name, element);\n (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetDisconnected(element, name));\n }\n }\n disconnectAllTargets() {\n for (const name of this.targetsByName.keys) {\n for (const element of this.targetsByName.getValuesForKey(name)) {\n this.disconnectTarget(element, name);\n }\n }\n }\n get attributeName() {\n return `data-${this.context.identifier}-target`;\n }\n get element() {\n return this.context.element;\n }\n get scope() {\n return this.context.scope;\n }\n}\n\nfunction readInheritableStaticArrayValues(constructor, propertyName) {\n const ancestors = getAncestorsForConstructor(constructor);\n return Array.from(ancestors.reduce((values, constructor) => {\n getOwnStaticArrayValues(constructor, propertyName).forEach((name) => values.add(name));\n return values;\n }, new Set()));\n}\nfunction readInheritableStaticObjectPairs(constructor, propertyName) {\n const ancestors = getAncestorsForConstructor(constructor);\n return ancestors.reduce((pairs, constructor) => {\n pairs.push(...getOwnStaticObjectPairs(constructor, propertyName));\n return pairs;\n }, []);\n}\nfunction getAncestorsForConstructor(constructor) {\n const ancestors = [];\n while (constructor) {\n ancestors.push(constructor);\n constructor = Object.getPrototypeOf(constructor);\n }\n return ancestors.reverse();\n}\nfunction getOwnStaticArrayValues(constructor, propertyName) {\n const definition = constructor[propertyName];\n return Array.isArray(definition) ? definition : [];\n}\nfunction getOwnStaticObjectPairs(constructor, propertyName) {\n const definition = constructor[propertyName];\n return definition ? Object.keys(definition).map((key) => [key, definition[key]]) : [];\n}\n\nclass OutletObserver {\n constructor(context, delegate) {\n this.started = false;\n this.context = context;\n this.delegate = delegate;\n this.outletsByName = new Multimap();\n this.outletElementsByName = new Multimap();\n this.selectorObserverMap = new Map();\n this.attributeObserverMap = new Map();\n }\n start() {\n if (!this.started) {\n this.outletDefinitions.forEach((outletName) => {\n this.setupSelectorObserverForOutlet(outletName);\n this.setupAttributeObserverForOutlet(outletName);\n });\n this.started = true;\n this.dependentContexts.forEach((context) => context.refresh());\n }\n }\n refresh() {\n this.selectorObserverMap.forEach((observer) => observer.refresh());\n this.attributeObserverMap.forEach((observer) => observer.refresh());\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.disconnectAllOutlets();\n this.stopSelectorObservers();\n this.stopAttributeObservers();\n }\n }\n stopSelectorObservers() {\n if (this.selectorObserverMap.size > 0) {\n this.selectorObserverMap.forEach((observer) => observer.stop());\n this.selectorObserverMap.clear();\n }\n }\n stopAttributeObservers() {\n if (this.attributeObserverMap.size > 0) {\n this.attributeObserverMap.forEach((observer) => observer.stop());\n this.attributeObserverMap.clear();\n }\n }\n selectorMatched(element, _selector, { outletName }) {\n const outlet = this.getOutlet(element, outletName);\n if (outlet) {\n this.connectOutlet(outlet, element, outletName);\n }\n }\n selectorUnmatched(element, _selector, { outletName }) {\n const outlet = this.getOutletFromMap(element, outletName);\n if (outlet) {\n this.disconnectOutlet(outlet, element, outletName);\n }\n }\n selectorMatchElement(element, { outletName }) {\n const selector = this.selector(outletName);\n const hasOutlet = this.hasOutlet(element, outletName);\n const hasOutletController = element.matches(`[${this.schema.controllerAttribute}~=${outletName}]`);\n if (selector) {\n return hasOutlet && hasOutletController && element.matches(selector);\n }\n else {\n return false;\n }\n }\n elementMatchedAttribute(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n elementAttributeValueChanged(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n elementUnmatchedAttribute(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n connectOutlet(outlet, element, outletName) {\n var _a;\n if (!this.outletElementsByName.has(outletName, element)) {\n this.outletsByName.add(outletName, outlet);\n this.outletElementsByName.add(outletName, element);\n (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletConnected(outlet, element, outletName));\n }\n }\n disconnectOutlet(outlet, element, outletName) {\n var _a;\n if (this.outletElementsByName.has(outletName, element)) {\n this.outletsByName.delete(outletName, outlet);\n this.outletElementsByName.delete(outletName, element);\n (_a = this.selectorObserverMap\n .get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletDisconnected(outlet, element, outletName));\n }\n }\n disconnectAllOutlets() {\n for (const outletName of this.outletElementsByName.keys) {\n for (const element of this.outletElementsByName.getValuesForKey(outletName)) {\n for (const outlet of this.outletsByName.getValuesForKey(outletName)) {\n this.disconnectOutlet(outlet, element, outletName);\n }\n }\n }\n }\n updateSelectorObserverForOutlet(outletName) {\n const observer = this.selectorObserverMap.get(outletName);\n if (observer) {\n observer.selector = this.selector(outletName);\n }\n }\n setupSelectorObserverForOutlet(outletName) {\n const selector = this.selector(outletName);\n const selectorObserver = new SelectorObserver(document.body, selector, this, { outletName });\n this.selectorObserverMap.set(outletName, selectorObserver);\n selectorObserver.start();\n }\n setupAttributeObserverForOutlet(outletName) {\n const attributeName = this.attributeNameForOutletName(outletName);\n const attributeObserver = new AttributeObserver(this.scope.element, attributeName, this);\n this.attributeObserverMap.set(outletName, attributeObserver);\n attributeObserver.start();\n }\n selector(outletName) {\n return this.scope.outlets.getSelectorForOutletName(outletName);\n }\n attributeNameForOutletName(outletName) {\n return this.scope.schema.outletAttributeForScope(this.identifier, outletName);\n }\n getOutletNameFromOutletAttributeName(attributeName) {\n return this.outletDefinitions.find((outletName) => this.attributeNameForOutletName(outletName) === attributeName);\n }\n get outletDependencies() {\n const dependencies = new Multimap();\n this.router.modules.forEach((module) => {\n const constructor = module.definition.controllerConstructor;\n const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n outlets.forEach((outlet) => dependencies.add(outlet, module.identifier));\n });\n return dependencies;\n }\n get outletDefinitions() {\n return this.outletDependencies.getKeysForValue(this.identifier);\n }\n get dependentControllerIdentifiers() {\n return this.outletDependencies.getValuesForKey(this.identifier);\n }\n get dependentContexts() {\n const identifiers = this.dependentControllerIdentifiers;\n return this.router.contexts.filter((context) => identifiers.includes(context.identifier));\n }\n hasOutlet(element, outletName) {\n return !!this.getOutlet(element, outletName) || !!this.getOutletFromMap(element, outletName);\n }\n getOutlet(element, outletName) {\n return this.application.getControllerForElementAndIdentifier(element, outletName);\n }\n getOutletFromMap(element, outletName) {\n return this.outletsByName.getValuesForKey(outletName).find((outlet) => outlet.element === element);\n }\n get scope() {\n return this.context.scope;\n }\n get schema() {\n return this.context.schema;\n }\n get identifier() {\n return this.context.identifier;\n }\n get application() {\n return this.context.application;\n }\n get router() {\n return this.application.router;\n }\n}\n\nclass Context {\n constructor(module, scope) {\n this.logDebugActivity = (functionName, detail = {}) => {\n const { identifier, controller, element } = this;\n detail = Object.assign({ identifier, controller, element }, detail);\n this.application.logDebugActivity(this.identifier, functionName, detail);\n };\n this.module = module;\n this.scope = scope;\n this.controller = new module.controllerConstructor(this);\n this.bindingObserver = new BindingObserver(this, this.dispatcher);\n this.valueObserver = new ValueObserver(this, this.controller);\n this.targetObserver = new TargetObserver(this, this);\n this.outletObserver = new OutletObserver(this, this);\n try {\n this.controller.initialize();\n this.logDebugActivity(\"initialize\");\n }\n catch (error) {\n this.handleError(error, \"initializing controller\");\n }\n }\n connect() {\n this.bindingObserver.start();\n this.valueObserver.start();\n this.targetObserver.start();\n this.outletObserver.start();\n try {\n this.controller.connect();\n this.logDebugActivity(\"connect\");\n }\n catch (error) {\n this.handleError(error, \"connecting controller\");\n }\n }\n refresh() {\n this.outletObserver.refresh();\n }\n disconnect() {\n try {\n this.controller.disconnect();\n this.logDebugActivity(\"disconnect\");\n }\n catch (error) {\n this.handleError(error, \"disconnecting controller\");\n }\n this.outletObserver.stop();\n this.targetObserver.stop();\n this.valueObserver.stop();\n this.bindingObserver.stop();\n }\n get application() {\n return this.module.application;\n }\n get identifier() {\n return this.module.identifier;\n }\n get schema() {\n return this.application.schema;\n }\n get dispatcher() {\n return this.application.dispatcher;\n }\n get element() {\n return this.scope.element;\n }\n get parentElement() {\n return this.element.parentElement;\n }\n handleError(error, message, detail = {}) {\n const { identifier, controller, element } = this;\n detail = Object.assign({ identifier, controller, element }, detail);\n this.application.handleError(error, `Error ${message}`, detail);\n }\n targetConnected(element, name) {\n this.invokeControllerMethod(`${name}TargetConnected`, element);\n }\n targetDisconnected(element, name) {\n this.invokeControllerMethod(`${name}TargetDisconnected`, element);\n }\n outletConnected(outlet, element, name) {\n this.invokeControllerMethod(`${namespaceCamelize(name)}OutletConnected`, outlet, element);\n }\n outletDisconnected(outlet, element, name) {\n this.invokeControllerMethod(`${namespaceCamelize(name)}OutletDisconnected`, outlet, element);\n }\n invokeControllerMethod(methodName, ...args) {\n const controller = this.controller;\n if (typeof controller[methodName] == \"function\") {\n controller[methodName](...args);\n }\n }\n}\n\nfunction bless(constructor) {\n return shadow(constructor, getBlessedProperties(constructor));\n}\nfunction shadow(constructor, properties) {\n const shadowConstructor = extend(constructor);\n const shadowProperties = getShadowProperties(constructor.prototype, properties);\n Object.defineProperties(shadowConstructor.prototype, shadowProperties);\n return shadowConstructor;\n}\nfunction getBlessedProperties(constructor) {\n const blessings = readInheritableStaticArrayValues(constructor, \"blessings\");\n return blessings.reduce((blessedProperties, blessing) => {\n const properties = blessing(constructor);\n for (const key in properties) {\n const descriptor = blessedProperties[key] || {};\n blessedProperties[key] = Object.assign(descriptor, properties[key]);\n }\n return blessedProperties;\n }, {});\n}\nfunction getShadowProperties(prototype, properties) {\n return getOwnKeys(properties).reduce((shadowProperties, key) => {\n const descriptor = getShadowedDescriptor(prototype, properties, key);\n if (descriptor) {\n Object.assign(shadowProperties, { [key]: descriptor });\n }\n return shadowProperties;\n }, {});\n}\nfunction getShadowedDescriptor(prototype, properties, key) {\n const shadowingDescriptor = Object.getOwnPropertyDescriptor(prototype, key);\n const shadowedByValue = shadowingDescriptor && \"value\" in shadowingDescriptor;\n if (!shadowedByValue) {\n const descriptor = Object.getOwnPropertyDescriptor(properties, key).value;\n if (shadowingDescriptor) {\n descriptor.get = shadowingDescriptor.get || descriptor.get;\n descriptor.set = shadowingDescriptor.set || descriptor.set;\n }\n return descriptor;\n }\n}\nconst getOwnKeys = (() => {\n if (typeof Object.getOwnPropertySymbols == \"function\") {\n return (object) => [...Object.getOwnPropertyNames(object), ...Object.getOwnPropertySymbols(object)];\n }\n else {\n return Object.getOwnPropertyNames;\n }\n})();\nconst extend = (() => {\n function extendWithReflect(constructor) {\n function extended() {\n return Reflect.construct(constructor, arguments, new.target);\n }\n extended.prototype = Object.create(constructor.prototype, {\n constructor: { value: extended },\n });\n Reflect.setPrototypeOf(extended, constructor);\n return extended;\n }\n function testReflectExtension() {\n const a = function () {\n this.a.call(this);\n };\n const b = extendWithReflect(a);\n b.prototype.a = function () { };\n return new b();\n }\n try {\n testReflectExtension();\n return extendWithReflect;\n }\n catch (error) {\n return (constructor) => class extended extends constructor {\n };\n }\n})();\n\nfunction blessDefinition(definition) {\n return {\n identifier: definition.identifier,\n controllerConstructor: bless(definition.controllerConstructor),\n };\n}\n\nclass Module {\n constructor(application, definition) {\n this.application = application;\n this.definition = blessDefinition(definition);\n this.contextsByScope = new WeakMap();\n this.connectedContexts = new Set();\n }\n get identifier() {\n return this.definition.identifier;\n }\n get controllerConstructor() {\n return this.definition.controllerConstructor;\n }\n get contexts() {\n return Array.from(this.connectedContexts);\n }\n connectContextForScope(scope) {\n const context = this.fetchContextForScope(scope);\n this.connectedContexts.add(context);\n context.connect();\n }\n disconnectContextForScope(scope) {\n const context = this.contextsByScope.get(scope);\n if (context) {\n this.connectedContexts.delete(context);\n context.disconnect();\n }\n }\n fetchContextForScope(scope) {\n let context = this.contextsByScope.get(scope);\n if (!context) {\n context = new Context(this, scope);\n this.contextsByScope.set(scope, context);\n }\n return context;\n }\n}\n\nclass ClassMap {\n constructor(scope) {\n this.scope = scope;\n }\n has(name) {\n return this.data.has(this.getDataKey(name));\n }\n get(name) {\n return this.getAll(name)[0];\n }\n getAll(name) {\n const tokenString = this.data.get(this.getDataKey(name)) || \"\";\n return tokenize(tokenString);\n }\n getAttributeName(name) {\n return this.data.getAttributeNameForKey(this.getDataKey(name));\n }\n getDataKey(name) {\n return `${name}-class`;\n }\n get data() {\n return this.scope.data;\n }\n}\n\nclass DataMap {\n constructor(scope) {\n this.scope = scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get(key) {\n const name = this.getAttributeNameForKey(key);\n return this.element.getAttribute(name);\n }\n set(key, value) {\n const name = this.getAttributeNameForKey(key);\n this.element.setAttribute(name, value);\n return this.get(key);\n }\n has(key) {\n const name = this.getAttributeNameForKey(key);\n return this.element.hasAttribute(name);\n }\n delete(key) {\n if (this.has(key)) {\n const name = this.getAttributeNameForKey(key);\n this.element.removeAttribute(name);\n return true;\n }\n else {\n return false;\n }\n }\n getAttributeNameForKey(key) {\n return `data-${this.identifier}-${dasherize(key)}`;\n }\n}\n\nclass Guide {\n constructor(logger) {\n this.warnedKeysByObject = new WeakMap();\n this.logger = logger;\n }\n warn(object, key, message) {\n let warnedKeys = this.warnedKeysByObject.get(object);\n if (!warnedKeys) {\n warnedKeys = new Set();\n this.warnedKeysByObject.set(object, warnedKeys);\n }\n if (!warnedKeys.has(key)) {\n warnedKeys.add(key);\n this.logger.warn(message, object);\n }\n }\n}\n\nfunction attributeValueContainsToken(attributeName, token) {\n return `[${attributeName}~=\"${token}\"]`;\n}\n\nclass TargetSet {\n constructor(scope) {\n this.scope = scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get schema() {\n return this.scope.schema;\n }\n has(targetName) {\n return this.find(targetName) != null;\n }\n find(...targetNames) {\n return targetNames.reduce((target, targetName) => target || this.findTarget(targetName) || this.findLegacyTarget(targetName), undefined);\n }\n findAll(...targetNames) {\n return targetNames.reduce((targets, targetName) => [\n ...targets,\n ...this.findAllTargets(targetName),\n ...this.findAllLegacyTargets(targetName),\n ], []);\n }\n findTarget(targetName) {\n const selector = this.getSelectorForTargetName(targetName);\n return this.scope.findElement(selector);\n }\n findAllTargets(targetName) {\n const selector = this.getSelectorForTargetName(targetName);\n return this.scope.findAllElements(selector);\n }\n getSelectorForTargetName(targetName) {\n const attributeName = this.schema.targetAttributeForScope(this.identifier);\n return attributeValueContainsToken(attributeName, targetName);\n }\n findLegacyTarget(targetName) {\n const selector = this.getLegacySelectorForTargetName(targetName);\n return this.deprecate(this.scope.findElement(selector), targetName);\n }\n findAllLegacyTargets(targetName) {\n const selector = this.getLegacySelectorForTargetName(targetName);\n return this.scope.findAllElements(selector).map((element) => this.deprecate(element, targetName));\n }\n getLegacySelectorForTargetName(targetName) {\n const targetDescriptor = `${this.identifier}.${targetName}`;\n return attributeValueContainsToken(this.schema.targetAttribute, targetDescriptor);\n }\n deprecate(element, targetName) {\n if (element) {\n const { identifier } = this;\n const attributeName = this.schema.targetAttribute;\n const revisedAttributeName = this.schema.targetAttributeForScope(identifier);\n this.guide.warn(element, `target:${targetName}`, `Please replace ${attributeName}=\"${identifier}.${targetName}\" with ${revisedAttributeName}=\"${targetName}\". ` +\n `The ${attributeName} attribute is deprecated and will be removed in a future version of Stimulus.`);\n }\n return element;\n }\n get guide() {\n return this.scope.guide;\n }\n}\n\nclass OutletSet {\n constructor(scope, controllerElement) {\n this.scope = scope;\n this.controllerElement = controllerElement;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get schema() {\n return this.scope.schema;\n }\n has(outletName) {\n return this.find(outletName) != null;\n }\n find(...outletNames) {\n return outletNames.reduce((outlet, outletName) => outlet || this.findOutlet(outletName), undefined);\n }\n findAll(...outletNames) {\n return outletNames.reduce((outlets, outletName) => [...outlets, ...this.findAllOutlets(outletName)], []);\n }\n getSelectorForOutletName(outletName) {\n const attributeName = this.schema.outletAttributeForScope(this.identifier, outletName);\n return this.controllerElement.getAttribute(attributeName);\n }\n findOutlet(outletName) {\n const selector = this.getSelectorForOutletName(outletName);\n if (selector)\n return this.findElement(selector, outletName);\n }\n findAllOutlets(outletName) {\n const selector = this.getSelectorForOutletName(outletName);\n return selector ? this.findAllElements(selector, outletName) : [];\n }\n findElement(selector, outletName) {\n const elements = this.scope.queryElements(selector);\n return elements.filter((element) => this.matchesElement(element, selector, outletName))[0];\n }\n findAllElements(selector, outletName) {\n const elements = this.scope.queryElements(selector);\n return elements.filter((element) => this.matchesElement(element, selector, outletName));\n }\n matchesElement(element, selector, outletName) {\n const controllerAttribute = element.getAttribute(this.scope.schema.controllerAttribute) || \"\";\n return element.matches(selector) && controllerAttribute.split(\" \").includes(outletName);\n }\n}\n\nclass Scope {\n constructor(schema, element, identifier, logger) {\n this.targets = new TargetSet(this);\n this.classes = new ClassMap(this);\n this.data = new DataMap(this);\n this.containsElement = (element) => {\n return element.closest(this.controllerSelector) === this.element;\n };\n this.schema = schema;\n this.element = element;\n this.identifier = identifier;\n this.guide = new Guide(logger);\n this.outlets = new OutletSet(this.documentScope, element);\n }\n findElement(selector) {\n return this.element.matches(selector) ? this.element : this.queryElements(selector).find(this.containsElement);\n }\n findAllElements(selector) {\n return [\n ...(this.element.matches(selector) ? [this.element] : []),\n ...this.queryElements(selector).filter(this.containsElement),\n ];\n }\n queryElements(selector) {\n return Array.from(this.element.querySelectorAll(selector));\n }\n get controllerSelector() {\n return attributeValueContainsToken(this.schema.controllerAttribute, this.identifier);\n }\n get isDocumentScope() {\n return this.element === document.documentElement;\n }\n get documentScope() {\n return this.isDocumentScope\n ? this\n : new Scope(this.schema, document.documentElement, this.identifier, this.guide.logger);\n }\n}\n\nclass ScopeObserver {\n constructor(element, schema, delegate) {\n this.element = element;\n this.schema = schema;\n this.delegate = delegate;\n this.valueListObserver = new ValueListObserver(this.element, this.controllerAttribute, this);\n this.scopesByIdentifierByElement = new WeakMap();\n this.scopeReferenceCounts = new WeakMap();\n }\n start() {\n this.valueListObserver.start();\n }\n stop() {\n this.valueListObserver.stop();\n }\n get controllerAttribute() {\n return this.schema.controllerAttribute;\n }\n parseValueForToken(token) {\n const { element, content: identifier } = token;\n return this.parseValueForElementAndIdentifier(element, identifier);\n }\n parseValueForElementAndIdentifier(element, identifier) {\n const scopesByIdentifier = this.fetchScopesByIdentifierForElement(element);\n let scope = scopesByIdentifier.get(identifier);\n if (!scope) {\n scope = this.delegate.createScopeForElementAndIdentifier(element, identifier);\n scopesByIdentifier.set(identifier, scope);\n }\n return scope;\n }\n elementMatchedValue(element, value) {\n const referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1;\n this.scopeReferenceCounts.set(value, referenceCount);\n if (referenceCount == 1) {\n this.delegate.scopeConnected(value);\n }\n }\n elementUnmatchedValue(element, value) {\n const referenceCount = this.scopeReferenceCounts.get(value);\n if (referenceCount) {\n this.scopeReferenceCounts.set(value, referenceCount - 1);\n if (referenceCount == 1) {\n this.delegate.scopeDisconnected(value);\n }\n }\n }\n fetchScopesByIdentifierForElement(element) {\n let scopesByIdentifier = this.scopesByIdentifierByElement.get(element);\n if (!scopesByIdentifier) {\n scopesByIdentifier = new Map();\n this.scopesByIdentifierByElement.set(element, scopesByIdentifier);\n }\n return scopesByIdentifier;\n }\n}\n\nclass Router {\n constructor(application) {\n this.application = application;\n this.scopeObserver = new ScopeObserver(this.element, this.schema, this);\n this.scopesByIdentifier = new Multimap();\n this.modulesByIdentifier = new Map();\n }\n get element() {\n return this.application.element;\n }\n get schema() {\n return this.application.schema;\n }\n get logger() {\n return this.application.logger;\n }\n get controllerAttribute() {\n return this.schema.controllerAttribute;\n }\n get modules() {\n return Array.from(this.modulesByIdentifier.values());\n }\n get contexts() {\n return this.modules.reduce((contexts, module) => contexts.concat(module.contexts), []);\n }\n start() {\n this.scopeObserver.start();\n }\n stop() {\n this.scopeObserver.stop();\n }\n loadDefinition(definition) {\n this.unloadIdentifier(definition.identifier);\n const module = new Module(this.application, definition);\n this.connectModule(module);\n const afterLoad = definition.controllerConstructor.afterLoad;\n if (afterLoad) {\n afterLoad.call(definition.controllerConstructor, definition.identifier, this.application);\n }\n }\n unloadIdentifier(identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n this.disconnectModule(module);\n }\n }\n getContextForElementAndIdentifier(element, identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n return module.contexts.find((context) => context.element == element);\n }\n }\n proposeToConnectScopeForElementAndIdentifier(element, identifier) {\n const scope = this.scopeObserver.parseValueForElementAndIdentifier(element, identifier);\n if (scope) {\n this.scopeObserver.elementMatchedValue(scope.element, scope);\n }\n else {\n console.error(`Couldn't find or create scope for identifier: \"${identifier}\" and element:`, element);\n }\n }\n handleError(error, message, detail) {\n this.application.handleError(error, message, detail);\n }\n createScopeForElementAndIdentifier(element, identifier) {\n return new Scope(this.schema, element, identifier, this.logger);\n }\n scopeConnected(scope) {\n this.scopesByIdentifier.add(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.connectContextForScope(scope);\n }\n }\n scopeDisconnected(scope) {\n this.scopesByIdentifier.delete(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.disconnectContextForScope(scope);\n }\n }\n connectModule(module) {\n this.modulesByIdentifier.set(module.identifier, module);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach((scope) => module.connectContextForScope(scope));\n }\n disconnectModule(module) {\n this.modulesByIdentifier.delete(module.identifier);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach((scope) => module.disconnectContextForScope(scope));\n }\n}\n\nconst defaultSchema = {\n controllerAttribute: \"data-controller\",\n actionAttribute: \"data-action\",\n targetAttribute: \"data-target\",\n targetAttributeForScope: (identifier) => `data-${identifier}-target`,\n outletAttributeForScope: (identifier, outlet) => `data-${identifier}-${outlet}-outlet`,\n keyMappings: Object.assign(Object.assign({ enter: \"Enter\", tab: \"Tab\", esc: \"Escape\", space: \" \", up: \"ArrowUp\", down: \"ArrowDown\", left: \"ArrowLeft\", right: \"ArrowRight\", home: \"Home\", end: \"End\", page_up: \"PageUp\", page_down: \"PageDown\" }, objectFromEntries(\"abcdefghijklmnopqrstuvwxyz\".split(\"\").map((c) => [c, c]))), objectFromEntries(\"0123456789\".split(\"\").map((n) => [n, n]))),\n};\nfunction objectFromEntries(array) {\n return array.reduce((memo, [k, v]) => (Object.assign(Object.assign({}, memo), { [k]: v })), {});\n}\n\nclass Application {\n constructor(element = document.documentElement, schema = defaultSchema) {\n this.logger = console;\n this.debug = false;\n this.logDebugActivity = (identifier, functionName, detail = {}) => {\n if (this.debug) {\n this.logFormattedMessage(identifier, functionName, detail);\n }\n };\n this.element = element;\n this.schema = schema;\n this.dispatcher = new Dispatcher(this);\n this.router = new Router(this);\n this.actionDescriptorFilters = Object.assign({}, defaultActionDescriptorFilters);\n }\n static start(element, schema) {\n const application = new this(element, schema);\n application.start();\n return application;\n }\n async start() {\n await domReady();\n this.logDebugActivity(\"application\", \"starting\");\n this.dispatcher.start();\n this.router.start();\n this.logDebugActivity(\"application\", \"start\");\n }\n stop() {\n this.logDebugActivity(\"application\", \"stopping\");\n this.dispatcher.stop();\n this.router.stop();\n this.logDebugActivity(\"application\", \"stop\");\n }\n register(identifier, controllerConstructor) {\n this.load({ identifier, controllerConstructor });\n }\n registerActionOption(name, filter) {\n this.actionDescriptorFilters[name] = filter;\n }\n load(head, ...rest) {\n const definitions = Array.isArray(head) ? head : [head, ...rest];\n definitions.forEach((definition) => {\n if (definition.controllerConstructor.shouldLoad) {\n this.router.loadDefinition(definition);\n }\n });\n }\n unload(head, ...rest) {\n const identifiers = Array.isArray(head) ? head : [head, ...rest];\n identifiers.forEach((identifier) => this.router.unloadIdentifier(identifier));\n }\n get controllers() {\n return this.router.contexts.map((context) => context.controller);\n }\n getControllerForElementAndIdentifier(element, identifier) {\n const context = this.router.getContextForElementAndIdentifier(element, identifier);\n return context ? context.controller : null;\n }\n handleError(error, message, detail) {\n var _a;\n this.logger.error(`%s\\n\\n%o\\n\\n%o`, message, error, detail);\n (_a = window.onerror) === null || _a === void 0 ? void 0 : _a.call(window, message, \"\", 0, 0, error);\n }\n logFormattedMessage(identifier, functionName, detail = {}) {\n detail = Object.assign({ application: this }, detail);\n this.logger.groupCollapsed(`${identifier} #${functionName}`);\n this.logger.log(\"details:\", Object.assign({}, detail));\n this.logger.groupEnd();\n }\n}\nfunction domReady() {\n return new Promise((resolve) => {\n if (document.readyState == \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", () => resolve());\n }\n else {\n resolve();\n }\n });\n}\n\nfunction ClassPropertiesBlessing(constructor) {\n const classes = readInheritableStaticArrayValues(constructor, \"classes\");\n return classes.reduce((properties, classDefinition) => {\n return Object.assign(properties, propertiesForClassDefinition(classDefinition));\n }, {});\n}\nfunction propertiesForClassDefinition(key) {\n return {\n [`${key}Class`]: {\n get() {\n const { classes } = this;\n if (classes.has(key)) {\n return classes.get(key);\n }\n else {\n const attribute = classes.getAttributeName(key);\n throw new Error(`Missing attribute \"${attribute}\"`);\n }\n },\n },\n [`${key}Classes`]: {\n get() {\n return this.classes.getAll(key);\n },\n },\n [`has${capitalize(key)}Class`]: {\n get() {\n return this.classes.has(key);\n },\n },\n };\n}\n\nfunction OutletPropertiesBlessing(constructor) {\n const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n return outlets.reduce((properties, outletDefinition) => {\n return Object.assign(properties, propertiesForOutletDefinition(outletDefinition));\n }, {});\n}\nfunction getOutletController(controller, element, identifier) {\n return controller.application.getControllerForElementAndIdentifier(element, identifier);\n}\nfunction getControllerAndEnsureConnectedScope(controller, element, outletName) {\n let outletController = getOutletController(controller, element, outletName);\n if (outletController)\n return outletController;\n controller.application.router.proposeToConnectScopeForElementAndIdentifier(element, outletName);\n outletController = getOutletController(controller, element, outletName);\n if (outletController)\n return outletController;\n}\nfunction propertiesForOutletDefinition(name) {\n const camelizedName = namespaceCamelize(name);\n return {\n [`${camelizedName}Outlet`]: {\n get() {\n const outletElement = this.outlets.find(name);\n const selector = this.outlets.getSelectorForOutletName(name);\n if (outletElement) {\n const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n if (outletController)\n return outletController;\n throw new Error(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`);\n }\n throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n },\n },\n [`${camelizedName}Outlets`]: {\n get() {\n const outlets = this.outlets.findAll(name);\n if (outlets.length > 0) {\n return outlets\n .map((outletElement) => {\n const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n if (outletController)\n return outletController;\n console.warn(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`, outletElement);\n })\n .filter((controller) => controller);\n }\n return [];\n },\n },\n [`${camelizedName}OutletElement`]: {\n get() {\n const outletElement = this.outlets.find(name);\n const selector = this.outlets.getSelectorForOutletName(name);\n if (outletElement) {\n return outletElement;\n }\n else {\n throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n }\n },\n },\n [`${camelizedName}OutletElements`]: {\n get() {\n return this.outlets.findAll(name);\n },\n },\n [`has${capitalize(camelizedName)}Outlet`]: {\n get() {\n return this.outlets.has(name);\n },\n },\n };\n}\n\nfunction TargetPropertiesBlessing(constructor) {\n const targets = readInheritableStaticArrayValues(constructor, \"targets\");\n return targets.reduce((properties, targetDefinition) => {\n return Object.assign(properties, propertiesForTargetDefinition(targetDefinition));\n }, {});\n}\nfunction propertiesForTargetDefinition(name) {\n return {\n [`${name}Target`]: {\n get() {\n const target = this.targets.find(name);\n if (target) {\n return target;\n }\n else {\n throw new Error(`Missing target element \"${name}\" for \"${this.identifier}\" controller`);\n }\n },\n },\n [`${name}Targets`]: {\n get() {\n return this.targets.findAll(name);\n },\n },\n [`has${capitalize(name)}Target`]: {\n get() {\n return this.targets.has(name);\n },\n },\n };\n}\n\nfunction ValuePropertiesBlessing(constructor) {\n const valueDefinitionPairs = readInheritableStaticObjectPairs(constructor, \"values\");\n const propertyDescriptorMap = {\n valueDescriptorMap: {\n get() {\n return valueDefinitionPairs.reduce((result, valueDefinitionPair) => {\n const valueDescriptor = parseValueDefinitionPair(valueDefinitionPair, this.identifier);\n const attributeName = this.data.getAttributeNameForKey(valueDescriptor.key);\n return Object.assign(result, { [attributeName]: valueDescriptor });\n }, {});\n },\n },\n };\n return valueDefinitionPairs.reduce((properties, valueDefinitionPair) => {\n return Object.assign(properties, propertiesForValueDefinitionPair(valueDefinitionPair));\n }, propertyDescriptorMap);\n}\nfunction propertiesForValueDefinitionPair(valueDefinitionPair, controller) {\n const definition = parseValueDefinitionPair(valueDefinitionPair, controller);\n const { key, name, reader: read, writer: write } = definition;\n return {\n [name]: {\n get() {\n const value = this.data.get(key);\n if (value !== null) {\n return read(value);\n }\n else {\n return definition.defaultValue;\n }\n },\n set(value) {\n if (value === undefined) {\n this.data.delete(key);\n }\n else {\n this.data.set(key, write(value));\n }\n },\n },\n [`has${capitalize(name)}`]: {\n get() {\n return this.data.has(key) || definition.hasCustomDefaultValue;\n },\n },\n };\n}\nfunction parseValueDefinitionPair([token, typeDefinition], controller) {\n return valueDescriptorForTokenAndTypeDefinition({\n controller,\n token,\n typeDefinition,\n });\n}\nfunction parseValueTypeConstant(constant) {\n switch (constant) {\n case Array:\n return \"array\";\n case Boolean:\n return \"boolean\";\n case Number:\n return \"number\";\n case Object:\n return \"object\";\n case String:\n return \"string\";\n }\n}\nfunction parseValueTypeDefault(defaultValue) {\n switch (typeof defaultValue) {\n case \"boolean\":\n return \"boolean\";\n case \"number\":\n return \"number\";\n case \"string\":\n return \"string\";\n }\n if (Array.isArray(defaultValue))\n return \"array\";\n if (Object.prototype.toString.call(defaultValue) === \"[object Object]\")\n return \"object\";\n}\nfunction parseValueTypeObject(payload) {\n const { controller, token, typeObject } = payload;\n const hasType = isSomething(typeObject.type);\n const hasDefault = isSomething(typeObject.default);\n const fullObject = hasType && hasDefault;\n const onlyType = hasType && !hasDefault;\n const onlyDefault = !hasType && hasDefault;\n const typeFromObject = parseValueTypeConstant(typeObject.type);\n const typeFromDefaultValue = parseValueTypeDefault(payload.typeObject.default);\n if (onlyType)\n return typeFromObject;\n if (onlyDefault)\n return typeFromDefaultValue;\n if (typeFromObject !== typeFromDefaultValue) {\n const propertyPath = controller ? `${controller}.${token}` : token;\n throw new Error(`The specified default value for the Stimulus Value \"${propertyPath}\" must match the defined type \"${typeFromObject}\". The provided default value of \"${typeObject.default}\" is of type \"${typeFromDefaultValue}\".`);\n }\n if (fullObject)\n return typeFromObject;\n}\nfunction parseValueTypeDefinition(payload) {\n const { controller, token, typeDefinition } = payload;\n const typeObject = { controller, token, typeObject: typeDefinition };\n const typeFromObject = parseValueTypeObject(typeObject);\n const typeFromDefaultValue = parseValueTypeDefault(typeDefinition);\n const typeFromConstant = parseValueTypeConstant(typeDefinition);\n const type = typeFromObject || typeFromDefaultValue || typeFromConstant;\n if (type)\n return type;\n const propertyPath = controller ? `${controller}.${typeDefinition}` : token;\n throw new Error(`Unknown value type \"${propertyPath}\" for \"${token}\" value`);\n}\nfunction defaultValueForDefinition(typeDefinition) {\n const constant = parseValueTypeConstant(typeDefinition);\n if (constant)\n return defaultValuesByType[constant];\n const hasDefault = hasProperty(typeDefinition, \"default\");\n const hasType = hasProperty(typeDefinition, \"type\");\n const typeObject = typeDefinition;\n if (hasDefault)\n return typeObject.default;\n if (hasType) {\n const { type } = typeObject;\n const constantFromType = parseValueTypeConstant(type);\n if (constantFromType)\n return defaultValuesByType[constantFromType];\n }\n return typeDefinition;\n}\nfunction valueDescriptorForTokenAndTypeDefinition(payload) {\n const { token, typeDefinition } = payload;\n const key = `${dasherize(token)}-value`;\n const type = parseValueTypeDefinition(payload);\n return {\n type,\n key,\n name: camelize(key),\n get defaultValue() {\n return defaultValueForDefinition(typeDefinition);\n },\n get hasCustomDefaultValue() {\n return parseValueTypeDefault(typeDefinition) !== undefined;\n },\n reader: readers[type],\n writer: writers[type] || writers.default,\n };\n}\nconst defaultValuesByType = {\n get array() {\n return [];\n },\n boolean: false,\n number: 0,\n get object() {\n return {};\n },\n string: \"\",\n};\nconst readers = {\n array(value) {\n const array = JSON.parse(value);\n if (!Array.isArray(array)) {\n throw new TypeError(`expected value of type \"array\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(array)}\"`);\n }\n return array;\n },\n boolean(value) {\n return !(value == \"0\" || String(value).toLowerCase() == \"false\");\n },\n number(value) {\n return Number(value.replace(/_/g, \"\"));\n },\n object(value) {\n const object = JSON.parse(value);\n if (object === null || typeof object != \"object\" || Array.isArray(object)) {\n throw new TypeError(`expected value of type \"object\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(object)}\"`);\n }\n return object;\n },\n string(value) {\n return value;\n },\n};\nconst writers = {\n default: writeString,\n array: writeJSON,\n object: writeJSON,\n};\nfunction writeJSON(value) {\n return JSON.stringify(value);\n}\nfunction writeString(value) {\n return `${value}`;\n}\n\nclass Controller {\n constructor(context) {\n this.context = context;\n }\n static get shouldLoad() {\n return true;\n }\n static afterLoad(_identifier, _application) {\n return;\n }\n get application() {\n return this.context.application;\n }\n get scope() {\n return this.context.scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get targets() {\n return this.scope.targets;\n }\n get outlets() {\n return this.scope.outlets;\n }\n get classes() {\n return this.scope.classes;\n }\n get data() {\n return this.scope.data;\n }\n initialize() {\n }\n connect() {\n }\n disconnect() {\n }\n dispatch(eventName, { target = this.element, detail = {}, prefix = this.identifier, bubbles = true, cancelable = true, } = {}) {\n const type = prefix ? `${prefix}:${eventName}` : eventName;\n const event = new CustomEvent(type, { detail, bubbles, cancelable });\n target.dispatchEvent(event);\n return event;\n }\n}\nController.blessings = [\n ClassPropertiesBlessing,\n TargetPropertiesBlessing,\n ValuePropertiesBlessing,\n OutletPropertiesBlessing,\n];\nController.targets = [];\nController.outlets = [];\nController.values = {};\n\nexport { Application, AttributeObserver, Context, Controller, ElementObserver, IndexedMultimap, Multimap, SelectorObserver, StringMapObserver, TokenListObserver, ValueListObserver, add, defaultSchema, del, fetch, prune };\n", "/**\n * Returns a function that is `debounced` by the specified `delay` (in `ms`).\n * @template {(...args: any[]) => void} T\n * @param {T} func\n * @param {number} [delay] defaults to 1000ms\n * @returns {T}\n */\nexport function debounce(func, delay = 1000) {\n /** @type {number | undefined} */ let timer;\n\n /** @type {(args: Parameters) => void} */\n return (...args) => {\n clearTimeout(timer);\n timer = window.setTimeout(func, delay, ...args);\n };\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport { debounce } from \"@/utils/debounce\";\n\nexport default class extends Controller {\n static targets = [\"inputContainer\", \"input\", \"message\"];\n static values = { url: String };\n\n change() {\n const $target = $(this.inputTarget);\n\n debounce(() => this.validate($target.attr(\"name\"), $target.val()), 350)();\n }\n\n async validate(name, val) {\n const { status, message } = await $.post(this.urlValue, { [name]: val });\n\n this.redecorate($(this.inputContainerTarget), status);\n this.redecorate($(this.messageTarget), status).text(message);\n }\n\n redecorate($elt, status) {\n const classes = $elt.data(\"validatorClasses\");\n\n return $elt.removeClass(Object.values(classes).join(\" \")).addClass(classes[status]);\n }\n}\n", "import ErrorNotifier from \"../error_notifier\";\n\njQuery(function ($) {\n const paymentContainer = document.getElementById(\"payments\");\n if (!paymentContainer) {\n return;\n }\n\n const stripe = Stripe(window.params.stripe.public_key);\n\n const elements = stripe.elements();\n\n const style = {\n base: {\n color: \"#32325d\",\n fontSmoothing: \"antialiased\",\n fontSize: \"16px\",\n \"::placeholder\": {\n color: \"#aab7c4\",\n },\n },\n invalid: {\n color: \"#fa755a\",\n iconColor: \"#fa755a\",\n },\n };\n\n const card = elements.create(\"card\", { style });\n const errorElement = document.getElementById(\"card-errors\");\n const form = paymentContainer.parentNode;\n const submitButton = form.querySelector(\"input[type=\\\"submit\\\"]\");\n\n // Tracks whether Stripe Elements considers the card iframe fully\n // populated (number + expiry + CVC + zip). Browser autofill cannot\n // reach into Stripe's iframe, so customers who autofill the outer\n // fields can still submit with an empty card; gate the submit\n // button on this state and surface the missing-fields message.\n let cardComplete = false;\n\n card.mount(\"#card-element\");\n\n const setCardErrorText = (text) => {\n errorElement.textContent = text;\n errorElement.classList.toggle(\"hide\", !text);\n };\n\n card.addEventListener(\"change\", function (event) {\n cardComplete = !!event.complete;\n if (event.error) {\n setCardErrorText(event.error.message);\n } else if (!cardComplete) {\n setCardErrorText(\"Please complete your card details (number, expiry, CVC, and ZIP) above.\");\n } else {\n setCardErrorText(\"\");\n }\n syncSubmitState();\n });\n\n const $bankError = $(\".bank-error\");\n const $bankSuccess = $(\".bank-success\");\n const $cardPayment = $(\".card-payment\");\n const $bankPayment = $(\".bank-payment\");\n const $bankLoading = $(\".bank-loading\");\n const $bankInfo = $(\".bank-info\");\n\n const getCSRFToken = () => {\n const csrfToken = document.querySelector(\"[name='csrf-token']\");\n return csrfToken ? csrfToken.content : null;\n };\n\n const headers = {\n \"X-CSRF-Token\": getCSRFToken(),\n \"Content-Type\": \"application/json\",\n };\n\n // Tracks whether we've successfully linked a bank account via\n // Stripe Financial Connections. The hidden payment_method_id\n // field is set when this is true.\n let bankLinked = false;\n\n const $bankPendingVerification = $(\".bank-pending-verification\");\n const $bankManualForm = $(\".bank-manual-form\");\n const $bankToggleManual = $(\".bank-toggle-manual\");\n\n // Mints a fresh SetupIntent on the server. Used by both the instant\n // (Financial Connections) and manual entry paths.\n const fetchSetupIntent = async () => {\n const setupResponse = await fetch(\"/billing/bank_setup\", { method: \"POST\", headers });\n if (!setupResponse.ok) {\n throw new Error(\"Could not initialize bank linking. Please try again.\");\n }\n return setupResponse.json();\n };\n\n // Records the SetupIntent + PaymentMethod IDs on the hidden fields.\n // For instant FC the SetupIntent is `succeeded` and the customer's\n // subscription becomes active immediately. For manual entry the\n // SetupIntent is `requires_action` (pending micro-deposits); the\n // backend gives the customer a 30-day trial and CS handles\n // verification offline.\n const recordBankLinked = (setupIntent, { pending }) => {\n document.getElementById(\"payment_method_id\").setAttribute(\"value\", setupIntent.payment_method);\n document.getElementById(\"setup_intent_id\").setAttribute(\"value\", setupIntent.id);\n bankLinked = true;\n if (pending) {\n $bankPendingVerification.removeClass(\"hide\");\n $bankSuccess.addClass(\"hide\");\n } else {\n $bankSuccess.removeClass(\"hide\");\n $bankPendingVerification.addClass(\"hide\");\n }\n syncSubmitState();\n };\n\n const resetBankLinked = (message) => {\n bankLinked = false;\n document.getElementById(\"payment_method_id\").setAttribute(\"value\", \"\");\n document.getElementById(\"setup_intent_id\").setAttribute(\"value\", \"\");\n $bankSuccess.addClass(\"hide\");\n $bankPendingVerification.addClass(\"hide\");\n if (message) {\n $bankError.removeClass(\"hide\").text(message);\n } else {\n $bankError.addClass(\"hide\");\n }\n syncSubmitState();\n };\n\n const linkBankAccount = async () => {\n $bankError.addClass(\"hide\");\n $bankSuccess.addClass(\"hide\");\n $bankPendingVerification.addClass(\"hide\");\n $bankInfo.addClass(\"hide\");\n $bankLoading.removeClass(\"hide\");\n\n try {\n const { client_secret: clientSecret } = await fetchSetupIntent();\n\n // Open the Stripe Financial Connections modal. The customer\n // logs into their bank; the SetupIntent ends up holding a\n // us_bank_account PaymentMethod, instantly verified.\n const collectResult = await stripe.collectBankAccountForSetup({\n clientSecret,\n params: {\n payment_method_type: \"us_bank_account\",\n payment_method_data: {\n billing_details: {\n name: document.getElementById(\"customer_name\").value || \"AutoRaptor Customer\",\n email: document.getElementById(\"customer_email\").value,\n },\n },\n },\n });\n\n if (collectResult.error) {\n throw new Error(collectResult.error.message);\n }\n\n const confirmResult = await stripe.confirmUsBankAccountSetup(clientSecret);\n if (confirmResult.error) {\n throw new Error(confirmResult.error.message);\n }\n\n recordBankLinked(confirmResult.setupIntent, { pending: false });\n } catch (err) {\n resetBankLinked(err.message);\n ErrorNotifier.notify({ error: err.message, context: { stripe_fc_setup: true } });\n } finally {\n $bankLoading.addClass(\"hide\");\n }\n };\n\n const submitManualBank = async () => {\n $bankError.addClass(\"hide\");\n $bankSuccess.addClass(\"hide\");\n $bankPendingVerification.addClass(\"hide\");\n $bankInfo.addClass(\"hide\");\n $bankLoading.removeClass(\"hide\");\n\n try {\n const routing = document.getElementById(\"manual_bank_routing_number\").value.trim();\n const acct = document.getElementById(\"manual_bank_account_number\").value.trim();\n const accountHolderType = document.getElementById(\"manual_bank_account_holder_type\").value;\n if (!/^\\d{9}$/.test(routing)) {\n throw new Error(\"Routing number must be 9 digits.\");\n }\n if (acct.length === 0) {\n throw new Error(\"Account number is required.\");\n }\n\n const { client_secret: clientSecret } = await fetchSetupIntent();\n\n // Manual confirm with raw bank details. Stripe queues\n // micro-deposit verification and emails the customer the\n // verification URL; the SetupIntent ends in `requires_action`.\n // We still consider the customer \"signed up\" \u2014 the backend\n // gives them a 30-day trial subscription and CS handles\n // verification offline (per business decision).\n const confirmResult = await stripe.confirmUsBankAccountSetup(clientSecret, {\n payment_method: {\n us_bank_account: {\n routing_number: routing,\n account_number: acct,\n account_holder_type: accountHolderType,\n },\n billing_details: {\n name: document.getElementById(\"customer_name\").value || \"AutoRaptor Customer\",\n email: document.getElementById(\"customer_email\").value,\n },\n },\n });\n if (confirmResult.error) {\n throw new Error(confirmResult.error.message);\n }\n\n const pending = confirmResult.setupIntent.status !== \"succeeded\";\n recordBankLinked(confirmResult.setupIntent, { pending });\n } catch (err) {\n resetBankLinked(err.message);\n ErrorNotifier.notify({ error: err.message, context: { stripe_manual_ach_setup: true } });\n } finally {\n $bankLoading.addClass(\"hide\");\n }\n };\n\n const cardPaymentButton = document.getElementById(\"payment_type_card\");\n cardPaymentButton.addEventListener(\"click\", function () {\n $cardPayment.removeClass(\"hide\");\n $bankPayment.addClass(\"hide\");\n $(\".card-payment .required\").each(function () { this.setAttribute(\"required\", true); });\n });\n\n const bankPaymentButton = document.getElementById(\"payment_type_bank\");\n bankPaymentButton.addEventListener(\"click\", function () {\n $cardPayment.addClass(\"hide\");\n $bankPayment.removeClass(\"hide\");\n $(\".card-payment .required\").each(function () { this.removeAttribute(\"required\"); });\n });\n\n const bankLinkButton = document.getElementById(\"bank-link\");\n if (bankLinkButton) {\n bankLinkButton.addEventListener(\"click\", linkBankAccount);\n }\n\n const bankSubmitManualButton = document.getElementById(\"bank-submit-manual\");\n if (bankSubmitManualButton) {\n bankSubmitManualButton.addEventListener(\"click\", submitManualBank);\n }\n\n // Toggle between instant FC and manual entry. Resets any stale PM\n // so the customer doesn't accidentally submit one from the other path.\n // #bank-link hides via the `hidden` attribute, not the `hide` class: it\n // carries the design-system button classes, whose `display:flex` is a\n // Tailwind utility (important: true) and outranks `.hide`.\n const bankShowManual = document.getElementById(\"bank-show-manual\");\n if (bankShowManual) {\n bankShowManual.addEventListener(\"click\", function (e) {\n e.preventDefault();\n $bankManualForm.removeClass(\"hide\");\n $bankToggleManual.addClass(\"hide\");\n bankLinkButton.hidden = true;\n resetBankLinked(null);\n });\n }\n const bankShowInstant = document.getElementById(\"bank-show-instant\");\n if (bankShowInstant) {\n bankShowInstant.addEventListener(\"click\", function (e) {\n e.preventDefault();\n $bankManualForm.addClass(\"hide\");\n $bankToggleManual.removeClass(\"hide\");\n bankLinkButton.hidden = false;\n resetBankLinked(null);\n });\n }\n\n form.addEventListener(\"submit\", function (event) {\n event.preventDefault();\n\n const paymentType = form.elements.payment_type.value;\n if (paymentType === \"card\") {\n // Belt-and-suspenders: the submit button is disabled while\n // cardComplete is false (see syncSubmitState), but defend\n // against keyboard-submit / programmatic submit anyway.\n if (!cardComplete) {\n setCardErrorText(\"Please complete your card details (number, expiry, CVC, and ZIP) above.\");\n errorElement.scrollIntoView({ behavior: \"smooth\", block: \"center\" });\n return;\n }\n\n // Cardholder name lives in the Cardholder Name input\n // (`card[name]`), NOT in customer_name (which is the Legal\n // Business Name). Reading from the wrong field meant Stripe\n // received the business name as the cardholder, and the\n // visible Cardholder Name field was effectively dead.\n const name = document.getElementById(\"card_name\").value;\n\n stripe.createToken(\n card, { name, ...getBillingAddress() },\n ).then(function (result) {\n if (result.error) {\n setCardErrorText(result.error.message);\n errorElement.scrollIntoView({ behavior: \"smooth\", block: \"center\" });\n } else {\n setSourceToken(result.token.id);\n displaySpinner();\n form.submit();\n }\n });\n } else {\n // Bank flow: the PaymentMethod ID was set in the linkBankAccount\n // success path. If still empty, the customer never linked a bank\n // (or linking failed) \u2014 surface the bank error and bail.\n if (!bankLinked || form.elements.payment_method_id.value === \"\") {\n $bankError.removeClass(\"hide\").text(\"Please link your bank account before submitting.\");\n } else {\n displaySpinner();\n form.submit();\n }\n }\n });\n\n function syncSubmitState () {\n const paymentType = form.elements.payment_type.value;\n const cardReady = paymentType === \"card\" && cardComplete;\n const bankReady = paymentType === \"bank\" && bankLinked;\n if (cardReady || bankReady) {\n submitButton.disabled = false;\n submitButton.classList.remove(\"opacity-50\", \"cursor-not-allowed\");\n } else {\n submitButton.disabled = true;\n submitButton.classList.add(\"opacity-50\", \"cursor-not-allowed\");\n }\n }\n\n // When customers toggle between card and bank, re-evaluate\n // whether the submit button should be enabled.\n cardPaymentButton.addEventListener(\"click\", syncSubmitState);\n bankPaymentButton.addEventListener(\"click\", syncSubmitState);\n\n // Initial state: card is the default payment type and the iframe\n // starts empty, so the submit button starts disabled with a hint\n // pointing the customer to the card field.\n syncSubmitState();\n if (errorElement && !errorElement.textContent) {\n setCardErrorText(\"Enter your card details above to continue.\");\n }\n\n const billingAddress = document.getElementById(\"billing-address\");\n const useDealershipAddress = document.getElementById(\"use_dealership_address\");\n if (useDealershipAddress) {\n // Must run on both `click` AND initial load: after a 422 re-render the\n // ERB restores `checked` from params but the required-attribute + hidden\n // display state is baked at render time. Without the initial call, a\n // customer who used \"same as dealership\" and hit a 422 would see the\n // checkbox checked but the (empty) billing-address fields still visible\n // and still required, blocking browser form submission.\n const syncUseDealershipAddress = () => {\n if (useDealershipAddress.checked) {\n $(billingAddress).find(\"input.required\").each(function () { this.removeAttribute(\"required\"); });\n billingAddress.style.display = \"none\";\n } else {\n $(billingAddress).find(\"input.required\").each(function () { this.setAttribute(\"required\", true); });\n billingAddress.style.display = \"block\";\n }\n };\n useDealershipAddress.addEventListener(\"click\", syncUseDealershipAddress);\n syncUseDealershipAddress();\n }\n\n function getBillingAddress () {\n const address = {};\n if (useDealershipAddress && useDealershipAddress.checked) {\n address.address_line1 = document.getElementById(\"dealership_street1\").value;\n address.address_line2 = document.getElementById(\"dealership_street2\").value;\n address.address_city = document.getElementById(\"dealership_city\").value;\n address.address_state = document.getElementById(\"dealership_state\").value;\n address.address_zip = document.getElementById(\"dealership_zip\").value;\n address.address_country = document.getElementById(\"dealership_country\").value;\n } else {\n address.address_line1 = document.getElementById(\"billing_address_street_line1\").value;\n address.address_line2 = document.getElementById(\"billing_address_street_line2\").value;\n address.address_city = document.getElementById(\"billing_address_city\").value;\n address.address_state = document.getElementById(\"billing_address_state\").value;\n address.address_zip = document.getElementById(\"billing_address_zip\").value;\n address.address_country = document.getElementById(\"billing_address_country\").value;\n }\n return address;\n }\n\n function setSourceToken (token) {\n document\n .getElementById(\"source_token\")\n .setAttribute(\"value\", token);\n }\n\n function displaySpinner () {\n const spinner = document.getElementById(\"signup_button_spinner\");\n if (!spinner) {\n // We're not on the account#new page which doesn't render the spinner\n return;\n }\n submitButton.style.display = \"none\";\n spinner.style.display = \"block\";\n }\n});\n", "class InputField {\n constructor (item) {\n this.item = item;\n this.input = this.item.find(\"input[type = 'text']\");\n this.item[0].field = this;\n }\n\n blank () {\n return this.input.val() === \"\";\n }\n}\n\nexport class DateInput extends InputField {\n static monthNames = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n\n constructor(item) {\n super(item);\n\n this.hookup();\n }\n\n hookup () {\n this.month = this.item.find(\"select:first\");\n this.day = this.item.find(\"select\").eq(1);\n this.year = this.item.find(\"select\").eq(2);\n this.month.change(() => this.checkDate());\n this.day.change(() => this.checkDate(true));\n this.year.change(() => this.checkDate(true));\n }\n\n checkDate (show_error) {\n if (show_error == null) { show_error = false; }\n const daysInMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n if ((this.year.val() !== \"\") && !this.isLeap(this.year.val())) { daysInMonth[1] = 28; }\n const max = daysInMonth[this.month.val() - 1];\n\n if (parseInt(this.day.val()) > max) {\n this.day.val(max);\n if (show_error) {\n return alert(`There are only ${max} days in the month you have chosen.`);\n }\n }\n }\n\n isLeap (year) {\n const y = parseInt(year);\n return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;\n }\n}\n\nwindow.EmailInput = class EmailInput extends InputField {};\n\nwindow.StreetAddressInput = class StreetAddressInput extends InputField {\n constructor (item) {\n super(item);\n\n this.street = this.item.find(\"[data-target='street_address']\");\n const inputs = this.item.find(\"input[type = 'text']\").not(this.street);\n this.city = $(inputs[0]);\n this.state = $(inputs[1]);\n this.zip = $(inputs[2]);\n this.country = $(this.item.find(\"select\")[3]);\n\n this.hookup();\n }\n\n blank () {\n const x = $.trim(`${this.street.val()}${this.city.val()}${this.state.val()}${this.zip.val()}`);\n return x === \"\";\n }\n\n usOrCanada () {\n if (this.country.val() === \"US\") {\n this.item.find(\".state_select\").show();\n this.item.find(\".prov_select\").hide();\n return this.state.hide();\n } else if (this.country.val() === \"CA\") {\n this.item.find(\".prov_select\").show();\n this.item.find(\".state_select\").hide();\n return this.state.hide();\n } else {\n this.item.find(\".prov_select\").hide();\n this.item.find(\".state_select\").hide();\n return this.state.show();\n }\n }\n\n hookup (o) {\n this.usOrCanada();\n\n this.country.change(() => {\n return this.usOrCanada();\n });\n\n this.street.focus(() => {\n this.street[0].rows = 2;\n });\n\n this.fields = this.item.find(\"input[type = 'text'], textarea, select\");\n }\n};\n\nwindow.PhoneInput = class PhoneInput extends InputField {};\n", "var sparkMd5 = {\n exports: {}\n};\n\n(function(module, exports) {\n (function(factory) {\n {\n module.exports = factory();\n }\n })((function(undefined$1) {\n var hex_chr = [ \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\" ];\n function md5cycle(x, k) {\n var a = x[0], b = x[1], c = x[2], d = x[3];\n a += (b & c | ~b & d) + k[0] - 680876936 | 0;\n a = (a << 7 | a >>> 25) + b | 0;\n d += (a & b | ~a & c) + k[1] - 389564586 | 0;\n d = (d << 12 | d >>> 20) + a | 0;\n c += (d & a | ~d & b) + k[2] + 606105819 | 0;\n c = (c << 17 | c >>> 15) + d | 0;\n b += (c & d | ~c & a) + k[3] - 1044525330 | 0;\n b = (b << 22 | b >>> 10) + c | 0;\n a += (b & c | ~b & d) + k[4] - 176418897 | 0;\n a = (a << 7 | a >>> 25) + b | 0;\n d += (a & b | ~a & c) + k[5] + 1200080426 | 0;\n d = (d << 12 | d >>> 20) + a | 0;\n c += (d & a | ~d & b) + k[6] - 1473231341 | 0;\n c = (c << 17 | c >>> 15) + d | 0;\n b += (c & d | ~c & a) + k[7] - 45705983 | 0;\n b = (b << 22 | b >>> 10) + c | 0;\n a += (b & c | ~b & d) + k[8] + 1770035416 | 0;\n a = (a << 7 | a >>> 25) + b | 0;\n d += (a & b | ~a & c) + k[9] - 1958414417 | 0;\n d = (d << 12 | d >>> 20) + a | 0;\n c += (d & a | ~d & b) + k[10] - 42063 | 0;\n c = (c << 17 | c >>> 15) + d | 0;\n b += (c & d | ~c & a) + k[11] - 1990404162 | 0;\n b = (b << 22 | b >>> 10) + c | 0;\n a += (b & c | ~b & d) + k[12] + 1804603682 | 0;\n a = (a << 7 | a >>> 25) + b | 0;\n d += (a & b | ~a & c) + k[13] - 40341101 | 0;\n d = (d << 12 | d >>> 20) + a | 0;\n c += (d & a | ~d & b) + k[14] - 1502002290 | 0;\n c = (c << 17 | c >>> 15) + d | 0;\n b += (c & d | ~c & a) + k[15] + 1236535329 | 0;\n b = (b << 22 | b >>> 10) + c | 0;\n a += (b & d | c & ~d) + k[1] - 165796510 | 0;\n a = (a << 5 | a >>> 27) + b | 0;\n d += (a & c | b & ~c) + k[6] - 1069501632 | 0;\n d = (d << 9 | d >>> 23) + a | 0;\n c += (d & b | a & ~b) + k[11] + 643717713 | 0;\n c = (c << 14 | c >>> 18) + d | 0;\n b += (c & a | d & ~a) + k[0] - 373897302 | 0;\n b = (b << 20 | b >>> 12) + c | 0;\n a += (b & d | c & ~d) + k[5] - 701558691 | 0;\n a = (a << 5 | a >>> 27) + b | 0;\n d += (a & c | b & ~c) + k[10] + 38016083 | 0;\n d = (d << 9 | d >>> 23) + a | 0;\n c += (d & b | a & ~b) + k[15] - 660478335 | 0;\n c = (c << 14 | c >>> 18) + d | 0;\n b += (c & a | d & ~a) + k[4] - 405537848 | 0;\n b = (b << 20 | b >>> 12) + c | 0;\n a += (b & d | c & ~d) + k[9] + 568446438 | 0;\n a = (a << 5 | a >>> 27) + b | 0;\n d += (a & c | b & ~c) + k[14] - 1019803690 | 0;\n d = (d << 9 | d >>> 23) + a | 0;\n c += (d & b | a & ~b) + k[3] - 187363961 | 0;\n c = (c << 14 | c >>> 18) + d | 0;\n b += (c & a | d & ~a) + k[8] + 1163531501 | 0;\n b = (b << 20 | b >>> 12) + c | 0;\n a += (b & d | c & ~d) + k[13] - 1444681467 | 0;\n a = (a << 5 | a >>> 27) + b | 0;\n d += (a & c | b & ~c) + k[2] - 51403784 | 0;\n d = (d << 9 | d >>> 23) + a | 0;\n c += (d & b | a & ~b) + k[7] + 1735328473 | 0;\n c = (c << 14 | c >>> 18) + d | 0;\n b += (c & a | d & ~a) + k[12] - 1926607734 | 0;\n b = (b << 20 | b >>> 12) + c | 0;\n a += (b ^ c ^ d) + k[5] - 378558 | 0;\n a = (a << 4 | a >>> 28) + b | 0;\n d += (a ^ b ^ c) + k[8] - 2022574463 | 0;\n d = (d << 11 | d >>> 21) + a | 0;\n c += (d ^ a ^ b) + k[11] + 1839030562 | 0;\n c = (c << 16 | c >>> 16) + d | 0;\n b += (c ^ d ^ a) + k[14] - 35309556 | 0;\n b = (b << 23 | b >>> 9) + c | 0;\n a += (b ^ c ^ d) + k[1] - 1530992060 | 0;\n a = (a << 4 | a >>> 28) + b | 0;\n d += (a ^ b ^ c) + k[4] + 1272893353 | 0;\n d = (d << 11 | d >>> 21) + a | 0;\n c += (d ^ a ^ b) + k[7] - 155497632 | 0;\n c = (c << 16 | c >>> 16) + d | 0;\n b += (c ^ d ^ a) + k[10] - 1094730640 | 0;\n b = (b << 23 | b >>> 9) + c | 0;\n a += (b ^ c ^ d) + k[13] + 681279174 | 0;\n a = (a << 4 | a >>> 28) + b | 0;\n d += (a ^ b ^ c) + k[0] - 358537222 | 0;\n d = (d << 11 | d >>> 21) + a | 0;\n c += (d ^ a ^ b) + k[3] - 722521979 | 0;\n c = (c << 16 | c >>> 16) + d | 0;\n b += (c ^ d ^ a) + k[6] + 76029189 | 0;\n b = (b << 23 | b >>> 9) + c | 0;\n a += (b ^ c ^ d) + k[9] - 640364487 | 0;\n a = (a << 4 | a >>> 28) + b | 0;\n d += (a ^ b ^ c) + k[12] - 421815835 | 0;\n d = (d << 11 | d >>> 21) + a | 0;\n c += (d ^ a ^ b) + k[15] + 530742520 | 0;\n c = (c << 16 | c >>> 16) + d | 0;\n b += (c ^ d ^ a) + k[2] - 995338651 | 0;\n b = (b << 23 | b >>> 9) + c | 0;\n a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;\n a = (a << 6 | a >>> 26) + b | 0;\n d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;\n d = (d << 10 | d >>> 22) + a | 0;\n c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;\n c = (c << 15 | c >>> 17) + d | 0;\n b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;\n b = (b << 21 | b >>> 11) + c | 0;\n a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;\n a = (a << 6 | a >>> 26) + b | 0;\n d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;\n d = (d << 10 | d >>> 22) + a | 0;\n c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;\n c = (c << 15 | c >>> 17) + d | 0;\n b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;\n b = (b << 21 | b >>> 11) + c | 0;\n a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;\n a = (a << 6 | a >>> 26) + b | 0;\n d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;\n d = (d << 10 | d >>> 22) + a | 0;\n c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;\n c = (c << 15 | c >>> 17) + d | 0;\n b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;\n b = (b << 21 | b >>> 11) + c | 0;\n a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;\n a = (a << 6 | a >>> 26) + b | 0;\n d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;\n d = (d << 10 | d >>> 22) + a | 0;\n c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;\n c = (c << 15 | c >>> 17) + d | 0;\n b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;\n b = (b << 21 | b >>> 11) + c | 0;\n x[0] = a + x[0] | 0;\n x[1] = b + x[1] | 0;\n x[2] = c + x[2] | 0;\n x[3] = d + x[3] | 0;\n }\n function md5blk(s) {\n var md5blks = [], i;\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);\n }\n return md5blks;\n }\n function md5blk_array(a) {\n var md5blks = [], i;\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);\n }\n return md5blks;\n }\n function md51(s) {\n var n = s.length, state = [ 1732584193, -271733879, -1732584194, 271733878 ], i, length, tail, tmp, lo, hi;\n for (i = 64; i <= n; i += 64) {\n md5cycle(state, md5blk(s.substring(i - 64, i)));\n }\n s = s.substring(i - 64);\n length = s.length;\n tail = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];\n for (i = 0; i < length; i += 1) {\n tail[i >> 2] |= s.charCodeAt(i) << (i % 4 << 3);\n }\n tail[i >> 2] |= 128 << (i % 4 << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i += 1) {\n tail[i] = 0;\n }\n }\n tmp = n * 8;\n tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);\n lo = parseInt(tmp[2], 16);\n hi = parseInt(tmp[1], 16) || 0;\n tail[14] = lo;\n tail[15] = hi;\n md5cycle(state, tail);\n return state;\n }\n function md51_array(a) {\n var n = a.length, state = [ 1732584193, -271733879, -1732584194, 271733878 ], i, length, tail, tmp, lo, hi;\n for (i = 64; i <= n; i += 64) {\n md5cycle(state, md5blk_array(a.subarray(i - 64, i)));\n }\n a = i - 64 < n ? a.subarray(i - 64) : new Uint8Array(0);\n length = a.length;\n tail = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];\n for (i = 0; i < length; i += 1) {\n tail[i >> 2] |= a[i] << (i % 4 << 3);\n }\n tail[i >> 2] |= 128 << (i % 4 << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i += 1) {\n tail[i] = 0;\n }\n }\n tmp = n * 8;\n tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);\n lo = parseInt(tmp[2], 16);\n hi = parseInt(tmp[1], 16) || 0;\n tail[14] = lo;\n tail[15] = hi;\n md5cycle(state, tail);\n return state;\n }\n function rhex(n) {\n var s = \"\", j;\n for (j = 0; j < 4; j += 1) {\n s += hex_chr[n >> j * 8 + 4 & 15] + hex_chr[n >> j * 8 & 15];\n }\n return s;\n }\n function hex(x) {\n var i;\n for (i = 0; i < x.length; i += 1) {\n x[i] = rhex(x[i]);\n }\n return x.join(\"\");\n }\n if (hex(md51(\"hello\")) !== \"5d41402abc4b2a76b9719d911017c592\") ;\n if (typeof ArrayBuffer !== \"undefined\" && !ArrayBuffer.prototype.slice) {\n (function() {\n function clamp(val, length) {\n val = val | 0 || 0;\n if (val < 0) {\n return Math.max(val + length, 0);\n }\n return Math.min(val, length);\n }\n ArrayBuffer.prototype.slice = function(from, to) {\n var length = this.byteLength, begin = clamp(from, length), end = length, num, target, targetArray, sourceArray;\n if (to !== undefined$1) {\n end = clamp(to, length);\n }\n if (begin > end) {\n return new ArrayBuffer(0);\n }\n num = end - begin;\n target = new ArrayBuffer(num);\n targetArray = new Uint8Array(target);\n sourceArray = new Uint8Array(this, begin, num);\n targetArray.set(sourceArray);\n return target;\n };\n })();\n }\n function toUtf8(str) {\n if (/[\\u0080-\\uFFFF]/.test(str)) {\n str = unescape(encodeURIComponent(str));\n }\n return str;\n }\n function utf8Str2ArrayBuffer(str, returnUInt8Array) {\n var length = str.length, buff = new ArrayBuffer(length), arr = new Uint8Array(buff), i;\n for (i = 0; i < length; i += 1) {\n arr[i] = str.charCodeAt(i);\n }\n return returnUInt8Array ? arr : buff;\n }\n function arrayBuffer2Utf8Str(buff) {\n return String.fromCharCode.apply(null, new Uint8Array(buff));\n }\n function concatenateArrayBuffers(first, second, returnUInt8Array) {\n var result = new Uint8Array(first.byteLength + second.byteLength);\n result.set(new Uint8Array(first));\n result.set(new Uint8Array(second), first.byteLength);\n return returnUInt8Array ? result : result.buffer;\n }\n function hexToBinaryString(hex) {\n var bytes = [], length = hex.length, x;\n for (x = 0; x < length - 1; x += 2) {\n bytes.push(parseInt(hex.substr(x, 2), 16));\n }\n return String.fromCharCode.apply(String, bytes);\n }\n function SparkMD5() {\n this.reset();\n }\n SparkMD5.prototype.append = function(str) {\n this.appendBinary(toUtf8(str));\n return this;\n };\n SparkMD5.prototype.appendBinary = function(contents) {\n this._buff += contents;\n this._length += contents.length;\n var length = this._buff.length, i;\n for (i = 64; i <= length; i += 64) {\n md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));\n }\n this._buff = this._buff.substring(i - 64);\n return this;\n };\n SparkMD5.prototype.end = function(raw) {\n var buff = this._buff, length = buff.length, i, tail = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], ret;\n for (i = 0; i < length; i += 1) {\n tail[i >> 2] |= buff.charCodeAt(i) << (i % 4 << 3);\n }\n this._finish(tail, length);\n ret = hex(this._hash);\n if (raw) {\n ret = hexToBinaryString(ret);\n }\n this.reset();\n return ret;\n };\n SparkMD5.prototype.reset = function() {\n this._buff = \"\";\n this._length = 0;\n this._hash = [ 1732584193, -271733879, -1732584194, 271733878 ];\n return this;\n };\n SparkMD5.prototype.getState = function() {\n return {\n buff: this._buff,\n length: this._length,\n hash: this._hash.slice()\n };\n };\n SparkMD5.prototype.setState = function(state) {\n this._buff = state.buff;\n this._length = state.length;\n this._hash = state.hash;\n return this;\n };\n SparkMD5.prototype.destroy = function() {\n delete this._hash;\n delete this._buff;\n delete this._length;\n };\n SparkMD5.prototype._finish = function(tail, length) {\n var i = length, tmp, lo, hi;\n tail[i >> 2] |= 128 << (i % 4 << 3);\n if (i > 55) {\n md5cycle(this._hash, tail);\n for (i = 0; i < 16; i += 1) {\n tail[i] = 0;\n }\n }\n tmp = this._length * 8;\n tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);\n lo = parseInt(tmp[2], 16);\n hi = parseInt(tmp[1], 16) || 0;\n tail[14] = lo;\n tail[15] = hi;\n md5cycle(this._hash, tail);\n };\n SparkMD5.hash = function(str, raw) {\n return SparkMD5.hashBinary(toUtf8(str), raw);\n };\n SparkMD5.hashBinary = function(content, raw) {\n var hash = md51(content), ret = hex(hash);\n return raw ? hexToBinaryString(ret) : ret;\n };\n SparkMD5.ArrayBuffer = function() {\n this.reset();\n };\n SparkMD5.ArrayBuffer.prototype.append = function(arr) {\n var buff = concatenateArrayBuffers(this._buff.buffer, arr, true), length = buff.length, i;\n this._length += arr.byteLength;\n for (i = 64; i <= length; i += 64) {\n md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));\n }\n this._buff = i - 64 < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);\n return this;\n };\n SparkMD5.ArrayBuffer.prototype.end = function(raw) {\n var buff = this._buff, length = buff.length, tail = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], i, ret;\n for (i = 0; i < length; i += 1) {\n tail[i >> 2] |= buff[i] << (i % 4 << 3);\n }\n this._finish(tail, length);\n ret = hex(this._hash);\n if (raw) {\n ret = hexToBinaryString(ret);\n }\n this.reset();\n return ret;\n };\n SparkMD5.ArrayBuffer.prototype.reset = function() {\n this._buff = new Uint8Array(0);\n this._length = 0;\n this._hash = [ 1732584193, -271733879, -1732584194, 271733878 ];\n return this;\n };\n SparkMD5.ArrayBuffer.prototype.getState = function() {\n var state = SparkMD5.prototype.getState.call(this);\n state.buff = arrayBuffer2Utf8Str(state.buff);\n return state;\n };\n SparkMD5.ArrayBuffer.prototype.setState = function(state) {\n state.buff = utf8Str2ArrayBuffer(state.buff, true);\n return SparkMD5.prototype.setState.call(this, state);\n };\n SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;\n SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;\n SparkMD5.ArrayBuffer.hash = function(arr, raw) {\n var hash = md51_array(new Uint8Array(arr)), ret = hex(hash);\n return raw ? hexToBinaryString(ret) : ret;\n };\n return SparkMD5;\n }));\n})(sparkMd5);\n\nvar SparkMD5 = sparkMd5.exports;\n\nconst fileSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;\n\nclass FileChecksum {\n static create(file, callback) {\n const instance = new FileChecksum(file);\n instance.create(callback);\n }\n constructor(file) {\n this.file = file;\n this.chunkSize = 2097152;\n this.chunkCount = Math.ceil(this.file.size / this.chunkSize);\n this.chunkIndex = 0;\n }\n create(callback) {\n this.callback = callback;\n this.md5Buffer = new SparkMD5.ArrayBuffer;\n this.fileReader = new FileReader;\n this.fileReader.addEventListener(\"load\", (event => this.fileReaderDidLoad(event)));\n this.fileReader.addEventListener(\"error\", (event => this.fileReaderDidError(event)));\n this.readNextChunk();\n }\n fileReaderDidLoad(event) {\n this.md5Buffer.append(event.target.result);\n if (!this.readNextChunk()) {\n const binaryDigest = this.md5Buffer.end(true);\n const base64digest = btoa(binaryDigest);\n this.callback(null, base64digest);\n }\n }\n fileReaderDidError(event) {\n this.callback(`Error reading ${this.file.name}`);\n }\n readNextChunk() {\n if (this.chunkIndex < this.chunkCount || this.chunkIndex == 0 && this.chunkCount == 0) {\n const start = this.chunkIndex * this.chunkSize;\n const end = Math.min(start + this.chunkSize, this.file.size);\n const bytes = fileSlice.call(this.file, start, end);\n this.fileReader.readAsArrayBuffer(bytes);\n this.chunkIndex++;\n return true;\n } else {\n return false;\n }\n }\n}\n\nfunction getMetaValue(name) {\n const element = findElement(document.head, `meta[name=\"${name}\"]`);\n if (element) {\n return element.getAttribute(\"content\");\n }\n}\n\nfunction findElements(root, selector) {\n if (typeof root == \"string\") {\n selector = root;\n root = document;\n }\n const elements = root.querySelectorAll(selector);\n return toArray(elements);\n}\n\nfunction findElement(root, selector) {\n if (typeof root == \"string\") {\n selector = root;\n root = document;\n }\n return root.querySelector(selector);\n}\n\nfunction dispatchEvent(element, type, eventInit = {}) {\n const {disabled: disabled} = element;\n const {bubbles: bubbles, cancelable: cancelable, detail: detail} = eventInit;\n const event = document.createEvent(\"Event\");\n event.initEvent(type, bubbles || true, cancelable || true);\n event.detail = detail || {};\n try {\n element.disabled = false;\n element.dispatchEvent(event);\n } finally {\n element.disabled = disabled;\n }\n return event;\n}\n\nfunction toArray(value) {\n if (Array.isArray(value)) {\n return value;\n } else if (Array.from) {\n return Array.from(value);\n } else {\n return [].slice.call(value);\n }\n}\n\nclass BlobRecord {\n constructor(file, checksum, url, customHeaders = {}) {\n this.file = file;\n this.attributes = {\n filename: file.name,\n content_type: file.type || \"application/octet-stream\",\n byte_size: file.size,\n checksum: checksum\n };\n this.xhr = new XMLHttpRequest;\n this.xhr.open(\"POST\", url, true);\n this.xhr.responseType = \"json\";\n this.xhr.setRequestHeader(\"Content-Type\", \"application/json\");\n this.xhr.setRequestHeader(\"Accept\", \"application/json\");\n this.xhr.setRequestHeader(\"X-Requested-With\", \"XMLHttpRequest\");\n Object.keys(customHeaders).forEach((headerKey => {\n this.xhr.setRequestHeader(headerKey, customHeaders[headerKey]);\n }));\n const csrfToken = getMetaValue(\"csrf-token\");\n if (csrfToken != undefined) {\n this.xhr.setRequestHeader(\"X-CSRF-Token\", csrfToken);\n }\n this.xhr.addEventListener(\"load\", (event => this.requestDidLoad(event)));\n this.xhr.addEventListener(\"error\", (event => this.requestDidError(event)));\n }\n get status() {\n return this.xhr.status;\n }\n get response() {\n const {responseType: responseType, response: response} = this.xhr;\n if (responseType == \"json\") {\n return response;\n } else {\n return JSON.parse(response);\n }\n }\n create(callback) {\n this.callback = callback;\n this.xhr.send(JSON.stringify({\n blob: this.attributes\n }));\n }\n requestDidLoad(event) {\n if (this.status >= 200 && this.status < 300) {\n const {response: response} = this;\n const {direct_upload: direct_upload} = response;\n delete response.direct_upload;\n this.attributes = response;\n this.directUploadData = direct_upload;\n this.callback(null, this.toJSON());\n } else {\n this.requestDidError(event);\n }\n }\n requestDidError(event) {\n this.callback(`Error creating Blob for \"${this.file.name}\". Status: ${this.status}`);\n }\n toJSON() {\n const result = {};\n for (const key in this.attributes) {\n result[key] = this.attributes[key];\n }\n return result;\n }\n}\n\nclass BlobUpload {\n constructor(blob) {\n this.blob = blob;\n this.file = blob.file;\n const {url: url, headers: headers} = blob.directUploadData;\n this.xhr = new XMLHttpRequest;\n this.xhr.open(\"PUT\", url, true);\n this.xhr.responseType = \"text\";\n for (const key in headers) {\n this.xhr.setRequestHeader(key, headers[key]);\n }\n this.xhr.addEventListener(\"load\", (event => this.requestDidLoad(event)));\n this.xhr.addEventListener(\"error\", (event => this.requestDidError(event)));\n }\n create(callback) {\n this.callback = callback;\n this.xhr.send(this.file.slice());\n }\n requestDidLoad(event) {\n const {status: status, response: response} = this.xhr;\n if (status >= 200 && status < 300) {\n this.callback(null, response);\n } else {\n this.requestDidError(event);\n }\n }\n requestDidError(event) {\n this.callback(`Error storing \"${this.file.name}\". Status: ${this.xhr.status}`);\n }\n}\n\nlet id = 0;\n\nclass DirectUpload {\n constructor(file, url, delegate, customHeaders = {}) {\n this.id = ++id;\n this.file = file;\n this.url = url;\n this.delegate = delegate;\n this.customHeaders = customHeaders;\n }\n create(callback) {\n FileChecksum.create(this.file, ((error, checksum) => {\n if (error) {\n callback(error);\n return;\n }\n const blob = new BlobRecord(this.file, checksum, this.url, this.customHeaders);\n notify(this.delegate, \"directUploadWillCreateBlobWithXHR\", blob.xhr);\n blob.create((error => {\n if (error) {\n callback(error);\n } else {\n const upload = new BlobUpload(blob);\n notify(this.delegate, \"directUploadWillStoreFileWithXHR\", upload.xhr);\n upload.create((error => {\n if (error) {\n callback(error);\n } else {\n callback(null, blob.toJSON());\n }\n }));\n }\n }));\n }));\n }\n}\n\nfunction notify(object, methodName, ...messages) {\n if (object && typeof object[methodName] == \"function\") {\n return object[methodName](...messages);\n }\n}\n\nclass DirectUploadController {\n constructor(input, file) {\n this.input = input;\n this.file = file;\n this.directUpload = new DirectUpload(this.file, this.url, this);\n this.dispatch(\"initialize\");\n }\n start(callback) {\n const hiddenInput = document.createElement(\"input\");\n hiddenInput.type = \"hidden\";\n hiddenInput.name = this.input.name;\n this.input.insertAdjacentElement(\"beforebegin\", hiddenInput);\n this.dispatch(\"start\");\n this.directUpload.create(((error, attributes) => {\n if (error) {\n hiddenInput.parentNode.removeChild(hiddenInput);\n this.dispatchError(error);\n } else {\n hiddenInput.value = attributes.signed_id;\n }\n this.dispatch(\"end\");\n callback(error);\n }));\n }\n uploadRequestDidProgress(event) {\n const progress = event.loaded / event.total * 100;\n if (progress) {\n this.dispatch(\"progress\", {\n progress: progress\n });\n }\n }\n get url() {\n return this.input.getAttribute(\"data-direct-upload-url\");\n }\n dispatch(name, detail = {}) {\n detail.file = this.file;\n detail.id = this.directUpload.id;\n return dispatchEvent(this.input, `direct-upload:${name}`, {\n detail: detail\n });\n }\n dispatchError(error) {\n const event = this.dispatch(\"error\", {\n error: error\n });\n if (!event.defaultPrevented) {\n alert(error);\n }\n }\n directUploadWillCreateBlobWithXHR(xhr) {\n this.dispatch(\"before-blob-request\", {\n xhr: xhr\n });\n }\n directUploadWillStoreFileWithXHR(xhr) {\n this.dispatch(\"before-storage-request\", {\n xhr: xhr\n });\n xhr.upload.addEventListener(\"progress\", (event => this.uploadRequestDidProgress(event)));\n }\n}\n\nconst inputSelector = \"input[type=file][data-direct-upload-url]:not([disabled])\";\n\nclass DirectUploadsController {\n constructor(form) {\n this.form = form;\n this.inputs = findElements(form, inputSelector).filter((input => input.files.length));\n }\n start(callback) {\n const controllers = this.createDirectUploadControllers();\n const startNextController = () => {\n const controller = controllers.shift();\n if (controller) {\n controller.start((error => {\n if (error) {\n callback(error);\n this.dispatch(\"end\");\n } else {\n startNextController();\n }\n }));\n } else {\n callback();\n this.dispatch(\"end\");\n }\n };\n this.dispatch(\"start\");\n startNextController();\n }\n createDirectUploadControllers() {\n const controllers = [];\n this.inputs.forEach((input => {\n toArray(input.files).forEach((file => {\n const controller = new DirectUploadController(input, file);\n controllers.push(controller);\n }));\n }));\n return controllers;\n }\n dispatch(name, detail = {}) {\n return dispatchEvent(this.form, `direct-uploads:${name}`, {\n detail: detail\n });\n }\n}\n\nconst processingAttribute = \"data-direct-uploads-processing\";\n\nconst submitButtonsByForm = new WeakMap;\n\nlet started = false;\n\nfunction start() {\n if (!started) {\n started = true;\n document.addEventListener(\"click\", didClick, true);\n document.addEventListener(\"submit\", didSubmitForm, true);\n document.addEventListener(\"ajax:before\", didSubmitRemoteElement);\n }\n}\n\nfunction didClick(event) {\n const button = event.target.closest(\"button, input\");\n if (button && button.type === \"submit\" && button.form) {\n submitButtonsByForm.set(button.form, button);\n }\n}\n\nfunction didSubmitForm(event) {\n handleFormSubmissionEvent(event);\n}\n\nfunction didSubmitRemoteElement(event) {\n if (event.target.tagName == \"FORM\") {\n handleFormSubmissionEvent(event);\n }\n}\n\nfunction handleFormSubmissionEvent(event) {\n const form = event.target;\n if (form.hasAttribute(processingAttribute)) {\n event.preventDefault();\n return;\n }\n const controller = new DirectUploadsController(form);\n const {inputs: inputs} = controller;\n if (inputs.length) {\n event.preventDefault();\n form.setAttribute(processingAttribute, \"\");\n inputs.forEach(disable);\n controller.start((error => {\n form.removeAttribute(processingAttribute);\n if (error) {\n inputs.forEach(enable);\n } else {\n submitForm(form);\n }\n }));\n }\n}\n\nfunction submitForm(form) {\n let button = submitButtonsByForm.get(form) || findElement(form, \"input[type=submit], button[type=submit]\");\n if (button) {\n const {disabled: disabled} = button;\n button.disabled = false;\n button.focus();\n button.click();\n button.disabled = disabled;\n } else {\n button = document.createElement(\"input\");\n button.type = \"submit\";\n button.style.display = \"none\";\n form.appendChild(button);\n button.click();\n form.removeChild(button);\n }\n submitButtonsByForm.delete(form);\n}\n\nfunction disable(input) {\n input.disabled = true;\n}\n\nfunction enable(input) {\n input.disabled = false;\n}\n\nfunction autostart() {\n if (window.ActiveStorage) {\n start();\n }\n}\n\nsetTimeout(autostart, 1);\n\nexport { DirectUpload, DirectUploadController, DirectUploadsController, start };\n", "/**\n * Base class to be extended.\n */\nexport class BaseEvent extends Event {\n static eventName: string;\n constructor(name: string, options?: EventInit | undefined) {\n if (options == null) options = {};\n if (options.bubbles == null) options.bubbles = true;\n if (options.composed == null) options.composed = true;\n if (options.cancelable == null) options.cancelable = true;\n super(name, options);\n }\n}\n", "import { AttachmentManager } from \"../attachment-manager.js\";\nimport { BaseEvent } from \"./base-event.js\";\n\n/**\n * A mapping of the \"trix-attachment-add\" for Rhino that follows the same construct.\n * Fires after an attachment has been added.\n */\nexport class AddAttachmentEvent extends BaseEvent {\n static eventName = \"rhino-attachment-add\" as const;\n\n constructor(\n public attachment: AttachmentManager,\n options: Partial = {},\n ) {\n super(AddAttachmentEvent.eventName, options);\n this.attachment = attachment;\n }\n}\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n [AddAttachmentEvent.eventName]: AddAttachmentEvent;\n }\n}\n", "import { BaseEvent } from \"./base-event.js\";\n\n/**\n * Fires any time a user pastes into the editor\n */\nexport class RhinoFocusEvent extends BaseEvent {\n static eventName = \"rhino-focus\" as const;\n\n constructor(options?: EventInit | undefined) {\n super(RhinoFocusEvent.eventName, options);\n }\n}\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n [RhinoFocusEvent.eventName]: RhinoFocusEvent;\n }\n}\n", "import { BaseEvent } from \"./base-event.js\";\n\n/**\n * Fires any time the editor changes\n */\nexport class RhinoChangeEvent extends BaseEvent {\n static eventName = \"rhino-change\" as const;\n\n constructor(options?: EventInit | undefined) {\n super(RhinoChangeEvent.eventName, options);\n }\n}\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n [RhinoChangeEvent.eventName]: RhinoChangeEvent;\n }\n}\n", "import { BaseEvent } from \"./base-event.js\";\n\n/**\n * Fires any time a user pastes into the editor\n */\nexport class RhinoBlurEvent extends BaseEvent {\n static eventName = \"rhino-blur\" as const;\n\n constructor(options?: EventInit | undefined) {\n super(RhinoBlurEvent.eventName, options);\n }\n}\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n [RhinoBlurEvent.eventName]: RhinoBlurEvent;\n }\n}\n", "import { BaseEvent } from \"./base-event.js\";\n\n/**\n * Fires after the editor has been created\n */\nexport class InitializeEvent extends BaseEvent {\n static eventName = \"rhino-initialize\" as const;\n\n constructor(options?: EventInit | undefined) {\n super(InitializeEvent.eventName, options);\n }\n}\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n [InitializeEvent.eventName]: InitializeEvent;\n }\n}\n", "import { BaseEvent } from \"./base-event.js\";\n\n/**\n * A mapping of the \"trix-attachment-add\" for rhino that follows the same construct.\n * Use this to prevent uploading a file by calling `event.preventDefault()`\n */\nexport class FileAcceptEvent extends BaseEvent {\n static eventName = \"rhino-file-accept\" as const;\n\n constructor(\n public file: File,\n options?: EventInit | undefined,\n ) {\n super(FileAcceptEvent.eventName, options);\n this.file = file;\n }\n}\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n [FileAcceptEvent.eventName]: FileAcceptEvent;\n }\n}\n", "import { BaseEvent } from \"./base-event.js\";\n\n/**\n * Fires before the editor has been created\n */\nexport class BeforeInitializeEvent extends BaseEvent {\n static eventName = \"rhino-before-initialize\" as const;\n\n constructor(options?: EventInit | undefined) {\n super(BeforeInitializeEvent.eventName, options);\n }\n}\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n [BeforeInitializeEvent.eventName]: BeforeInitializeEvent;\n }\n}\n", "import { Transaction } from \"@tiptap/pm/state\";\nimport { BaseEvent } from \"./base-event.js\";\n\nexport interface SelectionChangeProps {\n transaction: Transaction;\n}\n\n/**\n * Fires before the editor has been created\n */\nexport class SelectionChangeEvent extends BaseEvent {\n static eventName = \"rhino-selection-change\" as const;\n\n transaction: Transaction;\n\n constructor(\n { transaction }: SelectionChangeProps,\n options?: EventInit | undefined,\n ) {\n super(SelectionChangeEvent.eventName, options);\n this.transaction = transaction;\n }\n}\n\ndeclare global {\n interface GlobalEventHandlersEventMap {\n [SelectionChangeEvent.eventName]: SelectionChangeEvent;\n }\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nconst NODE_MODE = false;\n\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\n/**\n * Whether the current browser supports `adoptedStyleSheets`.\n */\nexport const supportsAdoptingStyleSheets: boolean =\n global.ShadowRoot &&\n (global.ShadyCSS === undefined || global.ShadyCSS.nativeShadow) &&\n 'adoptedStyleSheets' in Document.prototype &&\n 'replace' in CSSStyleSheet.prototype;\n\n/**\n * A CSSResult or native CSSStyleSheet.\n *\n * In browsers that support constructible CSS style sheets, CSSStyleSheet\n * object can be used for styling along side CSSResult from the `css`\n * template tag.\n */\nexport type CSSResultOrNative = CSSResult | CSSStyleSheet;\n\nexport type CSSResultArray = Array;\n\n/**\n * A single CSSResult, CSSStyleSheet, or an array or nested arrays of those.\n */\nexport type CSSResultGroup = CSSResultOrNative | CSSResultArray;\n\nconst constructionToken = Symbol();\n\nconst cssTagCache = new WeakMap();\n\n/**\n * A container for a string of CSS text, that may be used to create a CSSStyleSheet.\n *\n * CSSResult is the return value of `css`-tagged template literals and\n * `unsafeCSS()`. In order to ensure that CSSResults are only created via the\n * `css` tag and `unsafeCSS()`, CSSResult cannot be constructed directly.\n */\nexport class CSSResult {\n // This property needs to remain unminified.\n ['_$cssResult$'] = true;\n readonly cssText: string;\n private _styleSheet?: CSSStyleSheet;\n private _strings: TemplateStringsArray | undefined;\n\n private constructor(\n cssText: string,\n strings: TemplateStringsArray | undefined,\n safeToken: symbol\n ) {\n if (safeToken !== constructionToken) {\n throw new Error(\n 'CSSResult is not constructable. Use `unsafeCSS` or `css` instead.'\n );\n }\n this.cssText = cssText;\n this._strings = strings;\n }\n\n // This is a getter so that it's lazy. In practice, this means stylesheets\n // are not created until the first element instance is made.\n get styleSheet(): CSSStyleSheet | undefined {\n // If `supportsAdoptingStyleSheets` is true then we assume CSSStyleSheet is\n // constructable.\n let styleSheet = this._styleSheet;\n const strings = this._strings;\n if (supportsAdoptingStyleSheets && styleSheet === undefined) {\n const cacheable = strings !== undefined && strings.length === 1;\n if (cacheable) {\n styleSheet = cssTagCache.get(strings);\n }\n if (styleSheet === undefined) {\n (this._styleSheet = styleSheet = new CSSStyleSheet()).replaceSync(\n this.cssText\n );\n if (cacheable) {\n cssTagCache.set(strings, styleSheet);\n }\n }\n }\n return styleSheet;\n }\n\n toString(): string {\n return this.cssText;\n }\n}\n\ntype ConstructableCSSResult = CSSResult & {\n new (\n cssText: string,\n strings: TemplateStringsArray | undefined,\n safeToken: symbol\n ): CSSResult;\n};\n\nconst textFromCSSResult = (value: CSSResultGroup | number) => {\n // This property needs to remain unminified.\n if ((value as CSSResult)['_$cssResult$'] === true) {\n return (value as CSSResult).cssText;\n } else if (typeof value === 'number') {\n return value;\n } else {\n throw new Error(\n `Value passed to 'css' function must be a 'css' function result: ` +\n `${value}. Use 'unsafeCSS' to pass non-literal values, but take care ` +\n `to ensure page security.`\n );\n }\n};\n\n/**\n * Wrap a value for interpolation in a {@linkcode css} tagged template literal.\n *\n * This is unsafe because untrusted CSS text can be used to phone home\n * or exfiltrate data to an attacker controlled site. Take care to only use\n * this with trusted input.\n */\nexport const unsafeCSS = (value: unknown) =>\n new (CSSResult as ConstructableCSSResult)(\n typeof value === 'string' ? value : String(value),\n undefined,\n constructionToken\n );\n\n/**\n * A template literal tag which can be used with LitElement's\n * {@linkcode LitElement.styles} property to set element styles.\n *\n * For security reasons, only literal string values and number may be used in\n * embedded expressions. To incorporate non-literal values {@linkcode unsafeCSS}\n * may be used inside an expression.\n */\nexport const css = (\n strings: TemplateStringsArray,\n ...values: (CSSResultGroup | number)[]\n): CSSResult => {\n const cssText =\n strings.length === 1\n ? strings[0]\n : values.reduce(\n (acc, v, idx) => acc + textFromCSSResult(v) + strings[idx + 1],\n strings[0]\n );\n return new (CSSResult as ConstructableCSSResult)(\n cssText,\n strings,\n constructionToken\n );\n};\n\n/**\n * Applies the given styles to a `shadowRoot`. When Shadow DOM is\n * available but `adoptedStyleSheets` is not, styles are appended to the\n * `shadowRoot` to [mimic the native feature](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot/adoptedStyleSheets).\n * Note, when shimming is used, any styles that are subsequently placed into\n * the shadowRoot should be placed *before* any shimmed adopted styles. This\n * will match spec behavior that gives adopted sheets precedence over styles in\n * shadowRoot.\n */\nexport const adoptStyles = (\n renderRoot: ShadowRoot,\n styles: Array\n) => {\n if (supportsAdoptingStyleSheets) {\n (renderRoot as ShadowRoot).adoptedStyleSheets = styles.map((s) =>\n s instanceof CSSStyleSheet ? s : s.styleSheet!\n );\n } else {\n for (const s of styles) {\n const style = document.createElement('style');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const nonce = (global as any)['litNonce'];\n if (nonce !== undefined) {\n style.setAttribute('nonce', nonce);\n }\n style.textContent = (s as CSSResult).cssText;\n renderRoot.appendChild(style);\n }\n }\n};\n\nconst cssResultFromStyleSheet = (sheet: CSSStyleSheet) => {\n let cssText = '';\n for (const rule of sheet.cssRules) {\n cssText += rule.cssText;\n }\n return unsafeCSS(cssText);\n};\n\nexport const getCompatibleStyle =\n supportsAdoptingStyleSheets ||\n (NODE_MODE && global.CSSStyleSheet === undefined)\n ? (s: CSSResultOrNative) => s\n : (s: CSSResultOrNative) =>\n s instanceof CSSStyleSheet ? cssResultFromStyleSheet(s) : s;\n", "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * Use this module if you want to create your own base class extending\n * {@link ReactiveElement}.\n * @packageDocumentation\n */\n\nimport {\n getCompatibleStyle,\n adoptStyles,\n CSSResultGroup,\n CSSResultOrNative,\n} from './css-tag.js';\nimport type {\n ReactiveController,\n ReactiveControllerHost,\n} from './reactive-controller.js';\n\n// In the Node build, this import will be injected by Rollup:\n// import {HTMLElement, customElements} from '@lit-labs/ssr-dom-shim';\n\nexport * from './css-tag.js';\nexport type {\n ReactiveController,\n ReactiveControllerHost,\n} from './reactive-controller.js';\n\n/**\n * Removes the `readonly` modifier from properties in the union K.\n *\n * This is a safer way to cast a value to a type with a mutable version of a\n * readonly field, than casting to an interface with the field re-declared\n * because it preserves the type of all the fields and warns on typos.\n */\ntype Mutable = Omit & {\n -readonly [P in keyof Pick]: P extends K ? T[P] : never;\n};\n\n// TODO (justinfagnani): Add `hasOwn` here when we ship ES2022\nconst {\n is,\n defineProperty,\n getOwnPropertyDescriptor,\n getOwnPropertyNames,\n getOwnPropertySymbols,\n getPrototypeOf,\n} = Object;\n\nconst NODE_MODE = false;\n\n// Lets a minifier replace globalThis references with a minified name\nconst global = globalThis;\n\nif (NODE_MODE) {\n global.customElements ??= customElements;\n}\n\nconst DEV_MODE = true;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nconst trustedTypes = (global as unknown as {trustedTypes?: {emptyScript: ''}})\n .trustedTypes;\n\n// Temporary workaround for https://crbug.com/993268\n// Currently, any attribute starting with \"on\" is considered to be a\n// TrustedScript source. Such boolean attributes must be set to the equivalent\n// trusted emptyScript value.\nconst emptyStringForBooleanAttribute = trustedTypes\n ? (trustedTypes.emptyScript as unknown as '')\n : '';\n\nconst polyfillSupport = DEV_MODE\n ? global.reactiveElementPolyfillSupportDevMode\n : global.reactiveElementPolyfillSupport;\n\nif (DEV_MODE) {\n // Ensure warnings are issued only 1x, even if multiple versions of Lit\n // are loaded.\n global.litIssuedWarnings ??= new Set();\n\n /**\n * Issue a warning if we haven't already, based either on `code` or `warning`.\n * Warnings are disabled automatically only by `warning`; disabling via `code`\n * can be done by users.\n */\n issueWarning = (code: string, warning: string) => {\n warning += ` See https://lit.dev/msg/${code} for more information.`;\n if (\n !global.litIssuedWarnings!.has(warning) &&\n !global.litIssuedWarnings!.has(code)\n ) {\n console.warn(warning);\n global.litIssuedWarnings!.add(warning);\n }\n };\n\n queueMicrotask(() => {\n issueWarning(\n 'dev-mode',\n `Lit is in dev mode. Not recommended for production!`\n );\n\n // Issue polyfill support warning.\n if (global.ShadyDOM?.inUse && polyfillSupport === undefined) {\n issueWarning(\n 'polyfill-support-missing',\n `Shadow DOM is being polyfilled via \\`ShadyDOM\\` but ` +\n `the \\`polyfill-support\\` module has not been loaded.`\n );\n }\n });\n}\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace ReactiveUnstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry = Update;\n export interface Update {\n kind: 'update';\n }\n }\n}\n\ninterface DebugLoggingWindow {\n // Even in dev mode, we generally don't want to emit these events, as that's\n // another level of cost, so only emit them when DEV_MODE is true _and_ when\n // window.emitLitDebugEvents is true.\n emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n ? (event: ReactiveUnstable.DebugLog.Entry) => {\n const shouldEmit = (global as unknown as DebugLoggingWindow)\n .emitLitDebugLogEvents;\n if (!shouldEmit) {\n return;\n }\n global.dispatchEvent(\n new CustomEvent('lit-debug', {\n detail: event,\n })\n );\n }\n : undefined;\n\n/*\n * When using Closure Compiler, JSCompiler_renameProperty(property, object) is\n * replaced at compile time by the munged name for object[property]. We cannot\n * alias this function, so we have to use a small shim that has the same\n * behavior when not compiling.\n */\n/*@__INLINE__*/\nconst JSCompiler_renameProperty =

(\n prop: P,\n _obj: unknown\n): P => prop;\n\n/**\n * Converts property values to and from attribute values.\n */\nexport interface ComplexAttributeConverter {\n /**\n * Called to convert an attribute value to a property\n * value.\n */\n fromAttribute?(value: string | null, type?: TypeHint): Type;\n\n /**\n * Called to convert a property value to an attribute\n * value.\n *\n * It returns unknown instead of string, to be compatible with\n * https://github.com/WICG/trusted-types (and similar efforts).\n */\n toAttribute?(value: Type, type?: TypeHint): unknown;\n}\n\ntype AttributeConverter =\n | ComplexAttributeConverter\n | ((value: string | null, type?: TypeHint) => Type);\n\n/**\n * Defines options for a property accessor.\n */\nexport interface PropertyDeclaration {\n /**\n * When set to `true`, indicates the property is internal private state. The\n * property should not be set by users. When using TypeScript, this property\n * should be marked as `private` or `protected`, and it is also a common\n * practice to use a leading `_` in the name. The property is not added to\n * `observedAttributes`.\n */\n readonly state?: boolean;\n\n /**\n * Indicates how and whether the property becomes an observed attribute.\n * If the value is `false`, the property is not added to `observedAttributes`.\n * If true or absent, the lowercased property name is observed (e.g. `fooBar`\n * becomes `foobar`). If a string, the string value is observed (e.g\n * `attribute: 'foo-bar'`).\n */\n readonly attribute?: boolean | string;\n\n /**\n * Indicates the type of the property. This is used only as a hint for the\n * `converter` to determine how to convert the attribute\n * to/from a property.\n */\n readonly type?: TypeHint;\n\n /**\n * Indicates how to convert the attribute to/from a property. If this value\n * is a function, it is used to convert the attribute value a the property\n * value. If it's an object, it can have keys for `fromAttribute` and\n * `toAttribute`. If no `toAttribute` function is provided and\n * `reflect` is set to `true`, the property value is set directly to the\n * attribute. A default `converter` is used if none is provided; it supports\n * `Boolean`, `String`, `Number`, `Object`, and `Array`. Note,\n * when a property changes and the converter is used to update the attribute,\n * the property is never updated again as a result of the attribute changing,\n * and vice versa.\n */\n readonly converter?: AttributeConverter;\n\n /**\n * Indicates if the property should reflect to an attribute.\n * If `true`, when the property is set, the attribute is set using the\n * attribute name determined according to the rules for the `attribute`\n * property option and the value of the property converted using the rules\n * from the `converter` property option.\n */\n readonly reflect?: boolean;\n\n /**\n * A function that indicates if a property should be considered changed when\n * it is set. The function should take the `newValue` and `oldValue` and\n * return `true` if an update should be requested.\n */\n hasChanged?(value: Type, oldValue: Type): boolean;\n\n /**\n * Indicates whether an accessor will be created for this property. By\n * default, an accessor will be generated for this property that requests an\n * update when set. If this flag is `true`, no accessor will be created, and\n * it will be the user's responsibility to call\n * `this.requestUpdate(propertyName, oldValue)` to request an update when\n * the property changes.\n */\n readonly noAccessor?: boolean;\n\n /**\n * Whether this property is wrapping accessors. This is set by `@property`\n * to control the initial value change and reflection logic.\n *\n * @internal\n */\n wrapped?: boolean;\n\n /**\n * When `true`, uses the initial value of the property as the default value,\n * which changes how attributes are handled:\n * - The initial value does *not* reflect, even if the `reflect` option is `true`.\n * Subsequent changes to the property will reflect, even if they are equal to the\n * default value.\n * - When the attribute is removed, the property is set to the default value\n * - The initial value will not trigger an old value in the `changedProperties` map\n * argument to update lifecycle methods.\n *\n * When set, properties must be initialized, either with a field initializer, or an\n * assignment in the constructor. Not initializing the property may lead to\n * improper handling of subsequent property assignments.\n *\n * While this behavior is opt-in, most properties that reflect to attributes should\n * use `useDefault: true` so that their initial values do not reflect.\n */\n useDefault?: boolean;\n}\n\n/**\n * Map of properties to PropertyDeclaration options. For each property an\n * accessor is made, and the property is processed according to the\n * PropertyDeclaration options.\n */\nexport interface PropertyDeclarations {\n readonly [key: string]: PropertyDeclaration;\n}\n\ntype PropertyDeclarationMap = Map;\n\ntype AttributeMap = Map;\n\n/**\n * A Map of property keys to values.\n *\n * Takes an optional type parameter T, which when specified as a non-any,\n * non-unknown type, will make the Map more strongly-typed, associating the map\n * keys with their corresponding value type on T.\n *\n * Use `PropertyValues` when overriding ReactiveElement.update() and\n * other lifecycle methods in order to get stronger type-checking on keys\n * and values.\n */\n// This type is conditional so that if the parameter T is not specified, or\n// is `any`, the type will include `Map`. Since T is not\n// given in the uses of PropertyValues in this file, all uses here fallback to\n// meaning `Map`, but if a developer uses\n// `PropertyValues` (or any other value for T) they will get a\n// strongly-typed Map type.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type PropertyValues = T extends object\n ? PropertyValueMap\n : Map;\n\n/**\n * Do not use, instead prefer {@linkcode PropertyValues}.\n */\n// This type must be exported such that JavaScript generated by the Google\n// Closure Compiler can import a type reference.\nexport interface PropertyValueMap extends Map {\n get(k: K): T[K] | undefined;\n set(key: K, value: T[K]): this;\n has(k: K): boolean;\n delete(k: K): boolean;\n}\n\nexport const defaultConverter: ComplexAttributeConverter = {\n toAttribute(value: unknown, type?: unknown): unknown {\n switch (type) {\n case Boolean:\n value = value ? emptyStringForBooleanAttribute : null;\n break;\n case Object:\n case Array:\n // if the value is `null` or `undefined` pass this through\n // to allow removing/no change behavior.\n value = value == null ? value : JSON.stringify(value);\n break;\n }\n return value;\n },\n\n fromAttribute(value: string | null, type?: unknown) {\n let fromValue: unknown = value;\n switch (type) {\n case Boolean:\n fromValue = value !== null;\n break;\n case Number:\n fromValue = value === null ? null : Number(value);\n break;\n case Object:\n case Array:\n // Do *not* generate exception when invalid JSON is set as elements\n // don't normally complain on being mis-configured.\n // TODO(sorvell): Do generate exception in *dev mode*.\n try {\n // Assert to adhere to Bazel's \"must type assert JSON parse\" rule.\n fromValue = JSON.parse(value!) as unknown;\n } catch (e) {\n fromValue = null;\n }\n break;\n }\n return fromValue;\n },\n};\n\nexport interface HasChanged {\n (value: unknown, old: unknown): boolean;\n}\n\n/**\n * Change function that returns true if `value` is different from `oldValue`.\n * This method is used as the default for a property's `hasChanged` function.\n */\nexport const notEqual: HasChanged = (value: unknown, old: unknown): boolean =>\n !is(value, old);\n\nconst defaultPropertyDeclaration: PropertyDeclaration = {\n attribute: true,\n type: String,\n converter: defaultConverter,\n reflect: false,\n useDefault: false,\n hasChanged: notEqual,\n};\n\n/**\n * A string representing one of the supported dev mode warning categories.\n */\nexport type WarningKind =\n | 'change-in-update'\n | 'migration'\n | 'async-perform-update';\n\nexport type Initializer = (element: ReactiveElement) => void;\n\n// Temporary, until google3 is on TypeScript 5.2\ndeclare global {\n interface SymbolConstructor {\n readonly metadata: unique symbol;\n }\n}\n\n// Ensure metadata is enabled. TypeScript does not polyfill\n// Symbol.metadata, so we must ensure that it exists.\n(Symbol as {metadata: symbol}).metadata ??= Symbol('metadata');\n\ndeclare global {\n // This is public global API, do not change!\n // eslint-disable-next-line no-var\n var litPropertyMetadata: WeakMap<\n object,\n Map\n >;\n}\n\n// Map from a class's metadata object to property options\n// Note that we must use nullish-coalescing assignment so that we only use one\n// map even if we load multiple version of this module.\nglobal.litPropertyMetadata ??= new WeakMap<\n object,\n Map\n>();\n\n/**\n * Base element class which manages element properties and attributes. When\n * properties change, the `update` method is asynchronously called. This method\n * should be supplied by subclasses to render updates as desired.\n * @noInheritDoc\n */\nexport abstract class ReactiveElement\n // In the Node build, this `extends` clause will be substituted with\n // `(globalThis.HTMLElement ?? HTMLElement)`.\n //\n // This way, we will first prefer any global `HTMLElement` polyfill that the\n // user has assigned, and then fall back to the `HTMLElement` shim which has\n // been imported (see note at the top of this file about how this import is\n // generated by Rollup). Note that the `HTMLElement` variable has been\n // shadowed by this import, so it no longer refers to the global.\n extends HTMLElement\n implements ReactiveControllerHost\n{\n // Note: these are patched in only in DEV_MODE.\n /**\n * Read or set all the enabled warning categories for this class.\n *\n * This property is only used in development builds.\n *\n * @nocollapse\n * @category dev-mode\n */\n static enabledWarnings?: WarningKind[];\n\n /**\n * Enable the given warning category for this class.\n *\n * This method only exists in development builds, so it should be accessed\n * with a guard like:\n *\n * ```ts\n * // Enable for all ReactiveElement subclasses\n * ReactiveElement.enableWarning?.('migration');\n *\n * // Enable for only MyElement and subclasses\n * MyElement.enableWarning?.('migration');\n * ```\n *\n * @nocollapse\n * @category dev-mode\n */\n static enableWarning?: (warningKind: WarningKind) => void;\n\n /**\n * Disable the given warning category for this class.\n *\n * This method only exists in development builds, so it should be accessed\n * with a guard like:\n *\n * ```ts\n * // Disable for all ReactiveElement subclasses\n * ReactiveElement.disableWarning?.('migration');\n *\n * // Disable for only MyElement and subclasses\n * MyElement.disableWarning?.('migration');\n * ```\n *\n * @nocollapse\n * @category dev-mode\n */\n static disableWarning?: (warningKind: WarningKind) => void;\n\n /**\n * Adds an initializer function to the class that is called during instance\n * construction.\n *\n * This is useful for code that runs against a `ReactiveElement`\n * subclass, such as a decorator, that needs to do work for each\n * instance, such as setting up a `ReactiveController`.\n *\n * ```ts\n * const myDecorator = (target: typeof ReactiveElement, key: string) => {\n * target.addInitializer((instance: ReactiveElement) => {\n * // This is run during construction of the element\n * new MyController(instance);\n * });\n * }\n * ```\n *\n * Decorating a field will then cause each instance to run an initializer\n * that adds a controller:\n *\n * ```ts\n * class MyElement extends LitElement {\n * @myDecorator foo;\n * }\n * ```\n *\n * Initializers are stored per-constructor. Adding an initializer to a\n * subclass does not add it to a superclass. Since initializers are run in\n * constructors, initializers will run in order of the class hierarchy,\n * starting with superclasses and progressing to the instance's class.\n *\n * @nocollapse\n */\n static addInitializer(initializer: Initializer) {\n this.__prepare();\n (this._initializers ??= []).push(initializer);\n }\n\n static _initializers?: Initializer[];\n\n /*\n * Due to closure compiler ES6 compilation bugs, @nocollapse is required on\n * all static methods and properties with initializers. Reference:\n * - https://github.com/google/closure-compiler/issues/1776\n */\n\n /**\n * Maps attribute names to properties; for example `foobar` attribute to\n * `fooBar` property. Created lazily on user subclasses when finalizing the\n * class.\n * @nocollapse\n */\n private static __attributeToPropertyMap: AttributeMap;\n\n /**\n * Marks class as having been finalized, which includes creating properties\n * from `static properties`, but does *not* include all properties created\n * from decorators.\n * @nocollapse\n */\n protected static finalized: true | undefined;\n\n /**\n * Memoized list of all element properties, including any superclass\n * properties. Created lazily on user subclasses when finalizing the class.\n *\n * @nocollapse\n * @category properties\n */\n static elementProperties: PropertyDeclarationMap;\n\n /**\n * User-supplied object that maps property names to `PropertyDeclaration`\n * objects containing options for configuring reactive properties. When\n * a reactive property is set the element will update and render.\n *\n * By default properties are public fields, and as such, they should be\n * considered as primarily settable by element users, either via attribute or\n * the property itself.\n *\n * Generally, properties that are changed by the element should be private or\n * protected fields and should use the `state: true` option. Properties\n * marked as `state` do not reflect from the corresponding attribute\n *\n * However, sometimes element code does need to set a public property. This\n * should typically only be done in response to user interaction, and an event\n * should be fired informing the user; for example, a checkbox sets its\n * `checked` property when clicked and fires a `changed` event. Mutating\n * public properties should typically not be done for non-primitive (object or\n * array) properties. In other cases when an element needs to manage state, a\n * private property set with the `state: true` option should be used. When\n * needed, state properties can be initialized via public properties to\n * facilitate complex interactions.\n * @nocollapse\n * @category properties\n */\n static properties: PropertyDeclarations;\n\n /**\n * Memoized list of all element styles.\n * Created lazily on user subclasses when finalizing the class.\n * @nocollapse\n * @category styles\n */\n static elementStyles: Array = [];\n\n /**\n * Array of styles to apply to the element. The styles should be defined\n * using the {@linkcode css} tag function, via constructible stylesheets, or\n * imported from native CSS module scripts.\n *\n * Note on Content Security Policy:\n *\n * Element styles are implemented with `\n \n \n \n `}};e.tag=\"scandit-rounded-exclamation-mark-icon\";var t=e;t.register();\n\nexport { t as a };\n", "import { a } from './chunk-MAMZS5CH.js';\nimport { a as a$1 } from './chunk-3A4KLILV.js';\nimport { a as a$2 } from './chunk-U6BTTEV6.js';\n\nvar e=class e extends a{static create(){return document.createElement(e.tag)}static register(){a$1({[e.tag]:e});}render(){return a$2`\n \n \n \n \n `}};e.tag=\"scandit-rounded-check-icon\";var t=e;t.register();\n\nexport { t as a };\n", "import { n as n$1 } from './chunk-N4NOODAT.js';\n\nvar e=n$1.fromRGBA(46,193,206,1),n=n$1.fromRGBA(98,209,218,1),t=n$1.fromRGBA(151,224,230,1),c=n$1.fromRGBA(203,240,243,1),a=n$1.fromRGBA(18,22,25,1),m=n$1.fromRGBA(218,225,231,1),p=n$1.fromRGBA(40,211,128,1),G=n$1.fromRGBA(83,220,153,1),R=n$1.fromRGBA(126,229,179,1),f=n$1.fromRGBA(169,237,204,1),s=n$1.fromRGBA(212,246,230,1),x=n$1.fromRGBA(251,192,44,1),y=n$1.fromRGBA(252,205,86,1),A=n$1.fromRGBA(253,217,128,1),B=n$1.fromRGBA(254,230,171,1),d=n$1.fromRGBA(254,242,213,1),S=n$1.fromRGBA(250,68,70,1),g=n$1.fromRGBA(251,105,107,1),i=n$1.fromRGBA(252,143,144,1),l=n$1.fromRGBA(253,180,181,1),O=n$1.fromRGBA(254,218,218,1);\n\nexport { e as a, n as b, t as c, c as d, a as e, m as f, p as g, G as h, R as i, f as j, s as k, x as l, y as m, A as n, B as o, d as p, S as q, g as r, i as s, l as t, O as u };\n", "function m(n,...r){let e=document.createElement(\"style\");return e.innerHTML=n.reduce((c,l,s)=>{var t;let a=(t=r.at(s))!=null?t:\"\";return c+l+String(a)},\"\"),e}\n\nexport { m as a };\n", "import { a as a$2 } from './chunk-5IVFVUF4.js';\nimport { a as a$3 } from './chunk-M46MIHI5.js';\nimport { e as e$1 } from './chunk-MSPQDVWJ.js';\nimport { a as a$6 } from './chunk-3A4KLILV.js';\nimport { a as a$4 } from './chunk-U6BTTEV6.js';\nimport { a as a$1 } from './chunk-EV4OEANA.js';\nimport { a as a$5 } from './chunk-GE4CBD4E.js';\n\nvar b=(i=>(i.DidShow=\"didshow\",i.DidHide=\"didhide\",i.WillShow=\"willshow\",i))(b||{}),o=\"--text-size\",s=\"--text-color\",n=\"--text-alignment\",a=\"--text-weight\",r=\"--line-height\",l=\"--background-color\",c=\"--corner-radius\",h=\"--max-lines\",x=\"ease-in-out\",e=class e extends a$1{constructor(){super();this.toast=null;this._hintStyle=null;this.currentAnimation=null;this.animationDuration=250;let t=this.attachShadow({mode:\"open\"});this._exclamationIcon=a$2.create(),this._checkIcon=a$3.create(),this._exclamationIcon.size=24,this._checkIcon.size=24,t.innerHTML=a$4`\n

\n \n
\n \n
\n

\n \n

\n
\n `,t.append(e.createStyleElement().cloneNode(!0)),this.toast=t.querySelector(\".toast\");}static createStyleElement(){return a$5`\n :host {\n font-family: \"SF Pro Display\", sans-serif;\n display: inline-block;\n }\n :host([hidden]) {\n display: none;\n }\n .toast {\n ${o}: 1rem;\n ${s} black;\n ${a}: 400;\n ${n}: ${\"center\"};\n ${r}: 1.5rem;\n ${l}: white;\n ${c}: 0.25rem;\n ${h}: 2;\n\n color: var(${s});\n font-size$: var(${o});\n font-weight: var(${a});\n line-height: var(${r});\n\n padding: 1rem;\n display: flex;\n flex-direction: row;\n align-items: flex-start;\n justify-content: var(${n});\n gap: 0.625rem;\n border-radius: var(${c});\n background-color: var(${l});\n }\n\n :host([direction=\"column\"]) .toast {\n flex-direction: column;\n align-items: center;\n }\n\n :host([diretion=\"row\"]) .toast {\n flex-direction: row;\n align-items: center;\n }\n\n .toast .left {\n display: flex;\n align-self: flex-start;\n }\n\n .toast.icon-${\"none\"} .left {\n display: none;\n }\n\n .toast p.middle {\n display: inline-block;\n margin: 0;\n padding: 0;\n text-align: var(${n});\n display: -webkit-box;\n -webkit-line-clamp: var(${h});\n -webkit-box-orient: vertical;\n overflow: hidden;\n align-self: center;\n text-shadow: 0px 1px 2px #${e$1.withAlpha(.3).toJSON()};\n }\n\n p.middle {\n text-align: var(${n});\n }\n `}get hintStyle(){return this._hintStyle}set hintStyle(t){this._hintStyle=t,this.render();}get showAnimation(){return new Animation(new KeyframeEffect(this,[{opacity:0},{opacity:1}],{duration:this.animationDuration,fill:\"both\",easing:x}))}get hideAnimation(){return new Animation(new KeyframeEffect(this,[{opacity:1},{opacity:0}],{duration:this.animationDuration,fill:\"both\",easing:x}))}static create(){return document.createElement(e.tag)}static register(){a$6({[e.tag]:e});}async show(){return this.toggle(!0)}async hide(){return this.toggle(!1)}connectedCallback(){this.render();}async toggle(t){var i,m;if(this.currentAnimation==null){this.animationDuration=(m=(i=this.hintStyle)==null?void 0:i.isAnimatedToView)==null||m?250:0,this.currentAnimation=t?this.showAnimation:this.hideAnimation,t&&this.dispatchEvent(new CustomEvent(\"willshow\",{bubbles:!0})),this.currentAnimation.play();try{await this.currentAnimation.finished,this.dispatchEvent(new CustomEvent(t?\"didshow\":\"didhide\",{bubbles:!0,detail:{target:this}}));}catch(E){}finally{this.currentAnimation=null;}}}render(){var t;!this.toast||!this.hintStyle||(this.toast.className=\"toast\",this.toast.style.setProperty(o,`${this.hintStyle.textSize}px`),this.toast.style.setProperty(s,`#${this.hintStyle.textColor}`),this.toast.style.setProperty(a,this.hintStyle.textWeight.toString()),this.toast.style.setProperty(n,this.hintStyle.textAlignment),this.toast.style.setProperty(r,`${this.hintStyle.lineHeight/14}`),this.toast.style.setProperty(l,`#${this.hintStyle.backgroundColor}`),this.toast.style.setProperty(c,`${this.hintStyle.cornerRadius/10}rem`),this.toast.style.setProperty(h,this.hintStyle.maxLines.toString()),this.toast.classList.toggle(\"icon-none\",this.hintStyle.hintIcon===\"none\"),this.hintStyle.hintIcon===\"check\"?(this._checkIcon.setAttribute(\"slot\",\"icon\"),this.append(this._checkIcon)):this.hintStyle.hintIcon===\"exclamationMark\"&&(this._exclamationIcon.setAttribute(\"slot\",\"icon\"),this.append(this._exclamationIcon)),(t=this.querySelector(\"[slot=icon]\"))==null||t.setAttribute(\"fill\",`#${this.hintStyle.iconColor}`));}};e.tag=\"scandit-toast-hint\";var d=e;d.register();\n\nexport { b as a, d as b };\n", "import { a as a$2 } from './chunk-3A4KLILV.js';\nimport { a as a$3 } from './chunk-U6BTTEV6.js';\nimport { a } from './chunk-EV4OEANA.js';\nimport { a as a$1 } from './chunk-GE4CBD4E.js';\n\nvar l=\"scandit-arrows-up\",t=class t extends a{constructor(){super();let a=this.attachShadow({mode:\"open\"});a.innerHTML=this.render(),a.prepend(t.createStyleElement().cloneNode(!0));}static createStyleElement(){return a$1`\n ${t.tag} {\n display: flex;\n }\n ${t.tag}[hidden] {\n display: none;\n }\n .arrow {\n animation: blink 1.5s infinite;\n animation-duration: 2s;\n }\n\n .arrow-1 {\n animation-delay: 0s;\n }\n\n .arrow-2 {\n animation-delay: 0.5s;\n }\n\n .arrow-3 {\n animation-delay: 1s;\n }\n\n @keyframes blink {\n 0%,\n 100% {\n opacity: 0;\n }\n 50% {\n opacity: 1;\n }\n }\n `}static create(){return document.createElement(t.tag)}static register(){a$2({[t.tag]:t});}render(){return a$3`\n \n \n \n \n \n `}};t.tag=l;var e=t;e.register();\n\nexport { e as a };\n", "var a=\"orientationchange\",n={\"portrait-primary\":{type:\"portrait-primary\",angle:0,value:\"portrait\"},\"portrait-secondary\":{type:\"portrait-secondary\",angle:180,value:\"portraitUpsideDown\"},\"landscape-primary\":{type:\"landscape-primary\",angle:90,value:\"landscapeLeft\"},\"landscape-secondary\":{type:\"landscape-secondary\",angle:270,value:\"landscapeRight\"}},t=class extends EventTarget{constructor(){super(...arguments);this.orientation={value:\"portrait\",type:\"portrait-primary\",angle:0};this.landscapeOrientationMediaQuery=matchMedia(\"(orientation: landscape)\");this.screenOrientationChangeListener=this.onScreenOrientationChange.bind(this);this.landscapeOrientationMediaQueryChangeListener=this.onLandscapeOrientationMediaQueryChange.bind(this);}register(){this.isScreenOrientationApiSupported()?(screen.orientation.addEventListener(\"change\",this.screenOrientationChangeListener),this.onScreenOrientationChange()):(this.landscapeOrientationMediaQuery.addEventListener(\"change\",this.landscapeOrientationMediaQueryChangeListener),this.onLandscapeOrientationMediaQueryChange(new MediaQueryListEvent(\"change\",{matches:this.landscapeOrientationMediaQuery.matches})));}unregister(){this.isScreenOrientationApiSupported()?screen.orientation.removeEventListener(\"change\",this.screenOrientationChangeListener):this.landscapeOrientationMediaQuery.removeEventListener(\"change\",this.landscapeOrientationMediaQueryChangeListener);}isScreenOrientationApiSupported(){return \"screen\"in window&&\"orientation\"in screen&&typeof screen.orientation.addEventListener==\"function\"}dispatchOrientationChangeEvent(e){this.dispatchEvent(new CustomEvent(a,{detail:e}));}onScreenOrientationChange(){this.orientation=n[screen.orientation.type],this.dispatchOrientationChangeEvent(this.orientation);}onLandscapeOrientationMediaQueryChange(e){let i=e;this.orientation=i.matches?n[\"landscape-primary\"]:n[\"portrait-primary\"],this.dispatchOrientationChangeEvent(this.orientation);}};\n\nexport { a, t as b };\n", "function r(t,n=300){let e=null;return function(...u){e!=null&&clearTimeout(e),e=setTimeout(()=>{t.apply(this,u),e=null;},n);}}\n\nexport { r as a };\n", "import { b as b$1 } from './chunk-U2VVDSM3.js';\nimport { a as a$7 } from './chunk-CNCPCHBZ.js';\nimport { b, a as a$6 } from './chunk-5S537AFM.js';\nimport { a as a$5 } from './chunk-3A4KLILV.js';\nimport { a as a$3 } from './chunk-U6BTTEV6.js';\nimport { a as a$1 } from './chunk-EV4OEANA.js';\nimport { a as a$4 } from './chunk-GE4CBD4E.js';\nimport { a as a$2 } from './chunk-R6E4CT22.js';\n\nvar o=\"--view-finder-top\",a=\"--view-finder-bottom\",s=\"--hint-anchor-offset\",H=\"--max-width-fraction\",T=\"--horizontal-margin\",d=\"--max-width-ratio-adjust\",w=(c=>(c.Update=\"hintpresenterupdate\",c))(w||{}),n=class n extends a$1{constructor(){super();this.onDidToastHideHandler=this.onDidToastHide.bind(this);this.orientationObserver=new b;this.onOrientationChangeHandler=a$2(this.onOrientationChange.bind(this),10);let t=this.attachShadow({mode:\"open\"});t.innerHTML=a$3`\n
\n \n
\n `,t.append(n.createStyleElement().cloneNode(!0)),this.root=t.querySelector(\"#root\");}static createStyleElement(){return a$4`\n :host {\n pointer-events: none;\n }\n :host #root {\n position: absolute;\n width: 100%;\n top: env(safe-area-inset-top, 5vh);\n right: env(safe-area-inset-right, 0px);\n bottom: env(safe-area-inset-bottom, 5vh);\n left: env(safe-area-inset-left, 0px);\n ${o}: 0px;\n ${a}: 0px;\n ${d}: 1;\n z-index: 1;\n }\n\n ::slotted(${b$1.tag}) {\n position: absolute;\n left: 50%;\n transform: translate3d(-50%, 0%, 0);\n width: 100%;\n max-width: calc(\n calc(var(${H}) * var(${d}) * 100%) -\n var(${T})\n );\n }\n\n ::slotted(${b$1.tag}.${\"aboveViewFinder\"}) {\n transform: translate3d(\n -50%,\n calc(-100% + var(${o}) - var(${s})),\n 0\n );\n }\n\n ::slotted(${b$1.tag}.${\"belowViewFinder\"}) {\n transform: translate3d(\n -50%,\n calc(var(${a}) + var(${s})),\n 0\n );\n }\n\n ::slotted(${b$1.tag}.${\"top\"}) {\n top: calc(var(${s}));\n }\n\n ::slotted(${b$1.tag}.fitToText) {\n width: fit-content;\n }\n `}static register(){a$5({[n.tag]:n});}static create(){return document.createElement(n.tag)}connectedCallback(){this.orientationObserver.addEventListener(a$6,this.onOrientationChangeHandler),this.orientationObserver.register(),this.addEventListener(\"didhide\",this.onDidToastHideHandler),this._viewFinderRect==null&&(this.root.style.setProperty(o,`${this.root.clientHeight/2}px`),this.root.style.setProperty(a,`${this.root.clientHeight/2+1}px`));}disconnectedCallback(){this.removeEventListener(\"didhide\",this.onDidToastHideHandler);}setViewFinderRect(t){if(t===null){this.root.style.removeProperty(o),this.root.style.removeProperty(a);return}this._viewFinderRect=t;let{origin:{y:i},size:{height:e}}=this._viewFinderRect;this.root.style.setProperty(o,`${i}px`),this.root.style.setProperty(a,`${i+e}px`);}handleMessage(t){let{type:i}=t;switch(i){case\"showToast\":{this.showToast(t.payload);break}case\"hideToast\":{this.hideToast(t.payload);break}case\"showGuidance\":{this.showGuidance(t.payload);break}case\"hideGuidance\":{this.hideGuidance(t.payload);break}case\"startUpdateTimer\":{this.startUpdateTimer(t.payload.duration.value);break}case\"stopUpdateTimer\":{this.stopUpdateTimer();break}}}onDidToastHide(t){t.stopPropagation(),t.detail.target.remove();}async showToast(t){let i=this.idFromHint(t),e=this.querySelector(`#${i}`);if(e||(e=b$1.create(),e.id=i,this.append(e)),e.textContent=t.text,e.hintStyle=t.hintStyle,e.className=\"\",e.style.setProperty(s,`${e.hintStyle.hintAnchorOffset/16}rem`),e.style.setProperty(H,t.hintStyle.maxWidthFraction.toString()),e.style.setProperty(T,`${t.hintStyle.horizontalMargin/16}rem`),e.classList.add(t.hintStyle.hintAnchor),e.classList.toggle(\"fitToText\",t.hintStyle.fitToText),t.tag===\"MoveCloserGuidance\"){let h=a$7.create();h.setAttribute(\"slot\",\"first-child\"),e.append(h),e.setAttribute(\"direction\",\"column\");}return e.show()}async hideToast(t){let i=this.querySelector(`#${this.idFromHint(t)}`);if(i!=null)return i.hide()}async showGuidance(t){return this.showToast(t)}async hideGuidance(t){return this.hideToast(t)}startUpdateTimer(t){this.intervalId=setInterval(()=>{this.dispatchEvent(new CustomEvent(\"hintpresenterupdate\"));},t);}stopUpdateTimer(){clearInterval(this.intervalId);}idFromHint(t){var i;return btoa([t.hintStyle.textColor,t.hintStyle.backgroundColor,t.hintStyle.hintAnchor,(i=t.tag)!=null?i:\"\",t.hintStyle.textAlignment].join(\"-\")).replace(/\\+/g,\"-\").replace(/\\//g,\"_\").replace(/=+$/,\"\")}onOrientationChange(t){let i=1;i=t.detail.value===\"landscapeLeft\"||t.detail.value===\"landscapeRight\"?window.innerHeight/window.innerWidth:1,this.root.style.setProperty(d,i.toString()),this._viewFinderRect==null&&(this.root.style.setProperty(o,`${this.root.clientHeight/2}px`),this.root.style.setProperty(a,`${this.root.clientHeight/2+1}px`));}};n.tag=\"scandit-hints\";var l=n;l.register();\n\nexport { w as a, l as b };\n", "import { b, a as a$4, c, f as f$1 } from './chunk-MSPQDVWJ.js';\nimport { a as a$5 } from './chunk-3A4KLILV.js';\nimport { a as a$2 } from './chunk-U6BTTEV6.js';\nimport { a as a$1 } from './chunk-EV4OEANA.js';\nimport { a as a$3 } from './chunk-GE4CBD4E.js';\n\nvar h=\"scandit-progress-bar\",n=\"aria-valuenow\",f=\"aria-valuemin\",w=\"aria-valuemax\",a=class a extends a$1{constructor(){super();let e=this.attachShadow({mode:\"open\"});e.innerHTML=a$2`\n
\n `,e.append(a.createStyleElement().cloneNode(!0)),this.progress=e.querySelector(\"#scandit-progress\");}static get observedAttributes(){return [\"value\",\"min\",\"max\"]}static createStyleElement(){return a$3`\n :host {\n display: inline-block;\n --indeterminate-bubble-width: 35%;\n --accent-color: #${b.toJSON()};\n --start-gradient-color: #${a$4.toJSON()};\n --end-gradient-color: #${c.toJSON()};\n --secondary-color: #${f$1.toJSON()};\n width: 100%;\n }\n\n :host [role=\"progressbar\"] {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n position: relative;\n overflow: hidden;\n border: none;\n height: 0.5rem;\n }\n\n :host [role=\"progressbar\"]::before,\n :host [role=\"progressbar\"]::after {\n content: \" \";\n position: absolute;\n top: 0;\n left: 0;\n background: var(--accent-color);\n height: 0.5rem;\n border-radius: 0.5rem;\n }\n\n :host([variant=\"gradient\"]) [role=\"progressbar\"]::before,\n :host([variant=\"gradient\"]) [role=\"progressbar\"]::after {\n background: linear-gradient(90deg, var(--start-gradient-color) 0%, var(--end-gradient-color) 100%);\n }\n\n :host(:focus-visible) {\n outline-color: var(--accent-color);\n outline-offset: 5px;\n border-radius: 0.5rem;\n }\n\n :host [role=\"progressbar\"]:not([aria-valuenow])::after {\n width: var(--indeterminate-bubble-width);\n animation: indeterminate-progress-bar 2.5s ease infinite;\n z-index: 1;\n }\n\n :host [role=\"progressbar\"][aria-valuenow]::after {\n width: 0;\n animation: none;\n }\n\n :host [role=\"progressbar\"][aria-valuenow]::before {\n width: calc(var(--aria-valuenow) * 1%);\n background-color: var(--accent-color);\n border-radius: 0.5rem;\n transition: width 0.3s linear;\n }\n\n :host [role=\"progressbar\"] {\n background-color: var(--secondary-color);\n border-radius: 0.5rem;\n }\n\n @keyframes indeterminate-progress-bar {\n 0% {\n left: 0%;\n }\n 50% {\n left: calc(100% - var(--indeterminate-bubble-width));\n }\n }\n `}get min(){var r;let e=(r=this.getAttribute(\"min\"))!=null?r:0;return Number(e)}get max(){var r;let e=(r=this.getAttribute(\"max\"))!=null?r:1;return Number(e)}set max(e){e!==null&&this.setAttribute(\"max\",String(e));}get value(){let e=this.getAttribute(\"value\");return e==null||e===\"\"?null:Number(e)}set value(e){if(e==null){this.removeAttribute(\"value\");return}e>=this.min&&e<=this.max&&this.setAttribute(\"value\",String(e));}static create(){return document.createElement(h)}static register(){a$5({[a.tag]:a});}attributeChangedCallback(){this.update();}connectedCallback(){this.update();}update(){let{min:e,max:r,value:i,progress:t}=this;if(t==null||t.setAttribute(f,e.toString()),t==null||t.setAttribute(w,r.toString()),i==null){t==null||t.removeAttribute(n),t==null||t.removeAttribute(\"style\");return}if(i>=e&&i<=r){let v=(i-e)/(r-e)*100,l=String(v);t==null||t.setAttribute(n,l),t==null||t.setAttribute(\"style\",`--${n}: ${l}`);}}};a.tag=h;var o=a;o.register();\n\nexport { o as a };\n", "var n=class i{constructor(){this.translations=new Map;}static getInstance(){return i.instance==null&&(i.instance=new i),i.instance}get(t){var s;return (s=this.translations.get(t))!=null?s:\"\"}getAll(){return {...this.translations}}update(t){this.translations=new Map(Object.entries({...Object.fromEntries(this.translations),...t}));}updateIfMissing(t){for(let[s,e]of Object.entries(t))this.translations.has(s)||this.translations.set(s,e);}};\n\nexport { n as a };\n", "import { a as a$5 } from './chunk-GXUTZY74.js';\nimport { a as a$6 } from './chunk-DTSV5FYV.js';\nimport { a as a$3 } from './chunk-3A4KLILV.js';\nimport { a as a$2 } from './chunk-U6BTTEV6.js';\nimport { a as a$1 } from './chunk-EV4OEANA.js';\nimport { a as a$4 } from './chunk-GE4CBD4E.js';\n\nvar d=\"scandit-loading-overlay\",t=class t extends a$1{constructor(){super();this._progressBar=null;this._label=null;let e=this.attachShadow({mode:\"open\"});e.innerHTML=a$2`\n
\n \n \n
\n `,e.append(t.createStyleElement().cloneNode(!0));}set progress(e){this._progressBar&&(this._progressBar.value=e);}set message(e){this._label&&(this._label.textContent=e);}get message(){var e,r;return (r=(e=this._label)==null?void 0:e.textContent)!=null?r:\"\"}static create(){return document.createElement(t.tag)}static register(){a$3({[d]:t});}static createStyleElement(){return a$4`\n @media (prefers-color-scheme: dark) {\n .loading-overlay {\n --foreground-color: white;\n --background-color: black;\n }\n }\n\n @media (prefers-color-scheme: light) {\n .loading-overlay {\n --foreground-color: black;\n --background-color: white;\n }\n }\n\n ${a$5.tag} {\n max-width: 15rem;\n }\n\n .loading-overlay {\n position: absolute;\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n z-index: 1;\n background-color: var(--background-color);\n }\n\n :host([hidden]) {\n display: none;\n }\n\n .loading-overlay .message {\n text-align: center;\n font-family: \"Open Sans\", sans-serif;\n margin-bottom: 1rem;\n color: var(--foreground-color);\n }\n `}connectedCallback(){var e,r;this._progressBar=(e=this.shadowRoot)==null?void 0:e.querySelector(a$5.tag),this._label=(r=this.shadowRoot)==null?void 0:r.querySelector(\"label\"),this.message=a$6.getInstance().get(\"core.view.loading\");}show(){this.removeAttribute(\"hidden\");}hide(){this.setAttribute(\"hidden\",\"\");}};t.tag=d;var a=t;a.register();\n\nexport { a };\n", "import { a } from './chunk-QCZSSQAQ.js';\n\nvar i=class extends a{constructor(r){super({name:\"UnsupportedBrowserError\",message:`This OS / browser has one or more missing features preventing it from working correctly (${r.missingFeatures.join(\", \")})`}),this.data=r;}};\n\nexport { i as a };\n", "import { c, d, b as b$1, a as a$1, e } from './chunk-HIOHGPUS.js';\nimport { a, b } from './chunk-FSQXZE3N.js';\n\nvar Oe=a((ke,ye)=>{(function(h){var u;if(typeof define==\"function\"&&define.amd&&(define(h),u=!0),typeof ke==\"object\"&&(ye.exports=h(),u=!0),!u){var B=window.Cookies,x=window.Cookies=h();x.noConflict=function(){return window.Cookies=B,x};}})(function(){function h(){for(var x=0,y={};x\"u\")){f=h({path:\"/\"},y.defaults,f),typeof f.expires==\"number\"&&(f.expires=new Date(new Date*1+f.expires*864e5)),f.expires=f.expires?f.expires.toUTCString():\"\";try{var o=JSON.stringify(k);/^[\\{\\[]/.test(o)&&(k=o);}catch(i){}k=x.write?x.write(k,S):encodeURIComponent(String(k)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),S=encodeURIComponent(String(S)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\\(\\)]/g,escape);var n=\"\";for(var e in f)f[e]&&(n+=\"; \"+e,f[e]!==!0&&(n+=\"=\"+f[e].split(\";\")[0]));return document.cookie=S+\"=\"+k+n}}function O(S,k){if(!(typeof document>\"u\")){for(var f={},o=document.cookie?document.cookie.split(\"; \"):[],n=0;n{(function(h,u){var B=\"1.0.37\",x=\"\",y=\"?\",T=\"function\",O=\"undefined\",S=\"object\",k=\"string\",f=\"major\",o=\"model\",n=\"name\",e=\"type\",i=\"vendor\",t=\"version\",A=\"architecture\",D=\"console\",b=\"mobile\",d=\"tablet\",C=\"smarttv\",N=\"wearable\",q=\"embedded\",H=500,z=\"Amazon\",P=\"Apple\",a=\"ASUS\",l=\"BlackBerry\",r=\"Browser\",v=\"Chrome\",_=\"Edge\",M=\"Firefox\",U=\"Google\",re=\"Huawei\",J=\"LG\",Q=\"Microsoft\",ae=\"Motorola\",G=\"Opera\",Y=\"Samsung\",se=\"Sharp\",Z=\"Sony\",ee=\"Xiaomi\",ie=\"Zebra\",le=\"Facebook\",ce=\"Chromium OS\",ue=\"Mac OS\",_e=function(w,m){var c={};for(var g in w)m[g]&&m[g].length%2===0?c[g]=m[g].concat(w[g]):c[g]=w[g];return c},K=function(w){for(var m={},c=0;c0?p.length===2?typeof p[1]==T?this[p[0]]=p[1].call(this,I):this[p[0]]=p[1]:p.length===3?typeof p[1]===T&&!(p[1].exec&&p[1].test)?this[p[0]]=I?p[1].call(this,I,p[2]):u:this[p[0]]=I?I.replace(p[1],p[2]):u:p.length===4&&(this[p[0]]=I?p[3].call(this,I.replace(p[1],p[2])):u):this[p]=I||u;c+=2;}},ne=function(w,m){for(var c in m)if(typeof m[c]===S&&m[c].length>0){for(var g=0;g2&&(s[o]=\"iPad\",s[e]=d),s},this.getEngine=function(){var s={};return s[n]=u,s[t]=u,j.call(s,g,R.engine),s},this.getOS=function(){var s={};return s[n]=u,s[t]=u,j.call(s,g,R.os),p&&!s[n]&&L&&L.platform!=\"Unknown\"&&(s[n]=L.platform.replace(/chrome os/i,ce).replace(/macos/i,ue)),s},this.getResult=function(){return {ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return g},this.setUA=function(s){return g=typeof s===k&&s.length>H?oe(s,H):s,this},this.setUA(g),this};E.VERSION=B,E.BROWSER=K([n,t,f]),E.CPU=K([A]),E.DEVICE=K([o,i,e,D,b,C,d,N,q]),E.ENGINE=E.OS=K([n,t]),typeof F!==O?(typeof $!==O&&$.exports&&(F=$.exports=E),F.UAParser=E):typeof define===T&&define.amd?define(function(){return E}):typeof h!==O&&(h.UAParser=E);var W=typeof h!==O&&(h.jQuery||h.Zepto);if(W&&!W.ua){var X=new E;W.ua=X.getResult(),W.ua.get=function(){return X.getUA()},W.ua.set=function(w){X.setUA(w);var m=X.getResult();for(var c in m)W.ua[c]=m[c];};}})(typeof window==\"object\"?window:F);});var Ee=b(Oe(),1),Te=b(Ce(),1);var Ae;(P=>{let h;function u(){return h==null&&(h=new Te.default(navigator.userAgent)),h}P.getUserAgentInfo=u;function B(){var r;if(\"orientation\"in window)return !1;let a=\"(any-pointer: coarse)\",l=(r=window.matchMedia)==null?void 0:r.call(window,a);return navigator.maxTouchPoints===0||(l==null?void 0:l.media)===a&&!(l!=null&&l.matches)}P.isDesktopDevice=B;function x(){return u().getDevice().model===\"iPhone\"}P.isIPhone=x;function y(){let a=u().getOS();return a.name===\"iOS\"&&a.version!=null&&a.version.localeCompare(\"16.3\",void 0,{numeric:!0})>=0}P.isIOSDeviceWithExtendedCameraAccess=y;function T(){return \"document\"in window?window.document.createElement(\"canvas\"):null}P.getCanvas=T;function O(a){return a.name===\"iOS\"&&a.version!=null&&[\"11.2.2\",\"11.2.5\",\"11.2.6\"].includes(a.version)}async function S(){return c()}P.hasSIMDSupport=S;async function k(){return d()}P.hasThreadsSupport=k;function f(a,l,r){let v=a[l[0]];return v==null?!1:l.length===1?typeof v===r:(typeof v==\"function\"||typeof v==\"object\")&&f(v,l.slice(1),r)}function o(){var M;let a=!0,l=null,r=null,v=null,_=null;try{if(l=P.getCanvas(),r=P.getCanvas(),v=l==null?void 0:l.getContext(\"webgl\"),_=r==null?void 0:r.getContext(\"experimental-webgl\"),!f(window,[\"WebGLRenderingContext\"],\"function\")||v==null&&_==null)throw new Error(\"WebGLRenderingContext is not supported\")}catch(U){a=!1;}finally{for(let U of [v,_])typeof(U==null?void 0:U.getExtension)==\"function\"&&((M=U.getExtension(\"WEBGL_lose_context\"))==null||M.loseContext());v=null,_=null,l=null,r=null;}return a}function n(){let a=!0,l=!0,r=new Set;location.protocol.startsWith(\"http\")||r.add(\"httpProtocol\"),f(window,[\"isSecureContext\"],\"boolean\")&&!window.isSecureContext&&r.add(\"secureContext\"),!f(navigator,[\"mediaDevices\",\"getUserMedia\"],\"function\")&&!f(navigator,[\"enumerateDevices\"],\"function\")&&!f(window,[\"MediaStreamTrack\",\"getSources\"],\"function\")&&(r.add(\"mediaDevices\"),a=!1),f(window,[\"Worker\"],\"function\")||(r.add(\"webWorkers\"),a=!1,l=!1),f(window,[\"WebAssembly\"],\"object\")||(r.add(\"webAssembly\"),a=!1,l=!1),f(window,[\"Blob\"],\"function\")||(r.add(\"blob\"),a=!1,l=!1),f(window,[\"URL\",\"createObjectURL\"],\"function\")||(r.add(\"urlObject\"),a=!1,l=!1),f(window,[\"OffscreenCanvas\"],\"function\")||r.add(\"offscreenCanvas\"),o()||r.add(\"webGL\");let v=u().getOS();return O(v)&&(r.add(\"webAssemblyErrorFree\"),a=!1,l=!1),b$1()||r.add(\"sharedArrayBuffer\"),a$1()||r.add(\"crossOriginIsolated\"),{fullSupport:a,scannerSupport:l,missingFeatures:[...r]}}P.checkBrowserCompatibility=n;async function e$1(){return e()}P.checkMultithreadingSupport=e$1;function i(){let a=\"scandit-device-id\",l=\"localStorage\"in globalThis?globalThis.localStorage:void 0;if(!l)return \"\";let r=l.getItem(a);if(r!=null&&r!==\"\")return r;if(r=(0, Ee.get)(a),r!=null&&r!==\"\")return l.setItem(a,r),r;let v=new Uint8Array(20);return crypto.getRandomValues(v),r=[...v].map(_=>{let M=_.toString(16);return M.length===1?`0${M}`:M}).join(\"\"),l.setItem(a,r),r}P.getDeviceId=i;function t(a){return a instanceof HTMLElement||a!=null&&typeof a==\"object\"&&typeof a.tagName==\"string\"}P.isValidHTMLElement=t;function A(){var v,_;let a=u().getOS();if(a.name!==\"iOS\")return !0;let[l,r]=(_=(v=a.version)==null?void 0:v.split(\".\").map(Number))!=null?_:[];return l>14||l===14&&r>=6}P.isSupportedIOSVersion=A;function D(){var a,l;return (l=(a=u().getBrowser().name)==null?void 0:a.toLowerCase().includes(\"safari\"))!=null?l:!1}P.isSafari=D;function b(){var l,r;return /iphone|ipod|ipad/.test((r=(l=u().getDevice().model)==null?void 0:l.toLowerCase())!=null?r:\"\")&&!D()}P.isIosWebView=b;async function d$1(){var l;return ((l=u().getOS().name)==null?void 0:l.toLowerCase())!==\"android\"?!1:u().getUA().includes(\"wv\")?!0:[...(await fetch(document.location.toString(),{method:\"HEAD\"})).headers].some(([r])=>r.toLowerCase()===\"x-requested-with\")}P.isAndroidWebView=d$1;function C(){return u().getOS().name===\"Windows\"}P.isWindows=C;function N(){return u().getBrowser().name===\"Firefox\"}P.isFirefox=N;function q(){if(\"navigator\"in globalThis){for(let a of [\"vibrate\",\"webkitVibrate\",\"msVibrate\",\"mozVibrate\"])if(typeof navigator[a]==\"function\")return navigator[a]}}P.getSupportedVibrationMethod=q;function H(){return q()!=null&&!B()&&!C()&&!N()}P.isVibrationAvailable=H;function z(){return u().getOS().name===\"iOS\"}P.isIOS=z;})(Ae||(Ae={}));\n\nexport { Ae as a };\n", "import { a as a$1 } from './chunk-GPJEB376.js';\nimport { a as a$2 } from './chunk-SP3HSP4K.js';\nimport { a as a$3 } from './chunk-QCZSSQAQ.js';\nimport { a } from './chunk-PSQ6LAQA.js';\n\nvar J=(p=>(p.WorldFacing=\"worldFacing\",p.UserFacing=\"userFacing\",p))(J||{}),Q=(c=>(c[c.ULTRA_HD=0]=\"ULTRA_HD\",c[c.FULL_HD=1]=\"FULL_HD\",c[c.HD=2]=\"HD\",c[c.SD=3]=\"SD\",c[c.NONE=4]=\"NONE\",c))(Q||{}),$=(v=>(v.AUTO=\"auto\",v.FOUR_TO_THREE=\"fourToThree\",v.SIXTEEN_TO_NINE=\"sixteenToNine\",v))($||{}),T;(l=>{let U=new Map([[\"DeviceCaptureError\",\"AbortError\"],[\"NotSupportedError\",\"AbortError\"],[\"ScreenCaptureError\",\"AbortError\"],[\"TabCaptureError\",\"AbortError\"],[\"TypeError\",\"AbortError\"],[\"InvalidStateError\",\"NotAllowedError\"],[\"MediaDeviceFailedDueToShutdown\",\"NotAllowedError\"],[\"MediaDeviceKillSwitchOn\",\"NotAllowedError\"],[\"PermissionDeniedError\",\"NotAllowedError\"],[\"PermissionDismissedError\",\"NotAllowedError\"],[\"DevicesNotFoundError\",\"NotFoundError\"],[\"SourceUnavailableError\",\"NotReadableError\"],[\"TrackStartError\",\"NotReadableError\"],[\"ConstraintNotSatisfiedError\",\"OverconstrainedError\"]]),P=[\"rear\",\"back\",\"r\\xFCck\",\"arri\\xE8re\",\"trasera\",\"tr\\xE1s\",\"traseira\",\"posteriore\",\"\\u540E\\u9762\",\"\\u5F8C\\u9762\",\"\\u80CC\\u9762\",\"\\u540E\\u7F6E\",\"\\u5F8C\\u7F6E\",\"\\u80CC\\u7F6E\",\"\\u0437\\u0430\\u0434\\u043D\\u0435\\u0439\",\"\\u0627\\u0644\\u062E\\u0644\\u0641\\u064A\\u0629\",\"\\uD6C4\",\"arka\",\"achterzijde\",\"\\u0E2B\\u0E25\\u0E31\\u0E07\",\"baksidan\",\"bagside\",\"sau\",\"bak\",\"tylny\",\"takakamera\",\"belakang\",\"\\u05D0\\u05D7\\u05D5\\u05E8\\u05D9\\u05EA\",\"\\u03C0\\u03AF\\u03C3\\u03C9\",\"spate\",\"h\\xE1ts\\xF3\",\"zadn\\xED\",\"darrere\",\"posterior\",\"zadn\\xE1\",\"\\u0437\\u0430\\u0434\\u043D\\u044F\",\"stra\\u017Enja\",\"belakang\",\"\\u092C\\u0948\\u0915\"],p=new Set([\"Desk View Camera\",\"Schreibtischansicht-Kamera\",\"Cam\\xE9ra Desk\\xA0View\",\"C\\xE1mara de Vista Cenital\",\"C\\xE2mara da Vista de Secret\\xE1ria\",\"Fotocamera di Panoramica Scrivania\",\"\\u684C\\u4E0A\\u89C6\\u89D2\\u76F8\\u673A\",\"\\u30C7\\u30B9\\u30AF\\u30D3\\u30E5\\u30FC\\u30AB\\u30E1\\u30E9\",\"\\u041A\\u0430\\u043C\\u0435\\u0440\\u0430 \\u041E\\u0431\\u0437\\u043E\\u0440\\u0430 \\u0441\\u0442\\u043E\\u043B\\u0430\",\"Masa G\\xF6r\\xFCnt\\xFCs\\xFC Kameras\\u0131\",\"Bureauweergave-camera\",\"\\u0643\\u0627\\u0645\\u064A\\u0631\\u0627 \\u0627\\u0644\\u0639\\u0631\\u0636 \\u0627\\u0644\\u0631\\u0623\\u0633\\u064A\",\"\\u0E01\\u0E25\\u0E49\\u0E2D\\u0E07\\u0E14\\u0E39\\u0E14\\u0E49\\u0E32\\u0E19\\u0E2B\\u0E19\\u0E49\\u0E32\\u0E42\\u0E15\\u0E4A\\u0E30\",\"Bordsvisningskamera\",\"Kamera til Visning af skrivebord\",\"Camera Desk View\",\"Bordvisning-kamera\",\"Kamera w\\xA0aplikacji Widok blatu\",\"Ty\\xF6p\\xF6yt\\xE4n\\xE4kym\\xE4n kamera\",\"Kamera Tampilan Meja\",\"\\u05DE\\u05E6\\u05DC\\u05DE\\u05EA \\u05F4\\u05EA\\u05E6\\u05D5\\u05D2\\u05EA \\u05E9\\u05D5\\u05DC\\u05D7\\u05DF\\u05F4\",\"\\u039A\\u03AC\\u03BC\\u03B5\\u03C1\\u03B1 \\u03C4\\u03B7\\u03C2 \\u03A0\\u03C1\\u03BF\\u03B2\\u03BF\\u03BB\\u03AE\\u03C2 \\u03B3\\u03C1\\u03B1\\u03C6\\u03B5\\u03AF\\u03BF\\u03C5\",\"Camer\\u0103 Vizualizare birou\",\"\\xCDr\\xF3asztal n\\xE9zet kamer\\xE1ja\",\"Stoln\\xED kamera\",\"C\\xE0mera de l\\u2019app Vista de l\\u2019Escriptori\"]),v=new Set([\"Front Camera\",\"Frontkamera\",\"Appareil photo avant\",\"C\\xE1mara frontal\",\"C\\xE2mera Frontal\",\"C\\xE2mara frontal\",\"Fotocamera (anteriore)\",\"\\u524D\\u7F6E\\u76F8\\u673A\",\"\\u524D\\u7F6E\\u76F8\\u6A5F\",\"\\u524D\\u9762\\u30AB\\u30E1\\u30E9\",\"\\u041A\\u0430\\u043C\\u0435\\u0440\\u0430 \\u043D\\u0430 \\u043F\\u0435\\u0440\\u0435\\u0434\\u043D\\u0435\\u0439 \\u043F\\u0430\\u043D\\u0435\\u043B\\u0438\",\"\\xD6n Kamera\",\"Camera aan voorzijde\",\"\\u0627\\u0644\\u0643\\u0627\\u0645\\u064A\\u0631\\u0627 \\u0627\\u0644\\u0623\\u0645\\u0627\\u0645\\u064A\\u0629\",\"\\u0E01\\u0E25\\u0E49\\u0E2D\\u0E07\\u0E14\\u0E49\\u0E32\\u0E19\\u0E2B\\u0E19\\u0E49\\u0E32\",\"Kamera p\\xE5 framsidan\",\"Forsidekamera\",\"Camera m\\u1EB7t tr\\u01B0\\u1EDBc\",\"Kamera foran\",\"Przedni aparat\",\"Etukamera\",\"Kamera Depan\",\"\\u05DE\\u05E6\\u05DC\\u05DE\\u05D4 \\u05E7\\u05D3\\u05DE\\u05D9\\u05EA\",\"\\u039C\\u03C0\\u03C1\\u03BF\\u03C3\\u03C4\\u03B9\\u03BD\\u03AE \\u03BA\\u03AC\\u03BC\\u03B5\\u03C1\\u03B1\",\"Camer\\u0103 fa\\u021B\\u0103\",\"El\\xFCls\\u0151 kamera\",\"P\\u0159edn\\xED fotoapar\\xE1t\",\"C\\xE0mera frontal\",\"Predn\\xE1 kamera\",\"\\u041F\\u0435\\u0440\\u0435\\u0434\\u043D\\u044F \\u043A\\u0430\\u043C\\u0435\\u0440\\u0430\",\"Prednja kamera\",\"Kamera Depan\",\"\\u092B\\u093C\\u094D\\u0930\\u0902\\u091F \\u0915\\u0948\\u092E\\u0930\\u093E\"]),x=new Set([\"Back Camera\",\"R\\xFCckkamera\",\"Cam\\xE9ra arri\\xE8re\",\"C\\xE1mara trasera\",\"C\\xE2mera Traseira\",\"C\\xE2mara traseira\",\"Fotocamera (posteriore)\",\"\\u540E\\u7F6E\\u76F8\\u673A\",\"\\u5F8C\\u7F6E\\u76F8\\u6A5F\",\"\\u80CC\\u9762\\u30AB\\u30E1\\u30E9\",\"\\u041A\\u0430\\u043C\\u0435\\u0440\\u0430 \\u043D\\u0430 \\u0437\\u0430\\u0434\\u043D\\u0435\\u0439 \\u043F\\u0430\\u043D\\u0435\\u043B\\u0438\",\"Arka Kamera\",\"Camera aan achterzijde\",\"\\u0627\\u0644\\u0643\\u0627\\u0645\\u064A\\u0631\\u0627 \\u0627\\u0644\\u062E\\u0644\\u0641\\u064A\\u0629\",\"\\u0E01\\u0E25\\u0E49\\u0E2D\\u0E07\\u0E14\\u0E49\\u0E32\\u0E19\\u0E2B\\u0E25\\u0E31\\u0E07\",\"Kamera p\\xE5 baksidan\",\"Bagsidekamera\",\"Camera m\\u1EB7t sau\",\"Kamera bak\",\"Tylny aparat\",\"Takakamera\",\"Kamera Belakang\",\"\\u05DE\\u05E6\\u05DC\\u05DE\\u05D4 \\u05D0\\u05D7\\u05D5\\u05E8\\u05D9\\u05EA\",\"\\u03A0\\u03AF\\u03C3\\u03C9 \\u03BA\\u03AC\\u03BC\\u03B5\\u03C1\\u03B1\",\"Camer\\u0103 spate\",\"H\\xE1ts\\xF3 kamera\",\"Zadn\\xED fotoapar\\xE1t\",\"C\\xE0mera posterior\",\"Zadn\\xE1 kamera\",\"\\u0417\\u0430\\u0434\\u043D\\u044F \\u043A\\u0430\\u043C\\u0435\\u0440\\u0430\",\"Stra\\u017Enja kamera\",\"Kamera Belakang\",\"\\u092C\\u0948\\u0915 \\u0915\\u0948\\u092E\\u0930\\u093E\"]),c=new Set([\"Back Dual Wide Camera\",\"R\\xFCckseitige Dual-Weitwinkelkamera\",\"Double appareil photo grand angle arri\\xE8re\",\"C\\xE1mara trasera dual con gran angular\",\"C\\xE2mera Dupla Grande-Angular Traseira\",\"C\\xE2mara grande angular dupla traseira\",\"Fotocamera doppia con grandangolo (posteriore)\",\"\\u540E\\u7F6E\\u53CC\\u5E7F\\u89D2\\u955C\\u5934\",\"\\u5F8C\\u7F6E\\u96D9\\u5EE3\\u89D2\\u76F8\\u6A5F\",\"\\u80CC\\u9762\\u30C7\\u30E5\\u30A2\\u30EB\\u5E83\\u89D2\\u30AB\\u30E1\\u30E9\",\"\\u0417\\u0430\\u0434\\u043D\\u044F\\u044F \\u0434\\u0432\\u043E\\u0439\\u043D\\u0430\\u044F \\u0448\\u0438\\u0440\\u043E\\u043A\\u043E\\u0443\\u0433\\u043E\\u043B\\u044C\\u043D\\u0430\\u044F \\u043A\\u0430\\u043C\\u0435\\u0440\\u0430\",\"\\xC7ift Geni\\u015F Kamera Arka Y\\xFCz\\xFC\",\"\\u0643\\u0627\\u0645\\u064A\\u0631\\u0627 \\u062E\\u0644\\u0641\\u064A\\u0629 \\u0645\\u0632\\u062F\\u0648\\u062C\\u0629 \\u0639\\u0631\\u064A\\u0636\\u0629\",\"\\u0E01\\u0E25\\u0E49\\u0E2D\\u0E07\\u0E04\\u0E39\\u0E48\\u0E14\\u0E49\\u0E32\\u0E19\\u0E2B\\u0E25\\u0E31\\u0E07\\u0E21\\u0E38\\u0E21\\u0E01\\u0E27\\u0E49\\u0E32\\u0E07\",\"Dubbel vidvinkelkamera p\\xE5 baksidan\",\"Camera k\\xE9p r\\u1ED9ng m\\u1EB7t sau\",\"Dobbelt vidvinkelkamera bak\",\"Tylny dwuobiektywowy aparat szerokok\\u0105tny\",\"Laajakulmainen kaksoistakakamera\",\"Kamera Lebar Belakang Ganda\",\"\\u05DE\\u05E6\\u05DC\\u05DE\\u05D4 \\u05DB\\u05E4\\u05D5\\u05DC\\u05D4 \\u05E8\\u05D7\\u05D1\\u05D4 \\u05D0\\u05D7\\u05D5\\u05E8\\u05D9\\u05EA\",\"\\u03A0\\u03AF\\u03C3\\u03C9 \\u03B4\\u03B9\\u03C0\\u03BB\\u03AE \\u03B5\\u03C5\\u03C1\\u03B5\\u03AF\\u03B1 \\u03BA\\u03AC\\u03BC\\u03B5\\u03C1\\u03B1\",\"Camer\\u0103 dubl\\u0103 cu obiectiv superangular spate\",\"H\\xE1ts\\xF3, kett\\u0151s, sz\\xE9les l\\xE1t\\xF3sz\\xF6g\\u0171 kamera\",\"Zadn\\xED du\\xE1ln\\xED \\u0161iroko\\xFAhl\\xFD fotoapar\\xE1t\",\"C\\xE0mera dual posterior amb gran angular\",\"Zadn\\xE1 du\\xE1lna \\u0161irokouhl\\xE1 kamera\",\"\\u0417\\u0430\\u0434\\u043D\\u044F \\u0437\\u0434\\u0432\\u043E\\u0454\\u043D\\u0430 \\u0448\\u0438\\u0440\\u043E\\u043A\\u043E\\u043A\\u0443\\u0442\\u043D\\u0430 \\u043A\\u0430\\u043C\\u0435\\u0440\\u0430\",\"Stra\\u017Enja dvostruka \\u0161iroka kamera\",\"Dwikamera Lebar Belakang\",\"\\u092C\\u0948\\u0915 \\u0921\\u094D\\u092F\\u0941\\u0905\\u0932 \\u0935\\u093E\\u0907\\u0921 \\u0915\\u0948\\u092E\\u0930\\u093E\"]),O=new Set([\"Back Ultra Wide Camera\",\"R\\xFCckseitige Ultra-Weitwinkelkamera\",\"Appareil photo ultra grand angle arri\\xE8re\",\"C\\xE1mara trasera con ultra gran angular\",\"C\\xE2mera Ultra-Angular Traseira\",\"C\\xE2mara ultra grande angular traseira\",\"Fotocamera con ultra-grandangolo (posteriore)\",\"\\u540E\\u7F6E\\u8D85\\u5E7F\\u89D2\\u76F8\\u673A\",\"\\u5F8C\\u7F6E\\u8D85\\u5EE3\\u89D2\\u76F8\\u6A5F\",\"\\u80CC\\u9762\\u8D85\\u5E83\\u89D2\\u30AB\\u30E1\\u30E9\",\"\\u0417\\u0430\\u0434\\u043D\\u044F\\u044F \\u0441\\u0432\\u0435\\u0440\\u0445\\u0448\\u0438\\u0440\\u043E\\u043A\\u043E\\u0443\\u0433\\u043E\\u043B\\u044C\\u043D\\u0430\\u044F \\u043A\\u0430\\u043C\\u0435\\u0440\\u0430\",\"Ultra Geni\\u015F Kamera Arka Y\\xFCz\\xFC\",\"Ultrabrede camera aan achterzijde\",\"\\u0643\\u0627\\u0645\\u064A\\u0631\\u0627 \\u062E\\u0644\\u0641\\u064A\\u0629 \\u0639\\u0631\\u064A\\u0636\\u0629 \\u062C\\u062F\\u064B\\u0627\",\"\\u0E01\\u0E25\\u0E49\\u0E2D\\u0E07\\u0E14\\u0E49\\u0E32\\u0E19\\u0E2B\\u0E25\\u0E31\\u0E07\\u0E21\\u0E38\\u0E21\\u0E01\\u0E27\\u0E49\\u0E32\\u0E07\\u0E2D\\u0E31\\u0E25\\u0E15\\u0E23\\u0E49\\u0E32\",\"Ultravidvinkelkamera p\\xE5 baksidan\",\"Ultravidvinkelkameraet p\\xE5 bagsiden\",\"Camera c\\u1EF1c r\\u1ED9ng m\\u1EB7t sau\",\"Ultravidvinkelkamera bak\",\"Tylny aparat ultraszerokok\\u0105tny\",\"Ultralaajakulmainen takakamera\",\"Kamera Ultra Lebar Belakang\",\"\\u05DE\\u05E6\\u05DC\\u05DE\\u05D4 \\u05D0\\u05D5\\u05DC\\u05D8\\u05E8\\u05D4 \\u05E8\\u05D7\\u05D1\\u05D4 \\u05D0\\u05D7\\u05D5\\u05E8\\u05D9\\u05EA\",\"\\u03A0\\u03AF\\u03C3\\u03C9 \\u03C5\\u03C0\\u03B5\\u03C1\\u03B5\\u03C5\\u03C1\\u03B5\\u03AF\\u03B1 \\u03BA\\u03AC\\u03BC\\u03B5\\u03C1\\u03B1\",\"Camer\\u0103 cu obiectiv ultra\\u2011superangular spate\",\"H\\xE1ts\\xF3, ultrasz\\xE9les l\\xE1t\\xF3sz\\xF6g\\u0171 kamera\",\"Zadn\\xED ultra \\u0161iroko\\xFAhl\\xFD fotoapar\\xE1t\",\"C\\xE0mera posterior amb ultra gran angular\",\"Zadn\\xE1 ultra\\u0161irokouhl\\xE1 kamera\",\"\\u0417\\u0430\\u0434\\u043D\\u044F \\u043D\\u0430\\u0434\\u0448\\u0438\\u0440\\u043E\\u043A\\u043E\\u043A\\u0443\\u0442\\u043D\\u0430 \\u043A\\u0430\\u043C\\u0435\\u0440\\u0430\",\"Stra\\u017Enja ultra \\u0161iroka kamera\",\"Kamera Ultralebar Belakang\",\"\\u092C\\u0948\\u0915 \\u0905\\u0932\\u094D\\u091F\\u094D\\u0930\\u093E \\u0935\\u093E\\u0907\\u0921 \\u0915\\u0948\\u092E\\u0930\\u093E\"]),d,D=!1;l.mainCameraForPositionOverridesOnDesktop=new Map,l.deviceIdToCameraObjects=new Map,l.inaccessibleDeviceIds=new Set;function ee(e,i){l.mainCameraForPositionOverridesOnDesktop.set(e,i);}l.setMainCameraForPositionOverridesOnDesktop=ee;function ae(){l.mainCameraForPositionOverridesOnDesktop.clear();}l.clearMainCameraForPositionOverridesOnDesktop=ae;function F(){return navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices)}function N(){if(typeof navigator.enumerateDevices==\"function\")return navigator.enumerateDevices.bind(navigator);if(typeof navigator.mediaDevices==\"object\"&&typeof navigator.mediaDevices.enumerateDevices==\"function\")return navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)}function S(){D=!0;}function B(e){let i=e.toLowerCase();return P.some(a=>i.includes(a))}function w(e){return v.has(e)}l.isIOSFrontCameraLabel=w;function E(e){return x.has(e)}l.isIOSBackCameraLabel=E;function M(e){return c.has(e)}l.isIOSBackDualWideCameraLabel=M;function K(e){return O.has(e)}l.isIOSUltraWideBackCameraLabel=K;function I(e){var a;let i=e.message===\"Invalid constraint\"?\"OverconstrainedError\":(a=U.get(e.name))!=null?a:e.name;Object.defineProperty(e,\"name\",{value:i});}function W(e){if(e.length===0)return {areSomeCameraLabelsFilled:!1,areAllCameraLabelsFilled:!1,areAllCameraLabelsUnfilled:!1};let i=e.every(r=>r.label!==\"\"),a=e.every(r=>r.label===\"\");return {areSomeCameraLabelsFilled:!a&&!i,areAllCameraLabelsFilled:i,areAllCameraLabelsUnfilled:a}}function R(e,i){var a;return (a=l.mainCameraForPositionOverridesOnDesktop.get(i))!=null?a:e.find(n=>n.position===i)}function j(e,i){if(i===\"worldFacing\"){let a=e.find(r=>M(r.label));if(a!=null)return a;let n=e.find(r=>E(r.label));if(n!=null)return n}else {let a=e.find(n=>w(n.label));if(a!=null)return a}}function z(e,i){let{areSomeCameraLabelsFilled:a$1,areAllCameraLabelsUnfilled:n}=W(e);if(n)return e[i===\"userFacing\"?0:e.length-1];if(a$1){let r=e.filter(t=>t.position===i);return r.length===1?r[0]:r[i===\"userFacing\"?0:r.length-1]}if(a.getUserAgentInfo().getOS().name===\"iOS\"){let r=j(e,i);if(r)return r}return e.filter(r=>r.position===i).sort((r,t)=>r.label.localeCompare(t.label))[0]}function re(e,i){return a.isDesktopDevice()?R(e,i):z(e,i)}l.getMainCameraForPosition=re;function k(e,i){return e.unshift(e.splice(i,1)[0])}function ie(e,i){function a$1(t,o){let s=l.mainCameraForPositionOverridesOnDesktop.get(o);return s!=null&&t.includes(s)&&(t=t.filter(f=>f!==s),t.unshift(s)),t}let n=e.filter(t=>t.position===\"userFacing\"),r=e.filter(t=>t.position===\"worldFacing\");return a.isDesktopDevice()?(n=a$1(n,\"userFacing\"),r=a$1(r,\"worldFacing\")):e.every(t=>t.label===\"\")?r.reverse():(n.sort((t,o)=>t.label.localeCompare(o.label)),r.sort((t,o)=>t.label.localeCompare(o.label)),a.getUserAgentInfo().getOS().name===\"iOS\"&&(n.some((t,o)=>w(t.label)&&k(n,o)>=0),r.some((t,o)=>K(t.label)&&k(r,o)>=0),r.some((t,o)=>M(t.label)&&k(r,o)>=0)||r.some((t,o)=>E(t.label)&&k(r,o)>=0))),i===\"userFacing\"?[...n,...r]:[...r,...n]}l.sortCamerasForCameraPosition=ie;function _(e,i){let a=e.getVideoTracks();if(a.length>0){let n=a[0],r;typeof n.getSettings==\"function\"&&(r=n.getSettings(),r.facingMode!=null&&r.facingMode.length>0&&(i.position=r.facingMode===\"environment\"?\"worldFacing\":\"userFacing\"));let{label:t=\"\"}=n;t.length>0&&(i.label=t);}}l.adjustCameraFromMediaStream=_;function H(e,i,a$1){if(l.deviceIdToCameraObjects.has(e.deviceId))return l.deviceIdToCameraObjects.get(e.deviceId);let{label:n=\"\",deviceId:r}=e,t;return !a.isDesktopDevice()&&a$1.every(o=>o.label===\"\"&&!l.deviceIdToCameraObjects.has(o.deviceId))?t=a$1.length===1||i+1<=Math.floor(a$1.length/2)?\"userFacing\":\"worldFacing\":t=B(n)?\"worldFacing\":\"userFacing\",{position:t,label:n,deviceId:r}}function A(e){let i=e.map((a,n,r)=>H(a,n,r)).map(a=>(a.deviceId!==\"\"&&l.deviceIdToCameraObjects.set(a.deviceId,a),a)).filter(a=>!/\\b(?:ir|infrared)\\b/i.test(a.label)).filter(a=>!p.has(a.label)).filter(a=>!l.inaccessibleDeviceIds.has(a.deviceId));if(!a.isDesktopDevice()&&i.length>1&&!i.some(a=>a.position===\"worldFacing\")){let a=i.length-1,n=i.map(r=>{let t=/\\b(\\d+)mp?\\b/i.exec(r.label);return t!=null?Number.parseInt(t[1],10):Number.NaN});n.some(r=>Number.isNaN(r))||(a=n.lastIndexOf(Math.max(...n))),i[a].position=\"worldFacing\";}return i}async function V(){if(d!=null&&d.length>0&&d.every(e=>e.label===\"\"&&!l.deviceIdToCameraObjects.has(e.deviceId)))try{return await F()({video:!0,audio:!1})}catch(e){}}function G(e,i){var a,n;if(i.length>0&&e.length===i.length&&!i.every((r,t)=>e[t].deviceId===r.deviceId)){let r={};for(let[t,o]of e.entries()){let s=l.deviceIdToCameraObjects.get(o.deviceId);if(s==null||s.label!==((n=(a=i[t])==null?void 0:a.label)!=null?n:\"\"))continue;let f=i[t].deviceId;r[s.deviceId]=f,l.inaccessibleDeviceIds.has(s.deviceId)&&l.inaccessibleDeviceIds.add(f),s.deviceId=f,l.deviceIdToCameraObjects.set(f,s);}a$2.log(a$2.Level.Debug,\"Detected updated camera deviceId information and updated it accordingly\",r);}}function Z(){typeof navigator.mediaDevices.addEventListener==\"function\"?navigator.mediaDevices.addEventListener(\"devicechange\",S):navigator.mediaDevices.ondevicechange=S;}async function y(){let e,i=N();if(i)e=await i();else throw new a$1({fullSupport:!1,scannerSupport:!0,missingFeatures:[\"mediaDevices\"]});return e.filter(a=>a.kind===\"videoinput\")}async function te(e=!1,i=!1){var r;let a$3=a.checkBrowserCompatibility();if(!a$3.fullSupport)throw new a$1(a$3);if(Z(),d==null||e||D){D=!1;let t,o=d!=null?d:[];d=[];try{d=await y(),i||(t=await V(),t!=null&&(d=await y())),a$2.log(a$2.Level.Debug,\"Camera list (devices):\",...d),d.length>0&&d.every(s=>s.deviceId===\"\")&&a$2.log(a$2.Level.Debug,\"Incomplete camera information listed due to user permission denial, cameras will not be accessible\"),G(o,d);}catch(s){throw I(s),s}finally{for(let s of (r=t==null?void 0:t.getVideoTracks())!=null?r:[])s.stop();}}let n=A(d);return a$2.log(a$2.Level.Debug,\"Camera list (cameras): \",...n),[...n]}l.getCameras=te;async function Y(e){return a$2.log(a$2.Level.Debug,\"Attempt to access camera (parameters):\",e.video),new Promise((i,a)=>{window.setTimeout(()=>{let n=F()(e);if(n==null){a(new a$3({name:\"AbortError\",message:\"Cannot get stream from getUserMedia function.\"}));return}i(n);},0);})}function X(e,i){let a={resizeMode:\"none\"};switch(e){case 0:return {...a,width:{min:2880,ideal:i===\"fourToThree\"?2880:3840,max:4096},height:{min:1800,ideal:2160,max:2400}};case 1:return {...a,width:{min:1440,ideal:i===\"fourToThree\"?1440:1920,max:2160},height:{min:900,ideal:1080,max:1440}};case 2:return {...a,width:{min:960,ideal:i===\"fourToThree\"?960:1280,max:1440},height:{min:480,ideal:720,max:960}};case 3:return {...a,width:{min:640,ideal:640,max:800},height:{min:360,ideal:i===\"fourToThree\"?480:360,max:640}};default:return {}}}l.getUserMediaVideoParameters=X;function q(e){e.deviceId!==\"\"&&(a$2.log(a$2.Level.Debug,\"Camera marked to be inaccessible:\",e),l.inaccessibleDeviceIds.add(e.deviceId));}l.markCameraAsInaccessible=q;async function ne(e,i,a){a$2.log(a$2.Level.Debug,\"Attempt to access camera (camera):\",e);let n={audio:!1,video:X(i,a)};e.deviceId===\"\"?n.video.facingMode={ideal:e.position===\"worldFacing\"?\"environment\":\"user\"}:n.video.deviceId={exact:e.deviceId};try{let r=await Y(n);return _(r,e),r}catch(r){throw I(r),[\"OverconstrainedError\",\"NotReadableError\",\"NotAllowedError\"].includes(r.name)||q(e),r}}l.accessCameraStream=ne;})(T||(T={}));\n\nexport { J as a, Q as b, $ as c, T as d };\n", "import { d } from './chunk-SK45SCLY.js';\n\nvar i;(m=>{async function n(o,t){return d.getCameras(o!=null?o:!1,t!=null?t:!1)}m.getCameras=n;})(i||(i={}));\n\nexport { i as a };\n", "import { a } from './chunk-SP3HSP4K.js';\n\nfunction d(r,o,t){let e=r.createProgram();if(!e)throw new Error(\"Cannot create webgl program\");return r.attachShader(e,o),r.attachShader(e,t),r.linkProgram(e),r.getProgramParameter(e,r.LINK_STATUS)?e:(a.log(a.Level.Error,\"Program linking error:\",r.getProgramInfoLog(e)),r.deleteProgram(e),null)}function h(r,o,t){let e=r.createShader(o);if(!e)throw new Error(\"Cannot create a shader\");return r.shaderSource(e,t),r.compileShader(e),r.getShaderParameter(e,r.COMPILE_STATUS)?e:(a.log(a.Level.Error,\"Shader compilation error:\",r.getShaderInfoLog(e)),r.deleteShader(e),null)}\n\nexport { d as a, h as b };\n", "var o=class{constructor(a,e){var r,t;this._contextWebGL=a,this._maxPoolCapacity=(r=e==null?void 0:e.maxPoolCapacity)!=null?r:2,this._minPoolCapacity=(t=e==null?void 0:e.minPoolCapacity)!=null?t:1;}recycle(a){var e;(e=this._framePool)==null||e.push(a);}};\n\nexport { o as a };\n", "var r=class{constructor(e){this.items=[];if(e.lowWaterMark>=e.capacity)throw new Error(\"Invalid Watermark options: lowWaterMark must be less than capacity\");this.capacity=e.capacity,this.lowWaterMark=e.lowWaterMark,this.createItem=e.createItem;for(let t=0;tnew Uint8ClampedArray(this._frameSize)}));}initShaderProgram(){let t=b(this._webglContext,this._webglContext.VERTEX_SHADER,m),e=b(this._webglContext,this._webglContext.FRAGMENT_SHADER,w);if(!t||!e)throw new Error(\"Shaders cannot be created\");this._shaderProgram=a$2(this._webglContext,t,e),this._webglContext.useProgram(this._shaderProgram);}initBuffers(){this._positionBuffer=this._webglContext.createBuffer(),this._webglContext.bindBuffer(this._webglContext.ARRAY_BUFFER,this._positionBuffer),this._webglContext.bufferData(this._webglContext.ARRAY_BUFFER,this._positions,this._webglContext.STATIC_DRAW);let t=this._webglContext.getAttribLocation(this._shaderProgram,\"a_position\");this._webglContext.enableVertexAttribArray(t),this._webglContext.bindBuffer(this._webglContext.ARRAY_BUFFER,this._positionBuffer),this._webglContext.vertexAttribPointer(t,2,this._webglContext.FLOAT,!1,0,0);}initTexture(){this._texture=this._webglContext.createTexture(),this._webglContext.bindTexture(this._webglContext.TEXTURE_2D,this._texture),this._webglContext.texParameteri(this._webglContext.TEXTURE_2D,this._webglContext.TEXTURE_WRAP_S,this._webglContext.CLAMP_TO_EDGE),this._webglContext.texParameteri(this._webglContext.TEXTURE_2D,this._webglContext.TEXTURE_WRAP_T,this._webglContext.CLAMP_TO_EDGE),this._webglContext.texParameteri(this._webglContext.TEXTURE_2D,this._webglContext.TEXTURE_MIN_FILTER,this._webglContext.LINEAR),this._webglContext.texParameteri(this._webglContext.TEXTURE_2D,this._webglContext.TEXTURE_MAG_FILTER,this._webglContext.LINEAR);let t=this._webglContext.getUniformLocation(this._shaderProgram,\"u_texture\");this._webglContext.uniform1i(t,0);}};\n\nexport { x as a };\n", "import { a } from './chunk-MW5PTAU7.js';\nimport { a as a$2 } from './chunk-QHBIT2WY.js';\nimport { a as a$1 } from './chunk-SP3HSP4K.js';\n\nvar s=(e=>(e.RGBA=\"RGBA\",e.GRAYSCALE=\"GRAYSCALE\",e))(s||{}),n=class extends a{constructor(){super(...arguments);this.colorType=\"RGBA\";}get _initialized(){return this._texture!=null&&this._framebuffer!=null}readFromSource(e){this._initialized||this.setup(),this.updateFrameSizeIfNeeded();let i=this._framePool.pop();return this._contextWebGL.texImage2D(this._contextWebGL.TEXTURE_2D,0,this._contextWebGL.RGBA,this._contextWebGL.RGBA,this._contextWebGL.UNSIGNED_BYTE,e),this._contextWebGL.readPixels(0,0,this._contextWebGL.drawingBufferWidth,this._contextWebGL.drawingBufferHeight,this._contextWebGL.RGBA,this._contextWebGL.UNSIGNED_BYTE,i),{width:this._contextWebGL.drawingBufferWidth,height:this._contextWebGL.drawingBufferHeight,data:i,colorType:this.colorType}}setup(){this._texture=this._contextWebGL.createTexture(),this._texture==null&&a$1.log(a$1.Level.Warn,\"Could not create texture from WebGLRenderingContext\"),this._contextWebGL.bindTexture(this._contextWebGL.TEXTURE_2D,this._texture),this._framebuffer=this._contextWebGL.createFramebuffer(),this._framebuffer==null&&a$1.log(a$1.Level.Warn,\"Could not create frameBuffer from WebGLRenderingContext\"),this._contextWebGL.bindFramebuffer(this._contextWebGL.FRAMEBUFFER,this._framebuffer),this._contextWebGL.framebufferTexture2D(this._contextWebGL.FRAMEBUFFER,this._contextWebGL.COLOR_ATTACHMENT0,this._contextWebGL.TEXTURE_2D,this._texture,0),this._contextWebGL.texParameteri(this._contextWebGL.TEXTURE_2D,this._contextWebGL.TEXTURE_WRAP_S,this._contextWebGL.CLAMP_TO_EDGE),this._contextWebGL.texParameteri(this._contextWebGL.TEXTURE_2D,this._contextWebGL.TEXTURE_WRAP_T,this._contextWebGL.CLAMP_TO_EDGE),this._contextWebGL.texParameteri(this._contextWebGL.TEXTURE_2D,this._contextWebGL.TEXTURE_MIN_FILTER,this._contextWebGL.NEAREST),this._contextWebGL.texParameteri(this._contextWebGL.TEXTURE_2D,this._contextWebGL.TEXTURE_MAG_FILTER,this._contextWebGL.NEAREST);}dispose(){var e;this._texture!=null&&(this._contextWebGL.deleteTexture(this._texture),this._texture=null),this._framebuffer!=null&&(this._contextWebGL.deleteFramebuffer(this._framebuffer),this._framebuffer=null),(e=this._framePool)==null||e.empty();}updateFrameSizeIfNeeded(){var o;let{drawingBufferWidth:e,drawingBufferHeight:i}=this._contextWebGL,r=e*i*4;this._frameSize!==r&&(this._frameSize=r,(o=this._framePool)==null||o.empty(),this._framePool=new a$2({capacity:this._maxPoolCapacity,lowWaterMark:this._minPoolCapacity,createItem:()=>new Uint8ClampedArray(this._frameSize)}));}};\n\nexport { s as a, n as b };\n", "import { a as a$1 } from './chunk-R6E4CT22.js';\nimport { a as a$5 } from './chunk-FSH6LHLS.js';\nimport { b as b$1 } from './chunk-SD5C67QU.js';\nimport { b } from './chunk-FTD535WI.js';\nimport { a } from './chunk-JKL2W65E.js';\nimport { d } from './chunk-SK45SCLY.js';\nimport { a as a$3 } from './chunk-SP3HSP4K.js';\nimport { a as a$4 } from './chunk-QCZSSQAQ.js';\nimport { a as a$2 } from './chunk-PSQ6LAQA.js';\n\nvar w=(r=>(r.CONTINUOUS=\"continuous\",r.MANUAL=\"manual\",r.NONE=\"none\",r.SINGLE_SHOT=\"single-shot\",r))(w||{}),R=(s=>(s[s.ULTRA_HD=0]=\"ULTRA_HD\",s[s.FULL_HD=1]=\"FULL_HD\",s[s.HD=2]=\"HD\",s[s.SD=3]=\"SD\",s[s.NONE=4]=\"NONE\",s))(R||{}),L=(t=>(t.CAMERA_PROPERTIES=\"cameraProperties\",t.CAMERA_ACCESS_ERROR=\"cameraAccessError\",t))(L||{}),n=class n{constructor(){this.checkCameraVideoStreamAccessIfVisibleListener=this.checkCameraVideoStreamAccessIfVisible.bind(this);this.handleWebGLContextLostListener=this.handleWebGLContextLost.bind(this);this.listeners=new Map;this.mirrorImageOverrides=new Map;this.postStreamInitializationListener=this.postStreamInitialization.bind(this);this.triggerManualFocusListener=this.triggerManualFocus.bind(this);this.triggerZoomMoveListener=this.triggerZoomMove.bind(this);this.triggerZoomStartListener=this.triggerZoomStart.bind(this);this.videoResizeListener=a$1(this.handleVideoResize.bind(this),500);this.videoTrackEndedListener=this.videoTrackEndedRecovery.bind(this);this.videoTrackMuteListener=this.videoTrackMuteRecovery.bind(this);this._synchronousFrameHandling=!1;this._glFrameReaders={GRAYSCALE:null,RGBA:null};this._frameReaderType=\"RGBA\";this.cameraPosition=\"worldFacing\",this.gui={isCameraRecoveryVisible:()=>!1,setCameraRecoveryVisible:()=>{}},this.isWebGLSupported=!a$2.checkBrowserCompatibility().missingFeatures.includes(\"webGL\"),this.videoElement=document.createElement(\"video\"),this.canvas=document.createElement(\"canvas\"),this.canvas.addEventListener(\"webglcontextlost\",this.handleWebGLContextLostListener);}get mediaStream(){return this._mediaStream}set mediaStream(e){this._mediaStream=e,e&&(this.mediaTrackCapabilitiesPromise=new Promise(t=>{this.mediaTrackCapabilitiesPromiseResolver=t;}));}get synchronousFrameHandling(){return this._synchronousFrameHandling}get canvas2dContext(){return this._canvas2dContext||(this._canvas2dContext=this.canvas.getContext(\"2d\",{willReadFrequently:!0}),this._canvas2dContext==null&&a$3.log(a$3.Level.Warn,\"Unable to get 2d canvas context\"),this.handleVideoResize()),this._canvas2dContext}get canvasWebGLContext(){var e;if(!this._canvas2dContext&&!this._canvasWebGLContext){if(!this.isWebGLSupported){a$3.log(a$3.Level.Warn,\"WebGL context not supported, falling back to 2d canvas context. This may impact the scanning performance.\");return}let t=(e=this.canvas.getContext(\"webgl\",{alpha:!1,antialias:!1}))!=null?e:this.canvas.getContext(\"experimental-webgl\",{alpha:!1,antialias:!1});t!=null&&(this._canvasWebGLContext=t,this.handleVideoResize());}return this._canvasWebGLContext}static instance(){return n._instance==null&&(n._instance=new n),n._instance}recycle(e){var t;(t=this.getFrameReader())==null||t.recycle(e);}getCurrentFrame(){var e;return (e=this._glFrameReaders.RGBA)==null?void 0:e.readFromSource(this.videoElement)}requestVideoFrame(e){return \"requestVideoFrameCallback\"in HTMLVideoElement.prototype?this.videoElement.requestVideoFrameCallback(e):requestAnimationFrame(e)}cancelVideoFrame(e){if(\"cancelVideoFrameCallback\"in HTMLVideoElement.prototype){this.videoElement.cancelVideoFrameCallback(e);return}cancelAnimationFrame(e);}addListener(e,t){var r;let i=(r=this.listeners.get(e))!=null?r:[];i.includes(t)||this.listeners.set(e,[...i,t]);}async applyCameraSettings(e){if(this.selectedCameraSettings=e,this.activeCamera==null)throw new a$4(n.noCameraErrorParameters);return this.initializeCameraWithSettings(this.activeCamera,e)}captureImage(){var e;if(((e=this.mediaStream)==null?void 0:e.active)!=null){if(this.canvasWebGLContext!=null)return this.captureImageForWebGLContext();if(this.canvas2dContext!=null)return this.captureImageFor2dContext()}return null}async initializeCameraWithSettings(e,t){if(this.cameraInitializationPromise&&await this.cameraInitializationPromise,e==null)throw new a$4(n.noCameraErrorParameters);return this.setSelectedCamera(e),this.selectedCameraSettings=t,this.activeCameraSettings=t,this.cameraInitializationPromise=this.initializeCameraAndCheckUpdatedSettings(e),this.cameraInitializationPromise}isMirrorImageEnabled(){if(this.selectedCamera&&this.activeCamera){let e=this.mirrorImageOverrides.get(this.activeCamera);return e!=null?e:this.activeCamera.position===\"userFacing\"}return !1}isPinchToZoomEnabled(){return this.pinchToZoomEnabled}isTapToFocusEnabled(){return this.tapToFocusEnabled}async isTorchAvailable(){var e;return this.mediaStream?(await this.waitForCapabilities(),((e=this.mediaTrackCapabilities)==null?void 0:e.torch)===!0):!1}async playVideo(){return new Promise(e=>{this._canvas2dContext&&this._canvas2dContext.clearRect(0,0,this.canvas.width,this.canvas.height);let t=this.videoElement.play();t==null?e():t.then(e).catch(()=>{e();});})}async reinitializeCamera(){if(this.activeCamera==null)a$3.log(a$3.Level.Debug,\"Camera reinitialization delayed\");else {a$3.log(a$3.Level.Debug,\"Reinitialize camera:\",this.activeCamera);try{let e=this.activeCamera;await this.stopStream(),await this.initializeCameraWithSettings(e,this.activeCameraSettings);}catch(e){throw a$3.log(a$3.Level.Warn,\"Couldn't access camera:\",this.activeCamera,e),this.emit(\"cameraAccessError\",e),e}}}removeListener(e,t){var s;let r=((s=this.listeners.get(e))!=null?s:[]).filter(o=>o!==t);this.listeners.set(e,r);}async setCameraPosition(e){var i;this.setInitialCameraPosition(e);let t=d.getMainCameraForPosition(await d.getCameras(),e);if(t&&t.deviceId!==((i=this.selectedCamera)==null?void 0:i.deviceId))return this.initializeCameraWithSettings(t,this.selectedCameraSettings)}async setExposure(e){var r,s,o,m,d,l,v,p;let t=(s=(r=this.mediaStream)==null?void 0:r.getVideoTracks())!=null?s:[];if(t.length===0||typeof t[0].applyConstraints!=\"function\")return;await this.waitForCapabilities();let i=e.time!=null&&e.time>0?\"manual\":\"continuous\";if(((m=(o=this.mediaTrackCapabilities)==null?void 0:o.exposureMode)==null?void 0:m.includes(i))===!0){if(await t[0].applyConstraints({advanced:[{exposureMode:i}]}),e.time!=null&&e.time>0&&this.mediaTrackCapabilities.exposureTime){let u=Math.max((d=this.mediaTrackCapabilities.exposureTime.min)!=null?d:.01,Math.min(e.time,(l=this.mediaTrackCapabilities.exposureTime.max)!=null?l:1e5));await t[0].applyConstraints({advanced:[{exposureTime:u}]});}else if(e.compensation!=null&&i===\"continuous\"&&this.mediaTrackCapabilities.exposureCompensation){let u=Math.max((v=this.mediaTrackCapabilities.exposureCompensation.min)!=null?v:-10,Math.min(e.compensation,(p=this.mediaTrackCapabilities.exposureCompensation.max)!=null?p:10));await t[0].applyConstraints({advanced:[{exposureCompensation:u}]});}}}async setFocus(e){var i,r,s,o,m;if(!this.mediaStream)return;let t=this.mediaStream.getVideoTracks();if(t.length>0&&typeof t[0].applyConstraints==\"function\"){await this.waitForCapabilities();let d=e>=0?\"manual\":\"continuous\";if(((r=(i=this.mediaTrackCapabilities)==null?void 0:i.focusMode)==null?void 0:r.includes(d))===!0&&(await t[0].applyConstraints({advanced:[{focusMode:d}]}),d===\"manual\"&&this.mediaTrackCapabilities.focusDistance)){let l=Math.max(0,Math.min(e,1))*(((s=this.mediaTrackCapabilities.focusDistance.max)!=null?s:1e3)-((o=this.mediaTrackCapabilities.focusDistance.min)!=null?o:.01))+((m=this.mediaTrackCapabilities.focusDistance.min)!=null?m:.01);await t[0].applyConstraints({advanced:[{focusDistance:l}]});}}}async setFrameRate(e){var t,i,r;if(this.mediaStream&&(await this.waitForCapabilities(),(t=this.mediaTrackCapabilities)!=null&&t.frameRate)){let s=this.mediaStream.getVideoTracks();if(s.length>0&&typeof s[0].applyConstraints==\"function\"){let o=Math.min((i=this.mediaTrackCapabilities.frameRate.max)!=null?i:240,(r=e.max)!=null?r:240);await s[0].applyConstraints({advanced:[{frameRate:o}]});}}}setInitialCameraPosition(e){this.cameraPosition=e;}setInteractionOptions(e,t,i){this.torchToggleEnabled=e,this.tapToFocusEnabled=t,this.pinchToZoomEnabled=i;}setMirrorImageEnabled(e,t){this.selectedCamera&&(e?(this.videoElement.classList.add(n.MIRRORED_CLASS_NAME),this.canvas.classList.add(n.MIRRORED_CLASS_NAME)):(this.videoElement.classList.remove(n.MIRRORED_CLASS_NAME),this.canvas.classList.remove(n.MIRRORED_CLASS_NAME)),t&&this.mirrorImageOverrides.set(this.selectedCamera,e));}setPinchToZoomEnabled(e){this.pinchToZoomEnabled=e,this.mediaStream&&(this.pinchToZoomEnabled?this.enablePinchToZoomListeners():this.disablePinchToZoomListeners());}setSelectedCamera(e){this.selectedCamera=e;}setSelectedCameraSettings(e){this.selectedCameraSettings=e;}setTapToFocusEnabled(e){this.tapToFocusEnabled=e,this.mediaStream&&(this.tapToFocusEnabled?this.enableTapToFocusListeners():this.disableTapToFocusListeners());}async setTorchEnabled(e){var t;if(this.mediaStream&&((t=this.mediaTrackCapabilities)==null?void 0:t.torch)===!0){this.torchEnabled=e;let i=this.mediaStream.getVideoTracks();i.length>0&&typeof i[0].applyConstraints==\"function\"&&await i[0].applyConstraints({advanced:[{torch:e}]});}}async setZoom(e){var t,i,r;if(this.mediaStream&&(await this.waitForCapabilities(),(t=this.mediaTrackCapabilities)!=null&&t.zoom)){let s=this.mediaStream.getVideoTracks();if(s.length>0&&typeof s[0].applyConstraints==\"function\"){let o=Math.max((i=this.mediaTrackCapabilities.zoom.min)!=null?i:1,Math.min(e,(r=this.mediaTrackCapabilities.zoom.max)!=null?r:16));await s[0].applyConstraints({advanced:[{zoom:o}]});}}}async setupCameras(){return this.cameraSetupPromise?this.cameraSetupPromise:(this.cameraSetupPromise=this.setupCamerasAndStream(),this.cameraSetupPromise)}pauseStream(){if(!this.mediaStream)return;let e=this.mediaStream.getVideoTracks()[0];e.enabled=!1,a$3.log(a$3.Level.Debug,\"Pause camera video stream\",this.mediaStream);}resumeStream(){if(!this.mediaStream)return;let e=this.mediaStream.getVideoTracks()[0];e.enabled=!0,a$3.log(a$3.Level.Debug,\"Resume camera video stream\",this.mediaStream);}async stopStream(e=!1){this.activeCamera&&(this.activeCamera.currentResolution=void 0),this.activeCamera=void 0,this.torchEnabled=!1,this.mediaStream&&(a$3.log(a$3.Level.Debug,`Stop camera video stream access${e?\" (abort access detection)\":\"\"}:`,this.mediaStream),document.removeEventListener(\"visibilitychange\",this.checkCameraVideoStreamAccessIfVisibleListener),window.clearTimeout(this.cameraAccessTimeout),window.clearInterval(this.videoMetadataCheckInterval),window.clearTimeout(this.getCapabilitiesTimeout),window.clearTimeout(this.manualFocusWaitTimeout),window.clearTimeout(this.manualToAutofocusResumeTimeout),window.clearInterval(this.autofocusInterval),this.videoElement.pause(),await new Promise(t=>{setTimeout(()=>{var i,r,s;for(let o of (r=(i=this.mediaStream)==null?void 0:i.getVideoTracks())!=null?r:[])o.removeEventListener(\"ended\",this.videoTrackEndedListener),o.stop();this.videoElement.srcObject=null,this._canvas2dContext&&this._canvas2dContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.mediaStream=void 0,this.mediaTrackCapabilities=void 0,this.mediaTrackCapabilitiesPromise=void 0,this.mediaTrackCapabilitiesPromiseResolver=void 0,e||(s=this.abortedCameraInitializationResolveCallback)==null||s.call(this),t();},0);}));}stopVideoTracks(){if(this.mediaStream!=null)for(let e of this.mediaStream.getVideoTracks())e.stop();}async toggleTorch(){this.torchEnabled=!this.torchEnabled,await this.setTorchEnabled(this.torchEnabled);}updateCanvasVideoImage(){this.canvas2dContext.drawImage(this.videoElement,0,0);}async waitForCapabilities(){var e;return (e=this.mediaTrackCapabilitiesPromise)!=null?e:Promise.resolve()}setFrameReaderType(e){e!==this._frameReaderType&&(this._frameReaderType=e,a$3.log(a$3.Level.Debug,`Change frame reader type to ${this._frameReaderType} mode`));}async allowPictureInPicture(e){e?(this.videoElement.disablePictureInPicture=!1,this.videoElement.removeAttribute(\"controlslist\"),this.videoElement.removeAttribute(\"disablepictureinpicture\")):(this.videoElement.disablePictureInPicture=!0,this.videoElement.setAttribute(\"controlslist\",\"nodownload\"),this.videoElement.setAttribute(\"disablepictureinpicture\",\"true\")),await this.reinitializeCamera();}setFrameHandling(e){var t;this._synchronousFrameHandling=e,this._frameReaderOptions=this.getFrameReaderOptions(e),(t=this._glFrameReaders[this._frameReaderType])==null||t.dispose(),delete this._glFrameReaders[this._frameReaderType];}async accessAutoselectedCamera(e){let t=d.sortCamerasForCameraPosition(e,this.cameraPosition),i=t.shift();for(;i;)try{await this.initializeCameraWithSettings(i,this.selectedCameraSettings);return}catch(r){if(this.setSelectedCamera(),t.length>0){a$3.log(a$3.Level.Warn,\"Couldn't access camera:\",i,r),i=t.shift();continue}throw r}throw new a$4(n.noCameraErrorParameters)}getFrameReaderOptions(e){return e?{minPoolCapacity:0,maxPoolCapacity:1}:a$2.isDesktopDevice()?{maxPoolCapacity:2,minPoolCapacity:1}:{maxPoolCapacity:10,minPoolCapacity:3}}getFrameReader(){var t;if(this._glFrameReaders[this._frameReaderType])return this._glFrameReaders[this._frameReaderType];if(!this._canvasWebGLContext)return null;let e=(t=this._frameReaderOptions)!=null?t:this.getFrameReaderOptions(this._synchronousFrameHandling);switch(this._frameReaderType){case\"GRAYSCALE\":{this._glFrameReaders.GRAYSCALE=new a$5(this._canvasWebGLContext,e),this._glFrameReaders.RGBA=new b$1(this._canvasWebGLContext,{minPoolCapacity:1,maxPoolCapacity:2});break}case\"RGBA\":{this._glFrameReaders.RGBA=new b$1(this._canvasWebGLContext,e);break}default:b(this._frameReaderType);}return a$3.log(a$3.Level.Debug,`Created frame reader ${this._frameReaderType}`,e),this._glFrameReaders[this._frameReaderType]}async accessInitialCamera(){let e={position:this.cameraPosition,deviceId:\"\",label:\"\"};try{await this.initializeCameraWithSettings(e,this.selectedCameraSettings);}catch(t){}finally{this.setSelectedCamera();}return e}recreateCanvas(){this.canvas.removeEventListener(\"webglcontextlost\",this.handleWebGLContextLostListener),this._canvasWebGLContext=void 0,this._canvas2dContext=void 0;for(let t of Object.values(this._glFrameReaders))t==null||t.dispose();let e=document.createElement(\"canvas\");e.addEventListener(\"webglcontextlost\",this.handleWebGLContextLostListener),e.width=this.canvas.width,e.height=this.canvas.height,e.className=this.canvas.className,this.canvas=e;}captureImageFor2dContext(){if(!this.isVideoAndContextStateValid())return null;let{width:e,height:t}=this.canvas;return {colorType:\"RGBA\",data:this.canvas2dContext.getImageData(0,0,e,t).data,width:e,height:t}}areVideoAndWebGLSizeMismatching(){return this.canvasWebGLContext?this.canvasWebGLContext.drawingBufferWidth!==this.videoElement.videoWidth||this.canvasWebGLContext.drawingBufferHeight!==this.videoElement.videoHeight:!0}captureImageForWebGLContext(){if(!this.isVideoAndContextStateValid()||!this.canvasWebGLContext||this.canvasWebGLContext.drawingBufferWidth<=2||this.canvasWebGLContext.drawingBufferHeight<=2||this.areVideoAndWebGLSizeMismatching()||this.getFrameReader()==null)return null;let e=this.getFrameReader().readFromSource(this.videoElement);if(e.data[3]!==255&&e.colorType===\"RGBA\"){if(a$3.log(a$3.Level.Warn,\"Detected incorrect GPU accelerated WebGL image processing, switching to canvas mode\"),this.recreateCanvas(),this.canvas2dContext==null)throw new Error(\"Unable to get 2d canvas context\");return this.captureImage()}return e}async checkCameraAccess(e){return new Promise((t,i)=>{this.cameraAccessRejectCallback=r=>{a$3.log(a$3.Level.Debug,\"Camera video stream access failure (video data load timeout):\",e),this.gui.setCameraRecoveryVisible(!0),i(r);},this.setCameraAccessTimeout();})}checkCameraVideoStreamAccessIfVisible(){document.visibilityState===\"visible\"&&(a$3.log(a$3.Level.Debug,\"Page is visible again, waiting for camera video stream start...\"),document.removeEventListener(\"visibilitychange\",this.checkCameraVideoStreamAccessIfVisibleListener),this.setCameraAccessTimeout());}async checkVideoMetadata(e){return new Promise((t,i)=>{this.videoElement.onloadeddata=()=>{if(this.videoElement.onloadeddata=null,window.clearTimeout(this.cameraAccessTimeout),this.videoElement.videoWidth>2&&this.videoElement.videoHeight>2&&this.videoElement.currentTime>0){this.updateActiveCameraCurrentResolution(e),a$3.log(a$3.Level.Debug,\"Camera video stream access success:\",e),t();return}let r=performance.now();window.clearInterval(this.videoMetadataCheckInterval),this.videoMetadataCheckInterval=window.setInterval(async()=>{if(this.videoElement.videoWidth<=2||this.videoElement.videoHeight<=2||this.videoElement.currentTime===0){if(performance.now()-r>n.videoMetadataCheckTimeoutMs){a$3.log(a$3.Level.Warn,\"Camera video stream access failure (valid video metadata timeout):\",e),window.clearInterval(this.videoMetadataCheckInterval),await this.stopStream(!0),i(new a$4(n.notReadableErrorParameters));return}return}window.clearInterval(this.videoMetadataCheckInterval),this.updateActiveCameraCurrentResolution(e),a$3.log(a$3.Level.Debug,\"Camera video stream access success:\",e),t();},n.videoMetadataCheckIntervalMs);};})}disablePinchToZoomListeners(){this.videoElement.removeEventListener(\"touchstart\",this.triggerZoomStartListener),this.videoElement.removeEventListener(\"touchmove\",this.triggerZoomMoveListener);}disableTapToFocusListeners(){for(let e of [\"touchend\",\"mousedown\"])this.videoElement.removeEventListener(e,this.triggerManualFocusListener);}emit(e,t){var r;let i=(r=this.listeners.get(e))!=null?r:[];for(let s of i)s(t);}enablePinchToZoomListeners(){this.videoElement.addEventListener(\"touchstart\",this.triggerZoomStartListener),this.videoElement.addEventListener(\"touchmove\",this.triggerZoomMoveListener);}enableTapToFocusListeners(){for(let e of [\"touchend\",\"mousedown\"])this.videoElement.addEventListener(e,this.triggerManualFocusListener);}getActiveCamera(e,t,i){return e.length===1?e[0]:e.find(r=>r.deviceId===i||r.label!==\"\"&&r.label===t)}getInitialCameraResolutionConstraint(e){var i;let t;switch((i=this.activeCameraSettings)==null?void 0:i.preferredResolution){case\"uhd4k\":{t=0;break}case\"fullHd\":{t=1;break}case\"hd\":default:{t=2;break}}return t}async handleCameraInitializationError(e,t,i){if(![\"OverconstrainedError\",\"NotReadableError\"].includes(i.name)||i.name===\"NotReadableError\"&&t===4)throw a$3.log(a$3.Level.Debug,\"Camera video stream access failure (unrecoverable error)\",e,i),i.name!==\"NotAllowedError\"&&d.markCameraAsInaccessible(e),i;if(i.name===\"OverconstrainedError\"&&t===4){if(e.deviceId===\"\")throw a$3.log(a$3.Level.Warn,\"Camera video stream access failure (no camera with such type error)\",e,i),i;a$3.log(a$3.Level.Warn,\"Detected non-existent deviceId error, attempt to find and reaccess updated camera\",e,i);let r=e.deviceId;if(await d.getCameras(!0),r===e.deviceId)throw a$3.log(a$3.Level.Warn,\"Camera video stream access failure (updated camera not found after non-existent deviceId error)\",e,i),d.markCameraAsInaccessible(e),i;return a$3.log(a$3.Level.Warn,\"Updated camera found (recovered from non-existent deviceId error), attempt to access it\",e),this.initializeCameraForResolution(e)}return this.initializeCameraForResolution(e,t+1)}handleVideoResize(){if(!(this.videoElement.videoWidth<=2||this.videoElement.videoHeight<=2)){if(this.activeCamera&&this.updateActiveCameraCurrentResolution(this.activeCamera),this.canvasWebGLContext!=null){if(this.canvas.width===this.videoElement.videoWidth&&this.canvas.height===this.videoElement.videoHeight)return;this.canvas.width=this.videoElement.videoWidth,this.canvas.height=this.videoElement.videoHeight,this.canvasWebGLContext.viewport(0,0,this.canvasWebGLContext.drawingBufferWidth,this.canvasWebGLContext.drawingBufferHeight);}else if(this.canvas2dContext!=null){if(this.canvas.width===this.videoElement.videoWidth&&this.canvas.height===this.videoElement.videoHeight)return;this.canvas.width=this.videoElement.videoWidth,this.canvas.height=this.videoElement.videoHeight;}}}handleWebGLContextLost(){a$3.log(a$3.Level.Warn,\"WebGL context has been lost, restoring...\"),this._canvasWebGLContext=void 0,this.canvasWebGLContext?(this.handleVideoResize(),a$3.log(a$3.Level.Warn,\"WebGL context restored\")):a$3.log(a$3.Level.Error,\"WebGL context restore failed\");}async initializeCameraAndCheckUpdatedSettings(e){var t,i,r,s,o;try{if(await this.initializeCameraForResolution(e),this.selectedCameraSettings!==this.activeCameraSettings&&(this.selectedCameraSettings==null||this.activeCameraSettings==null||Object.keys(this.selectedCameraSettings).some(u=>{var b,f;return ((b=this.selectedCameraSettings)==null?void 0:b[u])!==((f=this.activeCameraSettings)==null?void 0:f[u])}))){this.activeCameraSettings=this.selectedCameraSettings,await this.initializeCameraAndCheckUpdatedSettings(e);return}this.activeCameraSettings&&this.activeCameraSettings.zoomFactor>1&&await this.setZoom(this.activeCameraSettings.zoomFactor);let m=(t=this.activeCameraSettings)==null?void 0:t.getProperty(\"minFrameRate\"),d=(i=this.activeCameraSettings)==null?void 0:i.getProperty(\"maxFrameRate\");(m!=null||d!=null)&&await this.setFrameRate({min:m,max:d});let l=(r=this.activeCameraSettings)==null?void 0:r.getProperty(\"manualLensPosition\");l!=null&&await this.setFocus(l);let v=(s=this.activeCameraSettings)==null?void 0:s.getProperty(\"exposureTargetBias\"),p=(o=this.activeCameraSettings)==null?void 0:o.getProperty(\"exposureDuration\");(v!=null||p!=null)&&await this.setExposure({compensation:v,time:p});}finally{this.cameraInitializationPromise=void 0;}}async initializeCameraForResolution(e,t){var r;this.gui.setCameraRecoveryVisible(!1);let i=t!=null?t:this.getInitialCameraResolutionConstraint(e);this.mediaStream!=null&&e.deviceId!==\"\"&&((r=this.activeCamera)==null?void 0:r.deviceId)===e.deviceId?await(a$2.isIPhone()?this.initializeStreamForResolution(e,i):this.updateStreamForResolution(e,i)):await this.initializeStreamForResolution(e,i);}async initializeStreamForResolution(e,t){var i;await this.stopStream();try{let r=(i=this.activeCameraSettings)==null?void 0:i.getProperty(\"preferredAspectRatio\"),s=await d.accessCameraStream(e,t,r);if(a$3.log(a$3.Level.Debug,\"Camera accessed, waiting for camera video stream start...\"),typeof s.getVideoTracks()[0].getSettings==\"function\"){let o=s.getVideoTracks()[0].getSettings();if(o.width!=null&&o.height!=null&&(o.width===2||o.height===2)){if(a$3.log(a$3.Level.Debug,\"Camera video stream access failure (invalid video metadata):\",e),t===4)throw new a$4(n.notReadableErrorParameters);return await this.stopStream(),this.initializeStreamForResolution(e,t+1)}}this.mediaStream=s;for(let o of this.mediaStream.getVideoTracks())o.addEventListener(\"ended\",this.videoTrackEndedListener),o.addEventListener(\"mute\",this.videoTrackMuteListener),o.addEventListener(\"unmute\",this.videoTrackMuteListener);try{await this.setupCameraStreamVideo(e,s);}catch(o){if(t===4)throw o;return this.initializeStreamForResolution(e,t+1)}}catch(r){return this.handleCameraInitializationError(e,t,r)}}isVideoAndContextStateValid(){return this.videoElement.readyState===4&&this.videoElement.videoWidth>2&&this.videoElement.videoHeight>2&&this.canvas.width>2&&this.canvas.height>2}postStreamInitialization(){window.clearTimeout(this.getCapabilitiesTimeout),this.getCapabilitiesTimeout=window.setTimeout(()=>{this.storeStreamCapabilities(),this.setupAutofocus();},n.getCapabilitiesTimeoutMs);}async recoverStreamIfNeeded(){var t,i;let e=(t=this.mediaStream)==null?void 0:t.getVideoTracks();((i=e==null?void 0:e[0])==null?void 0:i.readyState)===\"ended\"&&await this.reinitializeCamera();}reportCameraProperties(e,t,i=!0){this.emit(\"cameraProperties\",{deviceId:e,isFrontFacing:t===\"userFacing\",hasAutofocus:i});}setCameraAccessTimeout(){window.clearTimeout(this.cameraAccessTimeout),this.cameraAccessTimeout=window.setTimeout(async()=>{var e;document.visibilityState===\"visible\"?(await this.stopStream(!0),(e=this.cameraAccessRejectCallback)==null||e.call(this,new a$4(n.notReadableErrorParameters))):(a$3.log(a$3.Level.Debug,\"Page is currently not visible, delay camera video stream access detection\"),document.addEventListener(\"visibilitychange\",this.checkCameraVideoStreamAccessIfVisibleListener));},n.cameraAccessTimeoutMs);}setupAutofocus(){if(window.clearTimeout(this.manualFocusWaitTimeout),window.clearTimeout(this.manualToAutofocusResumeTimeout),this.mediaStream&&this.mediaTrackCapabilities){let e=this.mediaTrackCapabilities.focusMode;Array.isArray(e)&&!e.includes(\"continuous\")&&e.includes(\"single-shot\")&&(window.clearInterval(this.autofocusInterval),this.autofocusInterval=window.setInterval(this.triggerAutoFocus.bind(this),n.autofocusIntervalMs));}}async setupCameraStreamVideo(e,t){this.videoElement.addEventListener(\"loadedmetadata\",this.postStreamInitializationListener),this.videoElement.addEventListener(\"resize\",this.videoResizeListener),this.tapToFocusEnabled&&this.enableTapToFocusListeners(),this.pinchToZoomEnabled&&this.enablePinchToZoomListeners();let i=Promise.race([this.checkCameraAccess(e),this.checkVideoMetadata(e),new Promise(r=>{this.abortedCameraInitializationResolveCallback=r;})]);return this.videoElement.srcObject=t,this.videoElement.load(),await this.playVideo(),this.handleVideoResize(),this.reportCameraProperties(e.deviceId,e.position),i}async setupCamerasAndStream(){var e,t;try{let i;this.selectedCamera==null&&(i=await this.accessInitialCamera());let r=await d.getCameras(!1,!0),s=(t=(e=this.mediaStream)==null?void 0:e.getVideoTracks()[0])==null?void 0:t.getSettings().deviceId;if(this.mediaStream&&i){let o=this.getActiveCamera(r,i.label,s);if(o){if(d.adjustCameraFromMediaStream(this.mediaStream,o),a$2.isDesktopDevice()&&(d.setMainCameraForPositionOverridesOnDesktop(this.cameraPosition,o),d.setMainCameraForPositionOverridesOnDesktop(o.position,o)),r.length===1||d.getMainCameraForPosition(r,this.cameraPosition)===o){a$3.log(a$3.Level.Debug,\"Initial camera access was correct (main camera), keep camera:\",o),this.setSelectedCamera(o),this.updateActiveCameraCurrentResolution(o),await this.recoverStreamIfNeeded();return}a$3.log(a$3.Level.Debug,\"Initial camera access was incorrect (not main camera), change camera\",{...i,deviceId:s});}else a$3.log(a$3.Level.Debug,\"Initial camera access was incorrect (unknown camera), change camera\",{...i,deviceId:s});}if(this.selectedCamera==null){await this.accessAutoselectedCamera(r);return}await this.initializeCameraWithSettings(this.selectedCamera,this.selectedCameraSettings);}finally{this.cameraSetupPromise=void 0;}}storeStreamCapabilities(){var e;if(this.mediaStream){let t=this.mediaStream.getVideoTracks();t.length>0&&typeof t[0].getCapabilities==\"function\"&&(this.mediaTrackCapabilities=t[0].getCapabilities()),this.mediaTrackCapabilitiesPromiseResolver&&this.mediaTrackCapabilitiesPromiseResolver();}this.activeCamera&&this.reportCameraProperties(this.activeCamera.deviceId,this.activeCamera.position,((e=this.mediaTrackCapabilities)==null?void 0:e.focusMode)==null||this.mediaTrackCapabilities.focusMode.includes(\"continuous\"));}async triggerAutoFocus(){await this.triggerFocusMode(\"single-shot\");}async triggerFocusMode(e){if(this.mediaStream){let t=this.mediaStream.getVideoTracks();if(t.length>0&&typeof t[0].applyConstraints==\"function\")try{await t[0].applyConstraints({advanced:[{focusMode:e}]});}catch(i){}}}async triggerManualFocus(e){if(e){if(e.preventDefault(),e.type===\"touchend\"&&e.touches.length>0)return;if(this.pinchToZoomDistance!=null){this.pinchToZoomDistance=void 0;return}}if(window.clearTimeout(this.manualFocusWaitTimeout),window.clearTimeout(this.manualToAutofocusResumeTimeout),!this.mediaStream||!this.mediaTrackCapabilities)return;let t=this.mediaTrackCapabilities.focusMode;Array.isArray(t)&&t.includes(\"single-shot\")&&(t.includes(\"continuous\")&&t.includes(\"manual\")?await this.triggerManualFocusForContinuous():t.includes(\"continuous\")||await this.triggerManualFocusForSingleShot());}async triggerManualFocusForContinuous(){var i;if(!this.mediaStream)return;this.manualToAutofocusResumeTimeout=window.setTimeout(async()=>{await this.triggerFocusMode(\"continuous\");},n.manualToAutofocusResumeTimeoutMs);let e=!0,t=this.mediaStream.getVideoTracks();t.length>0&&typeof t[0].getConstraints==\"function\"&&(e=((i=t[0].getConstraints().advanced)==null?void 0:i.some(r=>r.focusMode===\"manual\"))===!0),e?(await this.triggerFocusMode(\"continuous\"),this.manualFocusWaitTimeout=window.setTimeout(async()=>{await this.triggerFocusMode(\"manual\");},n.manualFocusWaitTimeoutMs)):await this.triggerFocusMode(\"manual\");}async triggerManualFocusForSingleShot(){window.clearInterval(this.autofocusInterval),this.manualToAutofocusResumeTimeout=window.setTimeout(()=>{this.autofocusInterval=window.setInterval(this.triggerAutoFocus.bind(this),n.autofocusIntervalMs);},n.manualToAutofocusResumeTimeoutMs);try{await this.triggerFocusMode(\"single-shot\");}catch(e){}}async triggerZoomMove(e){this.pinchToZoomDistance==null||(e==null?void 0:e.touches.length)!==2||e.preventDefault();}triggerZoomStart(e){var r,s,o,m;if((e==null?void 0:e.touches.length)!==2||(e.preventDefault(),this.pinchToZoomDistance=Math.hypot((e.touches[1].screenX-e.touches[0].screenX)/screen.width,(e.touches[1].screenY-e.touches[0].screenY)/screen.height),!this.mediaStream||!((r=this.mediaTrackCapabilities)!=null&&r.zoom)))return;let t=this.mediaStream.getVideoTracks();if(t.length===0||typeof t[0].getConstraints!=\"function\")return;this.pinchToZoomInitialZoom=(s=this.mediaTrackCapabilities.zoom.min)!=null?s:1;let i=t[0].getConstraints();if(i.advanced){let d=(o=i.advanced.find(l=>\"zoom\"in l))==null?void 0:o.zoom;d!=null&&(this.pinchToZoomInitialZoom=typeof d==\"number\"?d:(m=d.ideal)!=null?m:1);}}updateActiveCameraCurrentResolution(e){this.videoElement.videoWidth>2&&this.videoElement.videoHeight>2&&(e.currentResolution={width:this.videoElement.videoWidth,height:this.videoElement.videoHeight}),e.deviceId!==\"\"&&(this.activeCamera=e,this.setMirrorImageEnabled(this.isMirrorImageEnabled(),!1));}async updateStreamForResolution(e,t){var i;if(this.mediaStream==null)await this.initializeCameraForResolution(e,t);else try{let r=(i=this.activeCameraSettings)==null?void 0:i.getProperty(\"preferredAspectRatio\");a$3.log(a$3.Level.Debug,\"Setting new resolution for active camera video stream...\"),await this.mediaStream.getVideoTracks()[0].applyConstraints(d.getUserMediaVideoParameters(t,r)),await new Promise(o=>{this.videoElement.addEventListener(\"timeupdate\",()=>{o();},{once:!0});});let s=this.mediaStream.getVideoTracks()[0].getSettings();a$3.log(a$3.Level.Debug,\"New active camera video stream resolution set\",{width:s.width,height:s.height});}catch(r){if(t===4)throw r;await this.updateStreamForResolution(e,t+1);}}async videoTrackEndedRecovery(){if(document.visibilityState===\"visible\")try{a$3.log(a$3.Level.Debug,'Detected video track \"ended\" event, try to reinitialize camera'),await this.reinitializeCamera();}catch(e){}else a$3.log(a$3.Level.Debug,\"Page is currently not visible, delay camera reinitialization until visible\"),document.addEventListener(\"visibilitychange\",this.checkCameraVideoStreamAccessIfVisibleListener);}videoTrackMuteRecovery(e){if(this.videoElement.onloadeddata!=null){a$3.log(a$3.Level.Debug,`Detected video track \"${e.type}\" event, delay camera video stream access detection`),this.setCameraAccessTimeout();return}let t=e.type===\"mute\";t!==this.gui.isCameraRecoveryVisible()&&(a$3.log(a$3.Level.Debug,`Detected video track \"${e.type}\" event, ${t?\"enable\":\"disable\"} camera recovery`),this.gui.setCameraRecoveryVisible(t));}};n.autofocusIntervalMs=1500,n.cameraAccessTimeoutMs=4e3,n.getCapabilitiesTimeoutMs=500,n.manualFocusWaitTimeoutMs=400,n.manualToAutofocusResumeTimeoutMs=5e3,n.noCameraErrorParameters={name:\"NoCameraAvailableError\",message:\"No camera available\"},n.notReadableErrorParameters={name:\"NotReadableError\",message:\"Could not initialize camera correctly\"},n.videoMetadataCheckIntervalMs=50,n.videoMetadataCheckTimeoutMs=4e3,n.MIRRORED_CLASS_NAME=a.MIRRORED_CLASS_NAME,n._instance=null;var y=n;\n\nexport { w as a, R as b, L as c, y as d };\n", "import { d } from './chunk-5Y4OYXNX.js';\n\nvar u=(o=>(o.On=\"on\",o.Off=\"off\",o.Standby=\"standby\",o.Starting=\"starting\",o.Stopping=\"stopping\",o.BootingUp=\"bootingUp\",o.WakingUp=\"wakingUp\",o.GoingToSleep=\"goingToSleep\",o.ShuttingDown=\"shuttingDown\",o))(u||{}),c=(t=>(t.On=\"on\",t.Off=\"off\",t))(c||{}),m=(t=>(t.WorldFacing=\"worldFacing\",t.UserFacing=\"userFacing\",t))(m||{}),p=(r=>(r.Auto=\"auto\",r.HD=\"hd\",r.FullHD=\"fullHd\",r.UHD4K=\"uhd4k\",r))(p||{}),g=(r=>(r.None=\"none\",r.Manual=\"manual\",r.ManualUntilCapture=\"manualUntilCapture\",r.AutoOnLocation=\"autoOnLocation\",r))(g||{});function f(a){var e;return ((e=a==null?void 0:a.toJSONObject())==null?void 0:e.type)===\"camera\"}var i=class a{constructor(e){this.preferredResolution=d.Camera.Settings.preferredResolution;this.zoomFactor=d.Camera.Settings.zoomFactor;this.zoomGestureZoomFactor=d.Camera.Settings.zoomGestureZoomFactor;this.focus={focusGestureStrategy:d.Camera.Settings.focusGestureStrategy};if(e!=null)for(let t of Object.getOwnPropertyNames(e))this[t]=e[t];}get focusGestureStrategy(){return this.focus.focusGestureStrategy}set focusGestureStrategy(e){this.focus.focusGestureStrategy=e;}static fromJSON(e){let t=new a;return t.preferredResolution=e.preferredResolution,t.zoomFactor=e.zoomFactor,t.zoomGestureZoomFactor=e.zoomGestureZoomFactor,t.focusGestureStrategy=e.focusGestureStrategy,t}setProperty(e,t){this[e]=t;}getProperty(e){return this[e]}toJSONObject(){let e={preferredResolution:this.preferredResolution,zoomFactor:this.zoomFactor,zoomGestureZoomFactor:this.zoomGestureZoomFactor,focus:{focusGestureStrategy:this.focus.focusGestureStrategy}},t={};for(let n of Object.keys(this))[...Object.keys(e),\"focusGestureStrategy\"].includes(n)||(t[n]=this[n]);return {...e,...t}}};\n\nexport { u as a, c as b, m as c, p as d, g as e, f, i as g };\n", "import { a as a$1 } from './chunk-IWMYUNZ3.js';\nimport { d } from './chunk-XLX4QIMT.js';\nimport { a } from './chunk-SP3HSP4K.js';\nimport { a as a$2 } from './chunk-PSQ6LAQA.js';\nimport { g as g$1 } from './chunk-36CGJKPG.js';\nimport { d as d$1 } from './chunk-5Y4OYXNX.js';\n\nvar g=class n{constructor(e){this.deviceId=\"\";this.type=\"camera\";this._currentState=\"off\";this._settings=new g$1;this._desiredTorchState=\"off\";this._desiredState=\"off\";this.listeners=[];this._context=null;this.stateTransitionStrategyMap={off:{on:this.transitionFromStateOffToOn.bind(this),standby:this.transitionFromStateOffToStandby.bind(this)},on:{off:this.transitionFromStateOnToOff.bind(this),standby:this.transitionFromStateOnToStandby.bind(this)},standby:{off:this.transitionFromStateStandbyToOff.bind(this),on:this.transitionFromStateStandbyToOn.bind(this)}};this.cameraManager=e!=null?e:d.instance(),this.updateCanvasVideoImage=this.updateCanvasVideoImage.bind(this),this.captureAndSend=this.captureAndSend.bind(this);}static get default(){let e=new n;return e.position=\"worldFacing\",e}get desiredState(){return this._desiredState}get settings(){return this._settings}get currentResolution(){var e;return (e=this._currentResolution)!=null?e:null}get context(){return this._context}set context(e){this._context=e,this._context&&this.currentState===\"on\"&&this.startSendingCapturesToWorker();}get currentState(){return this._currentState}static atPosition(e){if(d$1.Camera.availablePositions.includes(e)){let t=new n;return t.position=e,t}return a.log(a.Level.Warn,`invalid CameraPosition: \"${e}\"`),null}static fromDeviceCamera(e){let t=n.atPosition(e.position);return t.deviceId=e.deviceId,t.label=e.label,t}async switchToDesiredState(e){var t,i;return this.currentTransitionStrategyPromise&&await this.currentTransitionStrategyPromise,this.currentTransitionStrategyPromise=(i=(t=this.stateTransitionStrategyMap[this.currentState])==null?void 0:t[e])==null?void 0:i.call(t).catch(r=>{if(r instanceof DOMException&&r.message===\"The associated Track is in an invalid state\"){a.log(a.Level.Warn,r);return}throw r}),this.currentTransitionStrategyPromise}getDesiredTorchState(){return this._desiredTorchState}async setDesiredTorchState(e){this._desiredTorchState=e,await this.cameraManager.setTorchEnabled(this._desiredTorchState===\"on\"),await this.notifyContext({type:\"torchState\",newValue:this._desiredTorchState});}async isTorchAvailable(){return this.cameraManager.isTorchAvailable()}addListener(e){e!=null&&(this.listeners.includes(e)||this.listeners.push(e));}removeListener(e){e!=null&&this.listeners.includes(e)&&this.listeners.splice(this.listeners.indexOf(e),1);}async applySettings(e){var i;this._settings=new g$1(e);let t=this.settings.getProperty(\"grayScaleFrameReader\");if(this.cameraManager.setFrameReaderType(t===!0?\"GRAYSCALE\":\"RGBA\"),this.currentState===\"on\"||this.currentState===\"standby\"){let r=this.cameraManager.activeCameraSettings;(r==null?void 0:r.preferredResolution)!==this.settings.preferredResolution&&(await this.cameraManager.applyCameraSettings(this.settings),(i=this.cameraManager.activeCamera)!=null&&i.currentResolution&&(this._currentResolution={width:this.cameraManager.activeCamera.currentResolution.width,height:this.cameraManager.activeCamera.currentResolution.height})),await this.cameraManager.setZoom(this.settings.zoomFactor);let o=this.settings.getProperty(\"minFrameRate\"),c=this.settings.getProperty(\"maxFrameRate\");(o!=null||c!=null)&&await this.cameraManager.setFrameRate({min:o,max:c});let m=this.settings.getProperty(\"manualLensPosition\");m!=null&&await this.cameraManager.setFocus(m);let u=this.settings.getProperty(\"exposureTargetBias\"),d=this.settings.getProperty(\"exposureDuration\");(u!=null||d!=null)&&await this.cameraManager.setExposure({compensation:u,time:d});}return this.notifyContext({type:\"cameraSettings\",newValue:this.settings})}toJSONObject(){return {type:this.type,position:this.position,settings:this.settings.toJSONObject(),desiredState:this.desiredState,desiredTorchState:this._desiredTorchState}}getMirrorImageEnabled(){var e;return (e=this._desiredMirrorImageEnabled)!=null?e:this.cameraManager.isMirrorImageEnabled()}async setMirrorImageEnabled(e){this._desiredMirrorImageEnabled=e,this.cameraManager.setMirrorImageEnabled(e,!0),this.context&&await this.context.setFrameSource(this);}getCurrentState(){return this._currentState}async setCurrentState(e){if(e!==this._currentState){this._currentState=e,this.notifyListeners();try{await this.notifyContext({type:\"frameSourceState\",newValue:e}),e===\"on\"&&this.startSendingCapturesToWorker();}catch(t){a.log(a.Level.Warn,\"Error while notifying context about new state of Camera\");}}}async setupCamera(){if(this.cameraManager.setSelectedCameraSettings(this.settings),this.deviceId===\"\")this.cameraManager.setSelectedCamera(),this.cameraManager.setInitialCameraPosition(this.position);else {let t=(await a$1.getCameras()).find(i=>i.deviceId===this.deviceId);t&&(this.cameraManager.setInitialCameraPosition(t.position),this.cameraManager.setSelectedCamera(t));}await this.cameraManager.setupCameras(),typeof this._desiredMirrorImageEnabled==\"boolean\"?this.cameraManager.setMirrorImageEnabled(this._desiredMirrorImageEnabled,!0):this.cameraManager.setMirrorImageEnabled(this.cameraManager.isMirrorImageEnabled(),!1),this.context&&await this.context.setFrameSource(this),this.cameraManager.activeCamera&&(this.label=this.cameraManager.activeCamera.label,this.position=this.cameraManager.activeCamera.position,this.deviceId=this.cameraManager.activeCamera.deviceId,this._currentResolution=this.cameraManager.activeCamera.currentResolution);}async notifyContext(e){if(this.context)return this.context.update([e])}notifyListeners(){for(let e of this.listeners)e.didChangeState&&e.didChangeState(this,this.currentState);}updateCanvasVideoImage(){this.currentState===\"on\"&&this.context&&(this.cameraManager.updateCanvasVideoImage(),this._lastCanvasVideoPreviewAnimationFrame=this.cameraManager.requestVideoFrame(this.updateCanvasVideoImage));}async captureAndSend(){if(this.currentState!==\"on\"||!this.context)return;if(!this.context.hasEnabledMode()){this._lastCaptureRequestAnimationFrame=this.cameraManager.requestVideoFrame(this.captureAndSend);return}let e=null;try{e=this.cameraManager.captureImage();}catch(t){a.log(a.Level.Warn,t.message);}finally{if(e!=null)if(this.cameraManager.synchronousFrameHandling){let t=await this.context.sendFrameToProcessor(e);this.cameraManager.recycle(t.data);}else this.context.sendFrameToProcessor(e).then(t=>(this.cameraManager.recycle(t.data),null)).catch(t=>{a.log(a.Level.Warn,\"error while recycling uint8array\",t);});this._lastCaptureRequestAnimationFrame=this.cameraManager.requestVideoFrame(this.captureAndSend);}}startSendingCapturesToWorker(){this.stopSendingCapturesToWorker(),this.captureAndSend();}stopSendingCapturesToWorker(){this._lastCanvasVideoPreviewAnimationFrame!=null&&this.cameraManager.cancelVideoFrame(this._lastCanvasVideoPreviewAnimationFrame),this._lastCaptureRequestAnimationFrame!=null&&this.cameraManager.cancelVideoFrame(this._lastCaptureRequestAnimationFrame);}async transitionFromStateOffToOn(){if(!(this.currentState===\"on\"||this.currentState===\"starting\"||this.currentState===\"wakingUp\")){this._desiredState=\"on\",await this.setCurrentState(\"starting\");try{await this.setupCamera(),await this.setCurrentState(\"on\");}catch(e){throw a.log(a.Level.Error,e),await this.setCurrentState(\"off\"),e}}}async transitionFromStateOffToStandby(){if(!(this.currentState===\"standby\"||this.currentState===\"bootingUp\"||this.currentState===\"goingToSleep\")){if(await this.isAndroidWebView()){a.log(a.Level.Warn,'Warning: \"Standby\" state does not work inside web views. Falling back to state \"On\".'),await this.transitionFromStateOffToOn();return}this._desiredState=\"standby\",await this.setCurrentState(\"bootingUp\");try{await this.setupCamera(),this.cameraManager.pauseStream(),await this.setCurrentState(\"standby\");}catch(e){throw a.log(a.Level.Error,e),await this.setCurrentState(\"off\"),e}await this.setCurrentState(\"standby\"),await this.setDesiredTorchState(\"off\");}}async transitionFromStateOnToOff(){this.currentState===\"off\"||this.currentState===\"stopping\"||(this._desiredState=\"off\",await this.setCurrentState(\"stopping\"),await this.cameraManager.stopStream(),await this.setCurrentState(\"off\"),await this.setDesiredTorchState(\"off\"));}async transitionFromStateOnToStandby(){if(!(this.currentState===\"standby\"||this.currentState===\"bootingUp\"||this.currentState===\"goingToSleep\")){if(await this.isAndroidWebView()){a.log(a.Level.Warn,'Warning: \"Standby\" state does not work inside web views. Falling back to state \"Off\".'),await this.transitionFromStateOnToOff();return}this._desiredState=\"standby\",await this.setCurrentState(\"goingToSleep\"),this.cameraManager.pauseStream(),await this.setCurrentState(\"standby\"),await this.setDesiredTorchState(\"off\");}}async transitionFromStateStandbyToOff(){this.currentState===\"off\"||this.currentState===\"stopping\"||(this._desiredState=\"off\",await this.setCurrentState(\"shuttingDown\"),await this.cameraManager.stopStream(),await this.setCurrentState(\"off\"),await this.setDesiredTorchState(\"off\"));}async transitionFromStateStandbyToOn(){this.currentState===\"on\"||this.currentState===\"starting\"||this.currentState===\"wakingUp\"||(this._desiredState=\"on\",await this.setCurrentState(\"wakingUp\"),this.cameraManager.resumeStream(),await this.setCurrentState(\"on\"));}async isAndroidWebView(){return this._isAndroidWebView==null&&(this._isAndroidWebView=await a$2.isAndroidWebView()),this._isAndroidWebView}};\n\nexport { g as a };\n", "import { a as a$1 } from './chunk-45EBHQYM.js';\nimport { d } from './chunk-SK45SCLY.js';\nimport { a } from './chunk-SP3HSP4K.js';\nimport { a as a$2 } from './chunk-PSQ6LAQA.js';\nimport { f, g as g$1 } from './chunk-36CGJKPG.js';\n\nvar g=(t=>(t.Idle=\"idle\",t.Pressed=\"pressed\",t))(g||{}),c=class{constructor(e,t){this.state=\"idle\";this.isHover=!1;this.control=e,this.domHost=t,this.onTouchStartListener=this.onTouchStart.bind(this),this.onMouseEnterListener=this.onMouseEnter.bind(this),this.onMouseLeaveListener=this.onMouseLeave.bind(this),this.onClickListener=this.onClick.bind(this),this.setup();}get frameSource(){var e,t;return (t=(e=this.control.view)==null?void 0:e.getContext())==null?void 0:t.frameSource}get context(){var e;return (e=this.control.view)==null?void 0:e.getContext()}async install(){this.button||this.setup();let e=await this.canShow();return e?(this.updateButtonBackground(this.button,this.getImageFromState()),this.show()):this.hide(),e}remove(e=!1){e&&this.button?(this.button.removeEventListener(\"mouseenter\",this.onMouseEnterListener),this.button.removeEventListener(\"mouseleave\",this.onMouseLeaveListener),this.button.removeEventListener(\"touchstart\",this.onTouchStartListener),this.button.removeEventListener(\"click\",this.onClickListener),this.button.remove(),this.isHover=!1,this.button=void 0):this.hide();}hide(){this.button&&(this.button.style.display=\"none\");}show(){this.button&&(this.button.style.display=\"block\");}setupButton(){let e=document.createElement(\"button\");return e.type=\"button\",e.style.display=\"none\",e.className=`scandit-control-widget scandit-control-widget-${this.control.type}`,this.updateButtonBackground(e,this.getImageFromState()),this.domHost.append(e),e.addEventListener(\"mouseenter\",this.onMouseEnterListener),e.addEventListener(\"mouseleave\",this.onMouseLeaveListener),a$2.isDesktopDevice()||e.addEventListener(\"touchstart\",this.onTouchStartListener),e.addEventListener(\"click\",this.onClickListener),e.setAttribute(\"aria-pressed\",String(this.state===\"pressed\")),this.button=e,this.button}setup(){this.setupButton();}onTouchStart(){var e,t;(e=this.button)==null||e.removeEventListener(\"mouseenter\",this.onMouseEnterListener),(t=this.button)==null||t.removeEventListener(\"mouseleave\",this.onMouseLeaveListener);}onMouseEnter(){this.isHover=!0,this.updateButtonBackground(this.button,this.getImageFromState());}onMouseLeave(){this.isHover=!1,this.updateButtonBackground(this.button,this.getImageFromState());}onClick(){var e;this.state=this.state===\"pressed\"?\"idle\":\"pressed\",this.buttonClicked(),this.updateButtonBackground(this.button,this.getImageFromState()),(e=this.button)==null||e.setAttribute(\"aria-pressed\",String(this.state===\"pressed\"));}updateButtonBackground(e,t){t!=null&&e!=null&&(e.style.backgroundImage=`url(${JSON.stringify(t)})`);}},p=class extends c{constructor(e,t){super(e,t);}async buttonClicked(){await this.frameSource.setDesiredTorchState(this.retrieveTorchState()===\"on\"?\"off\":\"on\");}async canShow(){return this.isTorchAvailable()}getImageFromState(){return this.retrieveTorchState()===\"on\"?this.isHover?this.control.torchOnPressedImage:this.control.torchOnImage:this.isHover?this.control.torchOffPressedImage:this.control.torchOffImage}setup(){if(this.control.torchOffImage==null||this.control.torchOnImage==null){a.log(a.Level.Warn,\"TorchSwitchControl icon is not set or is empty, the control will not be rendered.\");return}super.setup();}async isTorchAvailable(){return f(this.frameSource)?this.frameSource.isTorchAvailable():!1}retrieveTorchState(){return f(this.frameSource)?this.frameSource.getDesiredTorchState():\"off\"}},v=class s extends c{constructor(e,t){super(e,t);}static get Camera(){return a$1}static get CameraAccess(){return d}async canShow(){return (await s.CameraAccess.getCameras()).length>1}getImageFromState(){return this.isHover?this.control.pressedImage:this.control.idleImage}async buttonClicked(){if(this.isTransitioning)return;let e=await this.getNextDeviceCamera();e&&await this.switchCameras(e);}setup(){if(this.control.idleImage==null){a.log(a.Level.Warn,\"CameraSwitchControl idle icon is not set or is empty, the control will not be rendered.\");return}super.setup();}async getNextDeviceCamera(){var l,h;let e=await s.CameraAccess.getCameras(),t=this.frameSource?this.frameSource:null,r=(l=t==null?void 0:t.cameraManager.activeCamera)==null?void 0:l.deviceId,a=e.findIndex(f=>f.deviceId===r);return a>-1?(h=e[a+1])!=null?h:e[0]:e.length>0?e[0]:null}async switchCameras(e){var a;this.isTransitioning=!0;let t=this.frameSource;t!=null&&await t.switchToDesiredState(\"off\");let r=new s.Camera;r.deviceId=e.deviceId,t!=null&&await r.applySettings(new g$1(t.settings)),await r.switchToDesiredState(\"on\"),await((a=this.context)==null?void 0:a.setFrameSource(r)),this.isTransitioning=!1;}},C=class s extends c{constructor(e,t){super(e,t);}static get Camera(){return a$1}static get CameraAccess(){return d}async install(){let e=await super.install();return e&&await this.setInitialCamera(),e}async canShow(){return !a$2.isIOSDeviceWithExtendedCameraAccess()||!f(this.frameSource)?!1:d.isIOSBackDualWideCameraLabel(this.frameSource.label)||d.isIOSBackCameraLabel(this.frameSource.label)||d.isIOSUltraWideBackCameraLabel(this.frameSource.label)}getImageFromState(){return this.isUltraWideBackCamera()?this.isHover?this.control.cameraFOVUltraWidePressedImage:this.control.cameraFOVUltraWideImage:this.isHover?this.control.cameraFOVWidePressedImage:this.control.cameraFOVWideImage}async buttonClicked(){if(this.isTransitioning)return;let e=await this.getAlternativeDeviceCamera();e&&await this.switchCameras(e);}async setInitialCamera(){var e,t;if(!this.isTransitioning&&!d.isIOSBackCameraLabel((t=(e=this.frameSource)==null?void 0:e.label)!=null?t:\"\")){let a=(await s.CameraAccess.getCameras()).find(l=>d.isIOSBackCameraLabel(l.label));a&&await this.switchCameras(a);}}setup(){if(this.control.cameraFOVUltraWideImage==null||this.control.cameraFOVWideImage==null){a.log(a.Level.Warn,\"CameraFOVSwitchControl icon is not set or is empty, the control will not be rendered.\");return}super.setup();}isUltraWideBackCamera(){return f(this.frameSource)?d.isIOSUltraWideBackCameraLabel(this.frameSource.label):!1}async getAlternativeDeviceCamera(){return (await s.CameraAccess.getCameras()).find(t=>this.isUltraWideBackCamera()?d.isIOSBackCameraLabel(t.label):d.isIOSUltraWideBackCameraLabel(t.label))}async switchCameras(e){var a;this.isTransitioning=!0;let t=this.frameSource;t!=null&&await t.switchToDesiredState(\"off\");let r=new s.Camera;r.deviceId=e.deviceId,t!=null&&await r.applySettings(new g$1(t.settings)),await r.switchToDesiredState(\"on\"),await((a=this.context)==null?void 0:a.setFrameSource(r)),this.isTransitioning=!1;}};\n\nexport { g as a, p as b, v as c, C as d };\n", "import { a } from './chunk-NMX4VHW2.js';\n\nfunction A(){return `\n .${a.CONTAINER_CLASS_NAME}::before {\n content: \" \";\n position: absolute;\n top: 0;\n left: 0;\n width: 1px;\n height: 1px;\n background-color: white;\n pointer-events: none;\n opacity: 0;\n animation: scandit-rotation 1s linear infinite;\n }\n\n @keyframes scandit-rotation {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n }\n\n .${a.CONTAINER_CLASS_NAME} {\n display: flex;\n /* Without this the flex child overflows its parent on Chrome mobile: */\n flex-direction: column;\n width: 100%;\n height: 100%;\n align-items: center;\n justify-content: center;\n overflow: hidden;\n }\n\n .${a.PAINTBOARDS_CONTAINER_CLASS_NAME} {\n position: relative;\n width: 100%;\n height: inherit;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} {\n position: relative;\n width: 100%;\n height: 100%;\n min-width: 1px;\n min-height: 1px;\n background-color: black;\n aspect-ratio: 16 / 9;\n }\n\n .${a.PAINTBOARD_CLASS_NAME}.${a.PAINTBOARD_CLASS_NAME_STATE_ON} {\n aspect-ratio: auto\n }\n\n .${a.PAINTBOARD_CLASS_NAME} video {\n display: block;\n width: 100%;\n height: 100%;\n object-fit: cover;\n transition: opacity 300ms;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.MIRRORED_CLASS_NAME} {\n transform: scale(-1, 1);\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.CAMERA_RECOVERY_CLASS_NAME} {\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n display: flex;\n justify-content: center;\n align-items: center;\n z-index: 5;\n cursor: pointer;\n background-color: #000;\n color: #fff;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.ERROR_CLASS_NAME} {\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n display: flex;\n justify-content: center;\n align-items: center;\n text-align: center;\n z-index: 6;\n color: white;\n background-color: rgba(0,0,0,0.5);\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.HINT_CONTAINER_CLASS_NAME} {\n position: absolute;\n width: 100%;\n top: 5vh;\n bottom: 5vh;\n display: grid;\n pointer-events: none;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.HINT_CLASS_NAME} {\n width: fit-content;\n color: black;\n background-color: white;\n padding: 10px;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.CAMERA_RECOVERY_CLASS_NAME}[hidden],\n .${a.PAINTBOARD_CLASS_NAME} .${a.ERROR_CLASS_NAME}[hidden] {\n display: none;\n }\n .${a.PAINTBOARD_CLASS_NAME} .${a.HINT_CLASS_NAME}[hidden] {\n display: none;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} canvas {\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n object-fit: cover;\n transition: opacity 300ms;\n pointer-events: none;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.CONTROLS_CLASS_NAME} {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n display: flex;\n /* let events pass through */\n pointer-events: none;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} [class^=\"${a.CONTROL_WIDGET_CLASS_NAME}\"] {\n position: absolute;\n pointer-events: all;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.CONTROL_WIDGET_CLASS_NAME}-${a.TORCH_SWITCH_CONTROL_CLASS_NAME} {\n top: 24px;\n left: 16px;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.CONTROL_WIDGET_CLASS_NAME}-${a.CAMERA_SWITCH_CONTROL_CLASS_NAME} {\n top: 24px;\n right: 16px;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.CONTROL_WIDGET_CLASS_NAME}-${a.CAMERA_FOV_SWITCH_CONTROL_CLASS_NAME} {\n bottom: 24px;\n right: 24px;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.SINGLE_IMAGE_UPLOADER_CONTAINER_CLASS_NAME} {\n -webkit-tap-highlight-color: rgba(255, 255, 255, 0);\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n width: 100%;\n height: 100%;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.SINGLE_IMAGE_UPLOADER_CONTAINER_CLASS_NAME} label {\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n cursor: pointer;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.SINGLE_IMAGE_UPLOADER_CONTAINER_CLASS_NAME} label input[type=\"file\"] {\n position: absolute;\n top: -9999px;\n }\n\n .${a.PAINTBOARD_CLASS_NAME} .${a.SINGLE_IMAGE_UPLOADER_CONTAINER_CLASS_NAME} label button {\n pointer-events: none;\n }\n\n .${a.CONTROL_WIDGET_CLASS_NAME} {\n width: 32px;\n height: 32px;\n background-color: transparent;\n background-repeat: no-repeat;\n border: none;\n cursor: pointer;\n }\n\n .${a.CONTROL_WIDGET_CLASS_NAME} + .${a.CONTROL_WIDGET_CLASS_NAME} {\n margin-left: 16px;\n }\n\n .${a.FROZEN_FRAME} {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n object-fit: cover;\n opacity: 1;\n }\n\n .${a.FROZEN_FRAME}[hidden] {\n opacity: 0;\n pointer-events: none;\n visibility: hidden;\n }\n `}\n\nexport { A as a };\n", "var e=new Set,t=e;\n\nexport { t as a };\n", "import { h, d } from './chunk-N4NOODAT.js';\n\nvar o=class c{constructor(e){this.element=e,this.setupListeners(),this.cacheDOMRect();}get width(){return this.cachedDOMRect.width}get height(){return this.cachedDOMRect.height}static areEquivalentJSONStates(e,t){return !e||!t?!1:e.size.isSameAs(t.size)&&e.visible===t.visible}onStateChanged(e){this.onStateChangedListener=e;}onDisconnected(e){this.onDisconnectedListener=e;}toJSONObject(){return {size:new h(new d(this.width,\"pixel\"),new d(this.height,\"pixel\")),visible:this.isVisible()}}isSameAs(e){return c.areEquivalentJSONStates(this.toJSONObject(),e.toJSONObject())}removeListeners(){this.resizeObserver.disconnect(),this.mutationObserver.disconnect();}isVisible(){return this.width>0&&this.height>0||this.element.getClientRects().length>0}setupListeners(){this.resizeObserver=new ResizeObserver(this.onSizeChange.bind(this)),this.resizeObserver.observe(this.element),this.mutationObserver=new MutationObserver(this.onMutation.bind(this)),this.element.parentElement&&this.mutationObserver.observe(this.element.parentElement,{childList:!0});}onSizeChange(e){var t;this.cacheDOMRect(e),document.contains(this.element)&&((t=this.onStateChangedListener)==null||t.call(this));}onMutation(e){var s;let t=e.find(({type:i})=>i===\"childList\");if(t){for(let i of t.removedNodes)if(i===this.element&&!document.contains(this.element)){(s=this.onDisconnectedListener)==null||s.call(this);return}}}cacheDOMRect(e){let t;Array.isArray(e)&&e.length>0&&(t=e[0].contentRect),t==null&&(t=this.element.getBoundingClientRect()),this.cachedDOMRect=t;}};\n\nexport { o as a };\n", "var e={SINGLE_IMAGE_UPLOADER_CONTAINER:\"scandit-single-image-uploader-container\"},t={SINGLE_IMAGE_UPLOADER_CONTAINER_STYLE:{backgroundColor:\"#FFFFFF\"},SINGLE_IMAGE_UPLOADER_ICON_STYLE:{fill:\"#121619\"},SINGLE_IMAGE_UPLOADER_INFORMATION_STYLE:{color:\"#121619\",marginBottom:\"2em\"},SINGLE_IMAGE_UPLOADER_BUTTON_STYLE:{color:\"#FFFFFF\",backgroundColor:\"#121619\",fontWeight:\"bold\",padding:\"1.25em\",width:\"12em\",textAlign:\"center\",textTransform:\"uppercase\"}},E=`\n .${e.SINGLE_IMAGE_UPLOADER_CONTAINER} {\n -webkit-tap-highlight-color: rgba(255, 255, 255, 0);\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n width: 100%;\n height: 100%;\n }\n\n .${e.SINGLE_IMAGE_UPLOADER_CONTAINER} label {\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n }\n\n .${e.SINGLE_IMAGE_UPLOADER_CONTAINER} label input[type=\"file\"] {\n position: absolute;\n top: -9999px;\n }\n\n .${e.SINGLE_IMAGE_UPLOADER_CONTAINER} label div {\n user-select: none;\n }\n\n .${e.SINGLE_IMAGE_UPLOADER_CONTAINER} label input[type=\"file\"]:disabled + div {\n opacity: 0.5;\n }\n`;\n\nexport { e as a, t as b, E as c };\n", "import { c, a, b } from './chunk-JFRSUCMO.js';\nimport { a as a$1 } from './chunk-DTSV5FYV.js';\nimport { a as a$2 } from './chunk-SP3HSP4K.js';\nimport { c as c$1 } from './chunk-AXTXPLXP.js';\n\nvar s=class s{constructor(e){this.canUploadFile=!1;this._mounted=!1;this._loading=!1;this._htmlRoot=void 0;this._canvas=void 0;this._onInputCheck=void 0;this._onBeforeFileRead=void 0;this._onImageLoadError=void 0;this._onFileReaderError=void 0;this._onCaptureReady=void 0;this._resizedImageSizeLimit=1440;this._inputElement=void 0;this._buttonElement=void 0;this._chooseImageText=\"\";this._settings=e;}get canvas(){return this._canvas||(this._canvas=document.createElement(\"canvas\")),this._canvas}get canvasContext(){return this._canvasContext||(this._canvasContext=this.canvas.getContext(\"2d\",{willReadFrequently:!0})),this._canvasContext}mount(e){var E;if(this._mounted)return;if(!document.head.querySelector(`[data-component=${s.componentName}]`)){let o=document.createElement(\"style\");o.dataset.component=s.componentName,o.textContent=c,document.head.append(o);}let t=document.createElement(\"div\");t.className=a.SINGLE_IMAGE_UPLOADER_CONTAINER,Object.assign(t.style,b.SINGLE_IMAGE_UPLOADER_CONTAINER_STYLE,this._settings.containerStyle),e.append(t);let{iconElement:n,iconStyle:d,informationElement:i,informationStyle:u,buttonElement:r,buttonStyle:c$2,onlyCameraCapture:b$1}=this._settings;Object.assign(n.style,b.SINGLE_IMAGE_UPLOADER_ICON_STYLE,d,{maxWidth:\"100px\",maxHeight:\"100px\"}),t.append(n),i.hasAttribute(s.DEFAULT_DOM_ATTRIBUTE)&&(Object.assign(i.style,b.SINGLE_IMAGE_UPLOADER_INFORMATION_STYLE,u),i.textContent=a$1.getInstance().get(\"core.singleImageUploader.title\")),t.append(i);let a$2=document.createElement(\"input\");a$2.type=\"file\",a$2.accept=\"image/*\",b$1&&(a$2.capture=\"environment\",a$2.dataset.onlyCaptureOnMobile=\"environment\"),a$2.addEventListener(\"change\",o=>{this.onFileUpload(o);}),a$2.addEventListener(\"click\",o=>{var l;(l=this._onInputCheck)==null||l.call(this,o);}),a$2.addEventListener(\"keydown\",o=>{var l;(l=this._onInputCheck)==null||l.call(this,o);});let p=document.createElement(\"label\");p.append(a$2),r.hasAttribute(s.DEFAULT_DOM_ATTRIBUTE)&&(Object.assign(r.style,b.SINGLE_IMAGE_UPLOADER_BUTTON_STYLE,c$2),r.textContent=a$1.getInstance().get(\"core.singleImageUploader.button\")),p.append(r),t.append(p);let v=document.createRange().createContextualFragment(atob(c$1)).firstElementChild;Object.assign(v.style,{position:\"absolute\",bottom:\"1em\",right:\"1em\",width:\"10em\"}),t.append(v),this._htmlRoot=t,this._mounted=!0,this._inputElement=a$2,this._buttonElement=r,this._chooseImageText=(E=r.textContent)!=null?E:\"\";}unmount(){var e,t;this._mounted&&((e=this._htmlRoot)==null||e.remove(),(t=document.head.querySelector(`[data-component=${s.componentName}]`))==null||t.remove(),this._mounted=!1);}setButtonState(e){this._inputElement&&(this._inputElement.disabled=e===\"disabled\");}getButtonState(){return this._inputElement?this._inputElement.disabled?\"disabled\":\"enabled\":\"disabled\"}getLastUploadedImage(){return this.canvasContext.getImageData(0,0,this.canvasContext.canvas.width,this.canvasContext.canvas.height)}onInputCheck(e){this._onInputCheck=e;}onBeforeFileRead(e){this._onBeforeFileRead=e;}onImageLoadError(e){this._onImageLoadError=e;}onFileReaderError(e){this._onFileReaderError=e;}onCaptureReady(e){this._onCaptureReady=e;}onAfterImageProcessed(){this.setLoading(!1);}setLoading(e){this._buttonElement&&(this.setButtonState(e?\"disabled\":\"enabled\"),this._buttonElement.textContent=e?\"...\":this._chooseImageText,this._loading=e);}getResizedImageDimensions(e,t){return e<=this._resizedImageSizeLimit&&t<=this._resizedImageSizeLimit?{width:e,height:t}:e>t?{width:this._resizedImageSizeLimit,height:Math.round(t/e*this._resizedImageSizeLimit)}:{width:Math.round(e/t*this._resizedImageSizeLimit),height:this._resizedImageSizeLimit}}onImageLoad(e){var i;let{height:t,width:n}=this.getResizedImageDimensions(e.naturalWidth,e.naturalHeight);this.canvasContext.canvas.width=n,this.canvasContext.canvas.height=t,this.canvasContext.drawImage(e,0,0,n,t);let d={data:this.canvasContext.getImageData(0,0,n,t).data,width:n,height:t};(i=this._onCaptureReady)==null||i.call(this,d);}onFileReaderLoad(e,t,n){e.value=\"\",t.result!=null&&(n.addEventListener(\"load\",()=>{this.onImageLoad(n);},{once:!0}),n.addEventListener(\"error\",d=>{var i;(i=this._onImageLoadError)==null||i.call(this,d),this.setLoading(!1);},{once:!0}),n.src=t.result);}onFileUpload(e){var u;this.setLoading(!0);let t=e.currentTarget,{files:n}=t;if(n==null||n.length===0){this.setLoading(!1);return}if((u=this._onBeforeFileRead)==null||u.call(this,e),!this.canUploadFile){t.value=\"\",a$2.log(a$2.Level.Warn,\"Can't upload file, no capture mode enabled.\"),this.setLoading(!1);return}let d=new Image,i=new FileReader;i.addEventListener(\"load\",()=>{this.onFileReaderLoad(t,i,d);}),i.addEventListener(\"error\",r=>{var c;(c=this._onFileReaderError)==null||c.call(this,r),this.setLoading(!1);}),i.readAsDataURL(n[0]);}};s.componentName=\"SingleImageUploaderView\",s.DEFAULT_DOM_ATTRIBUTE=\"data-scandit-default\";var f=s;\n\nexport { f as a };\n", "import { b } from './chunk-FTD535WI.js';\n\nvar l=(e=>(e.Nonzero=\"nonzero\",e.Evenodd=\"evenodd\",e))(l||{}),c=class{constructor(){this.pathWinding=\"nonzero\";}drawSingleCommand(t,e){switch(t){case 0:{this.addLine(e);break}case 1:{this.addArc(e);break}case 2:{this.addCircle(e);break}case 3:{this.addRectangle(e);break}case 4:{this.addRoundedRectangle(e);break}case 5:{this.beginPath(e);break}case 6:{this.closePath(e);break}case 7:{this.fill(e);break}case 8:{this.stroke(e);break}case 10:{this.setStrokeWidth(e);break}case 11:{this.setFillColor(e);break}case 12:{this.setStrokeColor(e);break}case 13:{this.moveTo(e);break}case 14:{this.lineTo(e);break}case 15:{this.saveState(e);break}case 16:{this.restoreState(e);break}case 17:{this.translate(e);break}case 19:{this.bezierTo(e);break}case 20:{this.transform(e);break}case 21:{this.scale(e);break}case 22:{this.addPathWinding(e);break}case 9:case 18:break;default:{b(t);break}}}beginPath(t){this.context.beginPath();}closePath(t){this.context.closePath();}setStrokeColor(t){let e=t.extractColor();this.context.strokeStyle=this.colorToRgbaString(e);}setFillColor(t){let e=t.extractColor();this.context.fillStyle=this.colorToRgbaString(e);}fill(t){this.context.fill(this.pathWinding);}stroke(t){this.context.stroke();}addLine(t){let e=t.extractFloat(),a=t.extractFloat();this.context.moveTo(e,a);let o=t.extractFloat(),r=t.extractFloat();this.context.lineTo(o,r);}lineTo(t){let e=t.extractFloat(),a=t.extractFloat();this.context.lineTo(e,a);}moveTo(t){let e=t.extractFloat(),a=t.extractFloat();this.context.moveTo(e,a);}addRectangle(t){let e=t.extractFloat(),a=t.extractFloat(),o=t.extractFloat(),r=t.extractFloat();this.context.rect(e,a,o,r);}addRoundedRectangle(t){let e=t.extractFloat(),a=t.extractFloat(),o=t.extractFloat(),r=t.extractFloat(),i=t.extractFloat();this.context.moveTo(e+i,a),this.context.lineTo(e+o-i,a),this.context.quadraticCurveTo(e+o,a,e+o,a+i),this.context.lineTo(e+o,a+r-i),this.context.quadraticCurveTo(e+o,a+r,e+o-i,a+r),this.context.lineTo(e+i,a+r),this.context.quadraticCurveTo(e,a+r,e,a+r-i),this.context.lineTo(e,a+i),this.context.quadraticCurveTo(e,a,e+i,a),this.context.closePath();}setStrokeWidth(t){this.context.lineWidth=t.extractFloat();}addArc(t){let e=t.extractFloat(),a=t.extractFloat(),o=t.extractFloat(),r=t.extractFloat(),i=t.extractFloat(),s=t.extractBoolean();this.context.arc(e,a,o,r,i,s);}addCircle(t){let e=t.extractFloat(),a=t.extractFloat(),o=t.extractFloat();this.context.arc(e,a,o,0,Math.PI*2);}bezierTo(t){let e=t.extractFloat(),a=t.extractFloat(),o=t.extractFloat(),r=t.extractFloat(),i=t.extractFloat(),s=t.extractFloat();this.context.bezierCurveTo(e,a,o,r,i,s);}saveState(t){this.context.save();}restoreState(t){this.context.restore();}translate(t){let e=t.extractFloat(),a=t.extractFloat();this.context.translate(e,a);}transform(t){let e=t.extractFloat(),a=t.extractFloat(),o=t.extractFloat(),r=t.extractFloat(),i=t.extractFloat(),s=t.extractFloat();this.context.transform(e,a,o,r,i,s);}scale(t){let e=t.extractFloat();this.context.scale(e,e);}addPathWinding(t){let e=t.extractBoolean();this.pathWinding=e?\"nonzero\":\"evenodd\";}colorToRgbaString(t){return `rgba(${t.r},${t.g},${t.b},${t.a})`}};\n\nexport { l as a, c as b };\n", "var h=(e=>(e[e.AddLine=0]=\"AddLine\",e[e.AddArc=1]=\"AddArc\",e[e.AddCircle=2]=\"AddCircle\",e[e.AddRect=3]=\"AddRect\",e[e.AddRoundedRect=4]=\"AddRoundedRect\",e[e.BeginPath=5]=\"BeginPath\",e[e.ClosePath=6]=\"ClosePath\",e[e.Fill=7]=\"Fill\",e[e.Stroke=8]=\"Stroke\",e[e.Clear=9]=\"Clear\",e[e.SetStrokeWidth=10]=\"SetStrokeWidth\",e[e.SetFillColor=11]=\"SetFillColor\",e[e.SetStrokeColor=12]=\"SetStrokeColor\",e[e.MoveTo=13]=\"MoveTo\",e[e.LineTo=14]=\"LineTo\",e[e.SaveState=15]=\"SaveState\",e[e.RestoreState=16]=\"RestoreState\",e[e.Translate=17]=\"Translate\",e[e.ScaleAroundPoint=18]=\"ScaleAroundPoint\",e[e.BezierTo=19]=\"BezierTo\",e[e.Transform=20]=\"Transform\",e[e.Scale=21]=\"Scale\",e[e.AddPathWinding=22]=\"AddPathWinding\",e))(h||{}),i=class{constructor(t){this._index=0;this._view=new DataView(t.buffer),this._index=0;}extractCommandType(){let t=this._view.getUint8(this._index);return this._index+=1,t}extractFloat(){let t=this._view.getFloat32(this._index,!0);return this._index+=4,t}extractBoolean(){let t=this._view.getUint8(this._index);return this._index+=1,t!==0}extractColor(){let t=this._view.getUint8(this._index),s=this._view.getUint8(this._index+1),l=this._view.getUint8(this._index+2),c=this._view.getUint8(this._index+3)/256;return this._index+=4,{r:t,g:s,b:l,a:c}}isConsumed(){return this._index>=this._view.byteLength}};\n\nexport { h as a, i as b };\n", "import { b } from './chunk-QBDQQMQ5.js';\nimport { b as b$1 } from './chunk-LA6TM76R.js';\n\nvar d=(e=>(e.Nonzero=\"nonzero\",e.Evenodd=\"evenodd\",e))(d||{}),n=class n extends b{constructor(e){super();this._context=null;this.isNextDrawPending=!1;this.latestCommands=new Uint8Array([]);this.canvas=e,this.doDrawLoop=this.doDraw.bind(this);}get context(){if(!this._context&&(this._context=this.canvas.getContext(\"2d\"),!this._context))throw new TypeError(\"CanvasRenderingContext cannot be retrieved.\");return this._context}draw(e){if(this.latestCommands=e,!this.isCanvasReady()){this.postponeDraw();return}this.isNextDrawPending||(this.isNextDrawPending=!0,requestAnimationFrame(this.doDrawLoop));}updateCanvasSizeAttributes(e,s,t=window.devicePixelRatio){let i=Math.round(e*t),r=Math.round(s*t);(i!==this.canvas.width||r!==this.canvas.height)&&(this.canvas.width=i,this.canvas.height=r,this.context.scale(t,t));}startObservingCanvasResize(){if(!this.resizeObserver){if(!n.ResizeObserver)throw new Error(\"PrivateCanvasDrawer.ResizeObserver is not set\");this.resizeObserver=new n.ResizeObserver(e=>{var r;let[s]=e,{width:t,height:i}=(r=s.contentRect)!=null?r:this.canvas;t===0||i===0||(this.updateCanvasSizeAttributes(t,i),this.latestCommands.length!==0&&(this.draw(this.latestCommands),this.latestCommands=new Uint8Array([])));}),this.resizeObserver.observe(this.canvas);}}endObservingCanvasResize(){this.resizeObserver&&this.resizeObserver.unobserve(this.canvas);}doDraw(){this.context.clearRect(0,0,this.canvas.width,this.canvas.height);let e=new b$1(this.latestCommands);for(;!e.isConsumed();){let s=e.extractCommandType();this.drawSingleCommand(s,e);}this.isNextDrawPending=!1;}postponeDraw(){this.startObservingCanvasResize();}isCanvasReady(){return this.canvas.width>0&&this.canvas.height>0}};n.ResizeObserver=\"ResizeObserver\"in globalThis?globalThis.ResizeObserver:void 0;var h=n;\n\nexport { d as a, h as b };\n", "import { b } from './chunk-457L5N2F.js';\nimport { a } from './chunk-SP3HSP4K.js';\n\nvar d={processedFramesCount:{text:\"Frames processed by engine\",valueSuffix:\"/sec\"},frameDataPoolSize:{text:\"Frame data pool size\",valueSuffix:\"\"},redrawRequestsCount:{text:\"Engine redraw requests\",valueSuffix:\"/sec\"},actualRedrawsCount:{text:\"Actual redraws\",valueSuffix:\"/sec\"},FPS:{text:\"Overlay FPS \",valueSuffix:\"/sec\"}},p=class extends b{constructor(e){var r;super(e);this.drawPerformanceTimer=null;this.drawPerformanceFPSCounter=0;this.lastDrawPerformanceFPSCounter=0;this.performanceCanvasLayer=document.createElement(\"canvas\"),(r=e.parentElement)==null||r.insertBefore(this.performanceCanvasLayer,e);}get performanceLayerContext(){if(!this._performanceLayerContext&&(this._performanceLayerContext=this.performanceCanvasLayer.getContext(\"2d\"),!this._performanceLayerContext))throw new TypeError(\"CanvasRenderingContext cannot be retrieved.\");return this._performanceLayerContext}setupPerformanceLayer(){}setPerformanceMetrics(e){this.performanceMetrics=e,this.drawPerformanceMetrics();}updateCanvasSizeAttributes(e,r,t=window.devicePixelRatio){super.updateCanvasSizeAttributes(e,r,t),this.performanceCanvasLayer.width=this.canvas.width,this.performanceCanvasLayer.height=this.canvas.height,this.performanceLayerContext.scale(t,t);}doDraw(){super.doDraw();}drawPerformanceMetrics(){this.drawPerformanceTimer==null&&(a.log(a.Level.Debug,\"Drawing performance monitoring enabled, FPS will be drawn into canvas\"),this.drawPerformanceTimer=setInterval(()=>{this.lastDrawPerformanceFPSCounter=this.drawPerformanceFPSCounter,this.drawPerformanceFPSCounter=0;},1e3)),this.drawPerformanceFPSCounter++,this.drawFullPerformanceMetrics();}drawFullPerformanceMetrics(){let e={...this.performanceMetrics,FPS:this.lastDrawPerformanceFPSCounter};this.performanceLayerContext.lineWidth=1,this.performanceLayerContext.fillStyle=\"white\",this.performanceLayerContext.strokeStyle=\"black\";let r=Math.min(Math.max(window.innerWidth/35,13),20),t=1.5*r,s=1.5;this.performanceLayerContext.font=`bold ${r}px sans-serif`;let l=0,n=0,i=[];for(let[a,u]of Object.entries(e)){let c=d[a],f=`${c.text}: ${u}${c.valueSuffix}`;n=Math.max(this.performanceLayerContext.measureText(f).width,n),i.push([f,t,t+r*s*l++]);}this.performanceLayerContext.clearRect(t,t-r,n,Object.values(e).length*r*s);for(let a of i)this.performanceLayerContext.fillText(...a),this.performanceLayerContext.strokeText(...a);}};\n\nexport { p as a };\n", "var t=class t{constructor(){this.hasApi=!1;this.hasTouch=!1;this.requiresPrefix=!1;}detect(){var e;try{\"PointerEvent\"in window?this.hasApi=!0:\"msPointerEnabled\"in navigator&&(this.hasApi=!0,this.requiresPrefix=!0);let o=(e=navigator.msMaxTouchPoints)!=null?e:navigator.maxTouchPoints;this.hasTouch=o>0;}catch(o){}}prefixIfNeeded(e){return this.requiresPrefix?t.prefixEventMap[e]:e}};t.prefixEventMap={pointerdown:\"MSPointerDown\",pointerup:\"MSPointerUp\",pointercancel:\"MSPointerCancel\",pointermove:\"MSPointerMove\",pointerover:\"MSPointerOver\",pointerout:\"MSPointerOut\",pointerenter:\"MSPointerEnter\",pointerleave:\"MSPointerLeave\",gotpointercapture:\"MSGotPointerCapture\",lostpointercapture:\"MSLostPointerCapture\"};var n=t,i=new n;\n\nexport { i as a };\n", "var t=class{constructor(){this._listeners=new Set;}get listeners(){return [...this._listeners]}addListener(e){this._listeners.add(e);}removeListener(e){this._listeners.delete(e);}};\n\nexport { t as a };\n", "import { a as a$1 } from './chunk-IGJQFAQU.js';\nimport { a } from './chunk-EP3GI7KA.js';\nimport { a as a$2 } from './chunk-N4NOODAT.js';\n\nvar v=class extends a{constructor(e){super();this._onTouchStart=this.onTouchStart.bind(this);this._onPointerDown=this.onPointerDown.bind(this);a$1.detect(),this.element=e,this.addPointerDownListener();}removeAllListeners(){this.element.removeEventListener(\"touchend\",this._onTouchStart),this.element.removeEventListener(\"mousedown\",this._onPointerDown),this.element.removeEventListener(\"pointerdown\",this._onPointerDown);}addPointerDownListener(){a$1.hasApi?this.element.addEventListener(a$1.prefixIfNeeded(\"pointerdown\"),this._onPointerDown):a$1.hasTouch?this.element.addEventListener(\"touchstart\",this._onTouchStart):this.element.addEventListener(\"mousedown\",this._onPointerDown);}onPointerDown(e){let{clientX:n,clientY:t,button:o,currentTarget:a=this.element}=e;o===0&&this.onTap(this.pointRelativeToElement({clientX:n,clientY:t,rect:a.getBoundingClientRect()}),e);}onTouchStart(e){let[n]=e.touches,{clientX:t,clientY:o}=n;this.onTap(this.pointRelativeToElement({clientX:t,clientY:o,rect:this.element.getBoundingClientRect()}),e);}pointRelativeToElement({clientX:e,clientY:n,rect:t}){return new a$2(e-t.left,n-t.top)}onTap(e,n){var t;for(let o of this.listeners)(t=o.onTap)==null||t.call(o,e,n);}};\n\nexport { v as a };\n", "var e={CUSTOM_VIEW_CONTAINER:\"scandit-custom-views\"},t=`\n .${e.CUSTOM_VIEW_CONTAINER} {\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n }\n .${e.CUSTOM_VIEW_CONTAINER} img {\n position: absolute;\n -webkit-tap-highlight-color: transparent;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n }\n`,s=t;\n\nexport { e as a, s as b };\n", "import { a as a$1 } from './chunk-XVLYCDJL.js';\nimport { b as b$1, a } from './chunk-KYNYQBNF.js';\nimport { i, a as a$2 } from './chunk-N4NOODAT.js';\n\nvar b={bottomLeft:\"bottomRight\",bottomRight:\"bottomLeft\",topLeft:\"topRight\",topRight:\"topLeft\",centerLeft:\"centerRight\",centerRight:\"centerLeft\",center:\"center\",topCenter:\"topCenter\",bottomCenter:\"bottomCenter\"},s=class s{constructor(){this.listener=null;this._mounted=!1;this._mirrored=!1;this._cachedSize=new i(0,0);this.resizeObserver=null;this.mapViewAnchorPositionsForFramePoint=e=>e;}get size(){return this._cachedSize}setMirrored(e){this._mounted&&(this._mirrored=e);}mount(e){var o;if(this._mounted)return;if(!document.head.querySelector(`[data-component=${s.componentName}]`)){let t=document.createElement(\"style\");t.dataset.component=s.componentName,t.append(document.createTextNode(b$1)),document.head.append(t);}let n=document.createElement(\"div\");n.classList.add(a.CUSTOM_VIEW_CONTAINER),(o=e.parentNode)==null||o.replaceChild(n,e),this._htmlRoot=n,this.gestureRecognizer=new a$1(this._htmlRoot),this.gestureRecognizer.addListener({onTap:(t,r)=>{var l,i;let m=(l=r.target.dataset.identifier)!=null?l:\"\";m!==\"\"&&((i=this.listener)==null||i.didTapView(Number.parseInt(m,10)));}}),this.resizeObserver=new ResizeObserver(([t])=>{this._cachedSize=new i(t.contentRect.width,t.contentRect.height);}),this.resizeObserver.observe(this._htmlRoot),this._cachedSize=new i(this._htmlRoot.clientWidth,this._htmlRoot.clientHeight),this._mounted=!0;}unmount(){var e,n,o,t;this._mounted&&(this.removeChildren(),(e=this.gestureRecognizer)==null||e.removeAllListeners(),(n=this.resizeObserver)==null||n.disconnect(),(o=this._htmlRoot)==null||o.remove(),this._htmlRoot=null,this.gestureRecognizer=null,(t=document.head.querySelector(`[data-component=${s.componentName}]`))==null||t.remove(),this.listener=null,this._mounted=!1);}render(e){var o,t,r,m,l;if(e.elements.length===0){this.removeChildren();return}for(let i of e.removedIds)(t=(o=this._htmlRoot)==null?void 0:o.querySelector(`#${s.elementSelectorPrefix}${i}`))==null||t.remove();let n=document.createDocumentFragment();for(let i of e.elements){let u=`${s.elementSelectorPrefix}${i.identifier}`,f=(r=this._htmlRoot)==null?void 0:r.querySelector(`#${u}`),a=f;if(f==null&&(a=new Image(i.view.options.size.width,i.view.options.size.height),a.id=u,a.dataset.identifier=String(i.identifier),n.append(a)),a){a.src=i.view.data;let d=this.mapViewAnchorPositionsForFramePoint(i.anchorPositions)[this._mirrored?b[i.anchor]:i.anchor];this._mirrored&&(d=a$2.mirrorX(d,this.size));let{x:S,y:w}=this.adjustCoordinatesWithOffset(d,{elementSize:i.view.options.size,offset:i.offset}),p=(m=i.view.options.scale)!=null?m:1;a.style.scale=`${p}`,a.style.transform=`translate3d(${S/p}px, ${w/p}px, 0px)`;}}(l=this._htmlRoot)==null||l.append(n);}removeChildren(){var e;for(;(e=this._htmlRoot)!=null&&e.firstChild;)this._htmlRoot.firstChild.remove();}adjustCoordinatesWithOffset(e,n){let o=e,{elementSize:t,offset:r}=n,m=e.x-t.width/2,l=e.y-t.height/2;return r.x.unit===\"pixel\"&&(o=new a$2(m+r.x.value,l+r.y.value)),r.x.unit===\"fraction\"&&(o=new a$2(m+t.width*r.x.value,l+t.height*r.y.value)),o}};s.componentName=\"CustomLocationsView\",s.elementSelectorPrefix=\"scandit-view-\";var R=s;\n\nexport { R as a };\n", "import { b, a } from './chunk-N4NOODAT.js';\n\nvar m=class h extends b{constructor(e,o,n,r,i,c,s,P,p){super(e,o,n,r),this._centerLeft=i,this._topCenter=c,this._centerRight=s,this._bottomCenter=P,this._center=p;}get centerRight(){return this._centerRight}get center(){return this._center}get centerLeft(){return this._centerLeft}get topCenter(){return this._topCenter}get bottomCenter(){return this._bottomCenter}static fromJSON(e){let{topLeft:o,topRight:n,bottomRight:r,bottomLeft:i,centerLeft:c,topCenter:s,centerRight:P,bottomCenter:p,center:S}=e,b=a.fromJSON(o),a$1=a.fromJSON(n),J=a.fromJSON(r),N=a.fromJSON(i),f=a.fromJSON(c),l=a.fromJSON(s),u=a.fromJSON(P),C=a.fromJSON(p),_=a.fromJSON(S);return new h(b,a$1,J,N,f,l,u,C,_)}toJSONObject(){return {...super.toJSONObject(),center:this._center.toJSONObject(),bottomCenter:this._bottomCenter.toJSONObject(),topCenter:this._topCenter.toJSONObject(),centerLeft:this._centerLeft.toJSONObject(),centerRight:this._centerRight.toJSONObject()}}};\n\nexport { m as a };\n", "var o=class n{static fromJSON(e){let t=new n;return t._code=e.code,t._message=e.message,t._isValid=e.isValid,t}get message(){return this._message}get code(){return this._code}get isValid(){return this._isValid}},r=(a=>(a.None=\"None\",a.X=\"X\",a.Y=\"Y\",a))(r||{});\n\nexport { o as a, r as b };\n", "import { b as b$3 } from './chunk-RZAO2YPF.js';\nimport { a as a$6 } from './chunk-436XQ2I6.js';\nimport { d as d$2, c, b as b$4 } from './chunk-5YHTIVUK.js';\nimport { a as a$d } from './chunk-4ZLDSFCW.js';\nimport { a as a$2 } from './chunk-N5YZEC56.js';\nimport { a as a$a } from './chunk-44B7Z6ZZ.js';\nimport { b, a as a$3 } from './chunk-5S537AFM.js';\nimport { a as a$c } from './chunk-COBZKSUV.js';\nimport { a as a$e } from './chunk-QR4TEDGM.js';\nimport { b as b$1 } from './chunk-457L5N2F.js';\nimport { a as a$7 } from './chunk-PXXUQXGB.js';\nimport { a as a$b } from './chunk-XVLYCDJL.js';\nimport { a as a$8 } from './chunk-KYNYQBNF.js';\nimport { a as a$5 } from './chunk-N5F43TUJ.js';\nimport { a as a$9 } from './chunk-NMX4VHW2.js';\nimport { a } from './chunk-DTSV5FYV.js';\nimport { d as d$1 } from './chunk-XLX4QIMT.js';\nimport { a as a$1 } from './chunk-SP3HSP4K.js';\nimport { d } from './chunk-5Y4OYXNX.js';\nimport { d as d$3 } from './chunk-AXTXPLXP.js';\nimport { a as a$4, b as b$2, i, f } from './chunk-N4NOODAT.js';\nimport { a as a$f } from './chunk-WUHKODFA.js';\n\nvar $=class G{constructor(){this.focusGesture=d.DataCaptureView.focusGesture;this.zoomGesture=d.DataCaptureView.zoomGesture;this._scanAreaMargins=d.DataCaptureView.scanAreaMargins;this._pointOfInterest=d.DataCaptureView.pointOfInterest;this._logoStyle=d.DataCaptureView.logoStyle;this._logoAnchor=d.DataCaptureView.logoAnchor;this._logoOffset=d.DataCaptureView.logoOffset;this._cameraRecoveryText=a.getInstance().get(\"core.camera.recovery\");this._context=null;this.overlays=[];this.controls=[];this.controlWidgets=new WeakMap;this.frozenFrameCanvas=document.createElement(\"canvas\");this.listeners=[];this.isVideoElementDetached=!1;this.orientation=\"portrait\";this.hiddenProperties={stopVideoTracksOnVisibilityChange:!0};this.orientationObserver=new b;this.onOrientationChangeListener=this.onOrientationChange.bind(this);this.onHintPresenterUpdateHandler=this.onHintPresenterUpdate.bind(this);this.onBeforeShowToastsHandler=this.onBeforeShowToasts.bind(this);this.onWorkerMessageHandler=this.onWorkerMessage.bind(this);this.visibilityListener=this.onVisibilityChange.bind(this),this.cameraRecoveryListener=this.cameraRecovery.bind(this);}get scanAreaMargins(){return this._scanAreaMargins}set scanAreaMargins(e){var t;this._scanAreaMargins=e,(t=this.privateContext)==null||t.update();}get pointOfInterest(){return this._pointOfInterest}set pointOfInterest(e){var t;this._pointOfInterest=e,(t=this.privateContext)==null||t.update();}get logoStyle(){return this._logoStyle}set logoStyle(e){var t;this._logoStyle=e,(t=this.privateContext)==null||t.update();}get logoAnchor(){return this._logoAnchor}set logoAnchor(e){var t;this._logoAnchor=e,(t=this.privateContext)==null||t.update();}get logoOffset(){return this._logoOffset}set logoOffset(e){var t;this._logoOffset=e,(t=this.privateContext)==null||t.update();}get cameraRecoveryText(){return this._cameraRecoveryText}set cameraRecoveryText(e){a$1.log(a$1.Level.Debug,\"DEPRECATED: DataCaptureView.cameraRecoveryText is deprecated, use the Localization API instead.\"),this._cameraRecoveryText=e,this.cameraRecoveryElement.textContent=e;}get width(){var e,t;return Math.round((t=(e=this.htmlElementState)==null?void 0:e.width)!=null?t:0)}get height(){var e,t;return Math.round((t=(e=this.htmlElementState)==null?void 0:e.height)!=null?t:0)}get canvasDrawer(){return !this._canvasDrawer&&this.canvasElement!=null&&(this._canvasDrawer=new b$1(this.canvasElement),this._canvasDrawer.startObservingCanvasResize()),this._canvasDrawer}get privateContext(){return this._context}static async forContext(e){let t=new G;return await t.setContext(e),t}showProgressBar(){var e;(e=this.loadingOverlay)==null||e.show();}hideProgressBar(){var e;(e=this.loadingOverlay)==null||e.hide();}setProgressBarPercentage(e){this.loadingOverlay&&(this.loadingOverlay.progress=e);}setProgressBarMessage(e){this.loadingOverlay&&(this.loadingOverlay.message=e);}getContext(){return this._context}async setContext(e){var t,i,n;if(this._context=e,e){if(this.overlays.length>0&&((t=this.privateContext)==null?void 0:t.modes.size)===0)throw new Error([\"Cannot assign this view to this context. This view has overlays but the context does not have any mode attached matching these overlays.\",\"Remove the overlays first before attaching the view to the context, or add the corresponding mode to the context before attaching this view.\"].join(\" \"));await e.setView(this),(i=this.privateContext)==null||i.subscribeToWorkerMessages(this.onWorkerMessageHandler),(n=this._context)!=null&&n.frameSource&&await this.onFrameSourceChange(this._context.frameSource);}}connectToElement(e){var t,i,n;this.orientationObserver.register(),this.setupHtmlElement(e),(t=this.canvasDrawer)==null||t.startObservingCanvasResize(),this.htmlElementDidChange(),a$2.add(this),this.orientation=this.orientationObserver.orientation.value,this.orientationObserver.addEventListener(a$3,this.onOrientationChangeListener),(i=this.hintPresenter)==null||i.addEventListener(\"hintpresenterupdate\",this.onHintPresenterUpdateHandler),(n=this.hintPresenter)==null||n.addEventListener(\"willshow\",this.onBeforeShowToastsHandler);}detachFromElement(){var e,t,i,n,a,o,l;(e=this.htmlElementState)==null||e.removeListeners(),this.removeStyles(),(t=this.canvasDrawer)==null||t.endObservingCanvasResize(),document.removeEventListener(\"visibilitychange\",this.visibilityListener);for(let m of [\"touchend\",\"mousedown\"])this.cameraRecoveryElement.removeEventListener(m,this.cameraRecoveryListener);(i=this.loadingOverlay)==null||i.remove(),(n=this.customLocationsView)==null||n.unmount(),this.htmlElementDidChange(),(a=this.gestureRecognizer)==null||a.removeAllListeners(),this.clearHtmlElementContent(),a$2.delete(this),this.orientationObserver.unregister(),this.orientationObserver.removeEventListener(a$3,this.onOrientationChangeListener),(o=this.hintPresenter)==null||o.removeEventListener(\"hintpresenterupdate\",this.onHintPresenterUpdateHandler),(l=this.hintPresenter)==null||l.removeEventListener(\"willshow\",this.onBeforeShowToastsHandler);}async addOverlay(e){var t;this.overlays.includes(e)||(this.overlays.push(e),await((t=this.privateContext)==null?void 0:t.update([{type:\"addOverlay\",newValue:e}])));}async removeOverlay(e){var t;this.overlays.includes(e)&&(this.overlays.splice(this.overlays.indexOf(e),1),await((t=this.privateContext)==null?void 0:t.update([{type:\"removeOverlay\",newValue:e}])));}addListener(e){this.listeners.includes(e)||this.listeners.push(e);}removeListener(e){this.listeners.includes(e)&&this.listeners.splice(this.listeners.indexOf(e),1);}viewPointForFramePoint(e){var v,y,S,b,O,P,L,V;let t={width:(y=(v=this.htmlElementState)==null?void 0:v.width)!=null?y:0,height:(b=(S=this.htmlElementState)==null?void 0:S.height)!=null?b:0},i={width:(P=(O=this.videoElement)==null?void 0:O.videoWidth)!=null?P:0,height:(V=(L=this.videoElement)==null?void 0:L.videoHeight)!=null?V:0},n=t.width/t.height,a=i.width/i.height,o=n>a?t.width/i.width:t.height/i.height,l={x:e.x*o,y:e.y*o},m=(i.width*o-t.width)/2,d=(i.height*o-t.height)/2;return new a$4(l.x-m,l.y-d)}viewQuadrilateralForFrameQuadrilateral(e){let t=this.viewPointForFramePoint(e.topLeft),i=this.viewPointForFramePoint(e.topRight),n=this.viewPointForFramePoint(e.bottomLeft),a=this.viewPointForFramePoint(e.bottomRight);return new b$2(t,i,a,n)}addControl(e){var t;this.controls.includes(e)||(e.view=this,this.controls.push(e),this.controlsUpdated(),(t=this.privateContext)==null||t.update([{type:\"addControl\",newValue:e}]));}removeControl(e){var t;if(this.controls.includes(e)){e.view=null;let i=this.controls.splice(this.controls.indexOf(e),1);this.getControlWidget(i[0]).remove(!0),this.controlsUpdated(),(t=this.privateContext)==null||t.update([{type:\"removeControl\",newValue:e}]);}}toJSONObject(){var e;return {scanAreaMargins:this.scanAreaMargins.toJSONObject(),pointOfInterest:this.pointOfInterest.toJSONObject(),logoAnchor:this.logoAnchor,logoOffset:this.logoOffset.toJSONObject(),logoHidden:(e=this.logoHidden)!=null?e:!1,logoStyle:this.logoStyle,overlays:this.overlays.map(t=>t.toJSONObject()),controls:this.controls.map(t=>t.toJSONObject()),focusGesture:this.focusGesture?this.focusGesture.toJSONObject():null,zoomGesture:this.zoomGesture?this.zoomGesture.toJSONObject():null}}isCameraRecoveryVisible(){return !this.cameraRecoveryElement.hidden}setCameraRecoveryVisible(e){this.cameraRecoveryElement.hidden=!e;}async allowPictureInPicture(e){await d$1.instance().allowPictureInPicture(e);}viewAnchorPositionsForFrameAnchorPositions(e){let t=this.viewPointForFramePoint(e.topLeft),i=this.viewPointForFramePoint(e.topRight),n=this.viewPointForFramePoint(e.bottomLeft),a=this.viewPointForFramePoint(e.bottomRight),o=this.viewPointForFramePoint(e.centerLeft),l=this.viewPointForFramePoint(e.centerRight),m=this.viewPointForFramePoint(e.topCenter),d=this.viewPointForFramePoint(e.bottomCenter),v=this.viewPointForFramePoint(e.center);return new a$5(t,i,a,n,o,m,l,d,v)}setDidTapCustomLocationsViewListener(e){this.customLocationsView&&this.customLocationsView.listener===null&&(this.customLocationsView.listener=e);}renderCustomLocationsView(e){this.customLocationsView!=null&&(this.customLocationsView.setMirrored(d$1.instance().isMirrorImageEnabled()),this.customLocationsView.render(e));}removeStyles(){var e;(e=document.querySelector(\"style[scandit]\"))==null||e.remove();}onHintPresenterUpdate(e){var t;(t=this.privateContext)==null||t.workerCommand(\"hintPresenterV2update\",{});}clearHtmlElementContent(){var e;this.htmlElement&&((e=this.canvasDrawer)==null||e.endObservingCanvasResize(),this.htmlElement.innerHTML=\"\",this.cameraPaintboardElement=void 0,this.singleImageUploaderPaintboardElement=void 0,this.htmlElement=void 0);}setupHtmlElement(e){var o,l,m;this.createStyles(),this.htmlElement=e,b$3.register();let t=`\n
\n
\n
\n
\n \n \n \n
\n
\n \n
\n <${b$3.tag}>\n
\n \n \n
\n
\n
\n
\n `;this.htmlElement.innerHTML=t,this.hintPresenter=this.htmlElement.querySelector(b$3.tag),this.loadingOverlay&&this.loadingOverlay.remove(),this.loadingOverlay=a$6.create(),this.loadingOverlay.hide(),(o=this.htmlElement.querySelector('[data-js-id=\"loading-overlay\"]'))==null||o.replaceWith(this.loadingOverlay),this.customLocationsView&&this.customLocationsView.unmount(),this.customLocationsView=new a$7,this.customLocationsView.mount(this.htmlElement.querySelector(`[data-js-id=\"${a$8.CUSTOM_VIEW_CONTAINER}\"]`)),this.customLocationsView.mapViewAnchorPositionsForFramePoint=d=>this.viewAnchorPositionsForFrameAnchorPositions(d),this.containerElement=this.htmlElement.querySelector(`.${a$9.CONTAINER_CLASS_NAME}`),this.cameraPaintboardElement=this.containerElement.querySelector('[data-js-id=\"camera-paintboard\"]'),this.singleImageUploaderPaintboardElement=this.containerElement.querySelector('[data-js-id=\"singleimage-paintboard\"]');let i=this.cameraPaintboardElement.querySelector(\"canvas\");this.canvasElement==null?this.canvasElement=i:i.replaceWith(this.canvasElement);let n=this.cameraPaintboardElement.querySelector('[data-js-id=\"frozen-frame\"]');this.frozenFrame==null?this.frozenFrame=n:n.replaceWith(this.frozenFrame),this.controlsElement=this.cameraPaintboardElement.querySelector(`.${a$9.CONTROLS_CLASS_NAME}`),this.cameraRecoveryElement=this.cameraPaintboardElement.querySelector(`.${a$9.CAMERA_RECOVERY_CLASS_NAME}`),this.errorElement=this.cameraPaintboardElement.querySelector(`.${a$9.ERROR_CLASS_NAME}`),this.hintContainerElement=this.cameraPaintboardElement.querySelector(`.${a$9.HINT_CONTAINER_CLASS_NAME}`),this.hintElement=this.cameraPaintboardElement.querySelector(`.${a$9.HINT_CLASS_NAME}`);let a=this.cameraPaintboardElement.querySelector(\"video\");this.videoElement?a.replaceWith(this.videoElement):(this.videoElement=a,this.videoPauseListener=this.handleVideoPause.bind(this),this.videoElement.addEventListener(\"pause\",this.videoPauseListener)),this.lastFrameSourceState!=null&&((m=(l=this._context)==null?void 0:l.frameSource)==null||m.switchToDesiredState(this.lastFrameSourceState)),document.addEventListener(\"visibilitychange\",this.visibilityListener);for(let d of [\"touchend\",\"mousedown\"])this.cameraRecoveryElement.addEventListener(d,this.cameraRecoveryListener);this.htmlElementState&&this.htmlElementState.removeListeners(),this.htmlElementState=new a$a(this.htmlElement),this.htmlElementState.onStateChanged(this.htmlElementDidChange.bind(this)),this.htmlElementState.onDisconnected(this.htmlElementDisconnected.bind(this)),this.gestureRecognizer=new a$b(this.htmlElement),this.gestureRecognizer.addListener({onTap:async d=>{var v;(v=this.privateContext)==null||v.workerCommand(\"onTap\",{point:d.toJSONObject()});}});}setupHtmlElementSingleImageUploader(e){var i;if(this.singleImageUploaderPaintboardElement==null)return;this.singleImageUploaderView&&this.singleImageUploaderView.unmount(),this.singleImageUploaderView=new a$c(e),this.singleImageUploaderView.mount(this.containerElement.querySelector('[data-js-id=\"singleimage-paintboard\"]'));let t=(i=this._context)==null?void 0:i.frameSource;this.singleImageUploaderView.onInputCheck(n=>{t.getCurrentState()!==\"starting\"&&n.preventDefault();}),this.singleImageUploaderView.onBeforeFileRead(()=>{t._context&&this.singleImageUploaderView&&(this.singleImageUploaderView.canUploadFile=t._context.hasEnabledMode());}),this.singleImageUploaderView.onImageLoadError(()=>{t.currentState=\"starting\",a$1.log(a$1.Level.Error,\"Could not load image from selected file\");}),this.singleImageUploaderView.onFileReaderError(n=>{var o,l;let a=n.target;t.currentState=\"starting\",a$1.log(a$1.Level.Error,`Error while reading the file: ${(l=(o=a.error)==null?void 0:o.toString())!=null?l:\"\"}`);}),this.singleImageUploaderView.onCaptureReady(async n=>{await t.processUploadedFileCapture(n);}),this.singleImageUploaderView.setButtonState(t.getCurrentState()===\"starting\"?\"enabled\":\"disabled\"),t.addView(this.singleImageUploaderView);}setupHtmlElementVisibility(e){this.cameraPaintboardElement!=null&&(this.cameraPaintboardElement.hidden=e!==\"camera\"),this.singleImageUploaderPaintboardElement!=null&&(this.singleImageUploaderPaintboardElement.hidden=e!==\"singleImageUploader\");}createStyles(){if(document.querySelector(\"style[scandit]\")===null){let e=document.createElement(\"style\");e.setAttribute(\"scandit\",\"data-capture-sdk\"),e.innerHTML=a$d(),document.head.append(e);}}async onOrientationChange(e){var t,i;this.orientation=e.detail.value,await((i=this.privateContext)==null?void 0:i.update([{type:\"viewChange\",newValue:{...(t=this.htmlElementState)==null?void 0:t.toJSONObject(),orientation:this.orientation}}]));}htmlElementDidChange(){var i$1,n;if(!this.htmlElementState)return;let e=this.htmlElementState,t=e.toJSONObject();if(!a$a.areEquivalentJSONStates(this.lastHtmlElementState,t)){this.orientation=this.orientationObserver.orientation.value,(i$1=this.privateContext)==null||i$1.update([{type:\"viewChange\",newValue:{...e.toJSONObject(),orientation:this.orientation}}]),this.lastHtmlElementState=t,(n=this.canvasDrawer)==null||n.updateCanvasSizeAttributes(this.width,this.height),this.handleVideoDisplay(t.visible);for(let a of this.listeners)typeof a.didChangeSize==\"function\"&&a.didChangeSize(this,new i(t.size.width.value,t.size.height.value),this.orientation);}}async htmlElementDisconnected(){var e,t,i,n,a,o,l;this.isVideoElementDetached=!1,(e=this.videoElement)==null||e.remove(),this.lastFrameSourceState=(i=(t=this._context)==null?void 0:t.frameSource)==null?void 0:i.getCurrentState(),await((a=(n=this._context)==null?void 0:n.frameSource)==null?void 0:a.switchToDesiredState(\"off\")),await((l=this.privateContext)==null?void 0:l.update([{type:\"viewChange\",newValue:{...(o=this.htmlElementState)==null?void 0:o.toJSONObject(),orientation:this.orientation}}]));}handleVideoDisplay(e){this.videoElement==null||this.cameraPaintboardElement==null||(!e&&!this.isVideoElementDetached?(this.videoElement.width=0,this.videoElement.height=0,this.videoElement.style.opacity=\"0\",this.videoElement.style.visibility=\"hidden\",document.body.append(this.videoElement),this.isVideoElementDetached=!0):e&&this.isVideoElementDetached&&(this.cameraPaintboardElement.insertAdjacentElement(\"afterbegin\",this.videoElement),this.isVideoElementDetached=!1,this.videoElement.style.removeProperty(\"visibility\"),this.videoElement.removeAttribute(\"width\"),this.videoElement.removeAttribute(\"height\"),this.videoElement.style.removeProperty(\"opacity\")));}isCanvasDrawerWithMetrics(e){return e instanceof a$e}onWorkerMessage(e){var t,i;switch(e.type){case\"draw\":{this.drawEngineCommands(e.payload);break}case\"performanceMetricsReport\":{let n=this._canvasDrawer;n!=null&&this.isCanvasDrawerWithMetrics(n)&&n.setPerformanceMetrics(e.payload);break}case\"contextDidChangeStatus\":{let n=a$f.fromJSON(e.payload);n.isValid||((t=this.loadingOverlay)==null||t.hide(),this.displayError(n));break}case\"showHint\":{this.displayHint(e.payload.text,e.payload.style);break}case\"updateHint\":{this.updateHint(e.payload.style);break}case\"hideHint\":{this.hideHint();break}default:{(i=this.hintPresenter)==null||i.handleMessage(e);break}}}async onBeforeShowToasts(){var t,i$1;let e=await((t=this._context)==null?void 0:t.workerCommand(\"getViewfinderInfo\",{}));if((e==null?void 0:e.rect)!=null){if(e.rect.origin.x===0&&e.rect.origin.y===0&&e.rect.size.width===0&&e.rect.size.height===0)return;(i$1=this.hintPresenter)==null||i$1.setViewFinderRect(new f(new a$4(e.rect.origin.x,e.rect.origin.y),new i(e.rect.size.width,e.rect.size.height)));}}drawEngineCommands(e){var t;(t=this.canvasDrawer)==null||t.draw(e);}displayError(e){this.errorElement.textContent=`Error ${e.code}: ${e.message}`,this.errorElement.hidden=!1;}clearError(){this.errorElement.textContent=\"\",this.errorElement.hidden=!0;}displayHint(e,t){this.hintElement.textContent=e,this.hintElement.hidden=!1,this.updateHint(t);}hideHint(){this.hintElement.textContent=\"\",this.hintElement.hidden=!0;}updateHint(e){this.hintElement.style.background=e.backgroundColor,this.hintElement.style.color=e.textColor,this.hintElement.style.fontSize=e.font===\"body\"?\"1.25rem\":\"1rem\",this.hintElement.style.borderRadius=e.hintCornerStyle===\"rounded\"?\"5px\":\"0px\",e.hintHeight===\"taller\"&&(this.hintElement.style.paddingTop=\"1.25em\",this.hintElement.style.paddingBottom=\"1.25em\"),e.hintWidth===\"wider\"&&(this.hintElement.style.paddingLeft=\"1.25em\",this.hintElement.style.paddingRight=\"1.25em\"),this.updateAnchor(e);}updateAnchor(e){let t=`${e.verticalOffsetRatio*100}vh`;switch(e.anchor){case\"topLeft\":{this.hintContainerElement.style.placeContent=\"start left\",this.hintElement.style.transform=`translateY(${t})`;break}case\"topCenter\":{this.hintContainerElement.style.placeContent=\"start center\",this.hintElement.style.transform=`translateY(${t})`;break}case\"topRight\":{this.hintContainerElement.style.placeContent=\"start right\",this.hintElement.style.transform=`translateY(${t})`;break}case\"centerLeft\":{this.hintContainerElement.style.placeContent=\"center start\";break}case\"center\":{this.hintContainerElement.style.placeContent=\"center\";break}case\"centerRight\":{this.hintContainerElement.style.placeContent=\"center end\";break}case\"bottomLeft\":{this.hintContainerElement.style.placeContent=\"end left\";break}case\"bottomCenter\":{this.hintContainerElement.style.placeContent=\"end center\";break}case\"bottomRight\":{this.hintContainerElement.style.placeContent=\"end right\";break}}}controlsUpdated(){var e;this.redrawControls(),(e=this.privateContext)==null||e.update();}redrawControls(){var t;let e=(t=this._context)==null?void 0:t.frameSource;for(let i of this.controls){let n=this.getControlWidget(i);e==null||e.desiredState===\"off\"||e.desiredState===\"standby\"||e.desiredState===\"stopping\"?n.remove():n.install();}}registerControlWidget(e,t){let i=new t(e,this.controlsElement);return this.controlWidgets.set(e,i),i}getControlWidget(e){let t=this.controlWidgets.get(e);if(t)return t;let{type:i}=e,n;switch(i){case\"torch\":{n=new b$4(e,this.controlsElement),this.controlWidgets.set(e,n);break}case\"camera\":{n=new c(e,this.controlsElement),this.controlWidgets.set(e,n);break}case\"camera-fov\":{n=new d$2(e,this.controlsElement),this.controlWidgets.set(e,n);break}}return n}async onFrameSourceChange(e){let t=e==null?void 0:e.type;if(this.setupHtmlElementVisibility(t),t===\"camera\"){let i=e==null?void 0:e.getCurrentState();i!=null&&await this.onCameraStateChanged(i);}else t===\"singleImageUploader\"&&this.setupHtmlElementSingleImageUploader(e.settings);}async onCameraStateChanged(e){var t;switch((t=this.cameraPaintboardElement)==null||t.classList.toggle(a$9.PAINTBOARD_CLASS_NAME_STATE_ON,e===\"on\"),e){case\"stopping\":{this.freezeFrame(),this.setVideoElementOpacity(\"0\");return}case\"starting\":case\"bootingUp\":case\"wakingUp\":{if(!this.htmlElement){a$1.log(a$1.Level.Error,\"cannot set frame source stream before connecting view to an HTML element\");return}this.videoElement&&(d$1.instance().videoElement=this.videoElement,d$1.instance().gui.isCameraRecoveryVisible=this.isCameraRecoveryVisible.bind(this),d$1.instance().gui.setCameraRecoveryVisible=this.setCameraRecoveryVisible.bind(this),this.setVideoElementOpacity(\"0\"));return}case\"off\":{this.setVideoElementOpacity(\"0\"),this.redrawControls();return}case\"on\":{await d$1.instance().waitForCapabilities(),this.redrawControls(),this.unfreezeFrame(),this.setVideoElementOpacity(\"1\");break}case\"goingToSleep\":{this.freezeFrame();break}}}setVideoElementOpacity(e){this.videoElement&&(this.videoElement.style.opacity=e),this.canvasElement&&(this.canvasElement.style.opacity=e);}onSingleImageUploaderSettingsChange(e){this.setupHtmlElementSingleImageUploader(e);}handleVideoPause(){d$1.instance().playVideo();}setHiddenProperty(e,t){this.hiddenProperties[e]=t;}async onVisibilityChange(){var t,i;let e=(t=this.videoElement)==null?void 0:t.srcObject;if(this.hiddenProperties.stopVideoTracksOnVisibilityChange&&(document.visibilityState===\"hidden\"&&d$1.instance().stopVideoTracks(),document.visibilityState===\"visible\"&&d$1.instance().activeCamera!=null&&e!=null))if(!e.active||(i=e.getVideoTracks()[0])!=null&&i.muted)try{a$1.log(a$1.Level.Debug,'Detected visibility change (\"visible\") event with inactive video source, try to reinitialize camera'),await d$1.instance().reinitializeCamera();}catch(n){}else a$1.log(a$1.Level.Debug,'Detected visibility change (\"visible\") event with active video source, replay video'),d$1.instance().playVideo();}async cameraRecovery(e){e.preventDefault(),d$1.instance().activeCamera=d$1.instance().selectedCamera,await d$1.instance().reinitializeCamera();}freezeFrame(){var i;if(!this.frozenFrame)return;let e=d$1.instance().getCurrentFrame();if(!e)return;let t=new ImageData(e.data,e.width,e.height);this.frozenFrameCanvas.width=t.width,this.frozenFrameCanvas.height=t.height,this.frozenFrame.width=t.width,this.frozenFrame.height=t.height,(i=this.frozenFrameCanvas.getContext(\"2d\"))==null||i.putImageData(t,0,0),this.frozenFrame.src=this.frozenFrameCanvas.toDataURL(\"image/jpeg\",.4),this.frozenFrame.classList.toggle(a$9.MIRRORED_CLASS_NAME,d$1.instance().isMirrorImageEnabled()),this.frozenFrame.hidden=!1;}unfreezeFrame(){this.frozenFrame&&(this.frozenFrame.src=\"\",this.frozenFrame.hidden=!0);}};\n\nexport { $ as a };\n", "import { a as a$1 } from './chunk-PSQ6LAQA.js';\nimport { d } from './chunk-5Y4OYXNX.js';\nimport { a as a$2 } from './chunk-AXTXPLXP.js';\nimport { a, b } from './chunk-FSQXZE3N.js';\n\nvar G=a(k=>{(function(){var A=function(){this.init();};A.prototype={init:function(){var e=this||r;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent=\"canplaythrough\",e._navigator=typeof window<\"u\"&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||r;if(e=parseFloat(e),t.ctx||g(),typeof e<\"u\"&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,r.ctx.currentTime);for(var n=0;n=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&typeof e.ctx.close<\"u\"&&(e.ctx.close(),e.ctx=null,g()),e},codecs:function(e){return (this||r)._codecs[e.replace(/^x-/,\"\")]},_setup:function(){var e=this||r;if(e.state=e.ctx&&e.ctx.state||\"suspended\",e._autoSuspend(),!e.usingWebAudio)if(typeof Audio<\"u\")try{var t=new Audio;typeof t.oncanplaythrough>\"u\"&&(e._canPlayEvent=\"canplay\");}catch(n){e.noAudio=!0;}else e.noAudio=!0;try{var t=new Audio;t.muted&&(e.noAudio=!0);}catch(n){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||r,t=null;try{t=typeof Audio<\"u\"?new Audio:null;}catch(y){return e}if(!t||typeof t.canPlayType!=\"function\")return e;var n=t.canPlayType(\"audio/mpeg;\").replace(/^no$/,\"\"),o=e._navigator?e._navigator.userAgent:\"\",l=o.match(/OPR\\/(\\d+)/g),s=l&&parseInt(l[0].split(\"/\")[1],10)<33,a=o.indexOf(\"Safari\")!==-1&&o.indexOf(\"Chrome\")===-1,f=o.match(/Version\\/(.*?) /),m=a&&f&&parseInt(f[1],10)<15;return e._codecs={mp3:!!(!s&&(n||t.canPlayType(\"audio/mp3;\").replace(/^no$/,\"\"))),mpeg:!!n,opus:!!t.canPlayType('audio/ogg; codecs=\"opus\"').replace(/^no$/,\"\"),ogg:!!t.canPlayType('audio/ogg; codecs=\"vorbis\"').replace(/^no$/,\"\"),oga:!!t.canPlayType('audio/ogg; codecs=\"vorbis\"').replace(/^no$/,\"\"),wav:!!(t.canPlayType('audio/wav; codecs=\"1\"')||t.canPlayType(\"audio/wav\")).replace(/^no$/,\"\"),aac:!!t.canPlayType(\"audio/aac;\").replace(/^no$/,\"\"),caf:!!t.canPlayType(\"audio/x-caf;\").replace(/^no$/,\"\"),m4a:!!(t.canPlayType(\"audio/x-m4a;\")||t.canPlayType(\"audio/m4a;\")||t.canPlayType(\"audio/aac;\")).replace(/^no$/,\"\"),m4b:!!(t.canPlayType(\"audio/x-m4b;\")||t.canPlayType(\"audio/m4b;\")||t.canPlayType(\"audio/aac;\")).replace(/^no$/,\"\"),mp4:!!(t.canPlayType(\"audio/x-mp4;\")||t.canPlayType(\"audio/mp4;\")||t.canPlayType(\"audio/aac;\")).replace(/^no$/,\"\"),weba:!!(!m&&t.canPlayType('audio/webm; codecs=\"vorbis\"').replace(/^no$/,\"\")),webm:!!(!m&&t.canPlayType('audio/webm; codecs=\"vorbis\"').replace(/^no$/,\"\")),dolby:!!t.canPlayType('audio/mp4; codecs=\"ec-3\"').replace(/^no$/,\"\"),flac:!!(t.canPlayType(\"audio/x-flac;\")||t.canPlayType(\"audio/flac;\")).replace(/^no$/,\"\")},e},_unlockAudio:function(){var e=this||r;if(!(e._audioUnlocked||!e.ctx)){e._audioUnlocked=!1,e.autoUnlock=!1,!e._mobileUnloaded&&e.ctx.sampleRate!==44100&&(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(n){for(;e._html5AudioPool.length\"u\"?m.noteOn(0):m.start(0),typeof e.ctx.resume==\"function\"&&e.ctx.resume(),m.onended=function(){m.disconnect(0),e._audioUnlocked=!0,document.removeEventListener(\"touchstart\",t,!0),document.removeEventListener(\"touchend\",t,!0),document.removeEventListener(\"click\",t,!0),document.removeEventListener(\"keydown\",t,!0);for(var y=0;y\"u\"||!r.usingWebAudio)){for(var t=0;t\"u\"||!r.usingWebAudio))return e.state===\"running\"&&e.ctx.state!==\"interrupted\"&&e._suspendTimer?(clearTimeout(e._suspendTimer),e._suspendTimer=null):e.state===\"suspended\"||e.state===\"running\"&&e.ctx.state===\"interrupted\"?(e.ctx.resume().then(function(){e.state=\"running\";for(var t=0;t\"u\"&&(e=\"__default\",!n._playLock)){for(var l=0,s=0;s0?a._seek:n._sprite[e][0]/1e3),y=Math.max(0,(n._sprite[e][0]+n._sprite[e][1])/1e3-m),b=y*1e3/Math.abs(a._rate),T=n._sprite[e][0]/1e3,x=(n._sprite[e][0]+n._sprite[e][1])/1e3;a._sprite=e,a._ended=!1;var I=function(){a._paused=!1,a._seek=m,a._start=T,a._stop=x,a._loop=!!(a._loop||n._sprite[e][2]);};if(m>=x){n._ended(a);return}var v=a._node;if(n._webAudio){var P=function(){n._playLock=!1,I(),n._refreshBuffer(a);var S=a._muted||n._muted?0:a._volume;v.gain.setValueAtTime(S,r.ctx.currentTime),a._playStart=r.ctx.currentTime,typeof v.bufferSource.start>\"u\"?a._loop?v.bufferSource.noteGrainOn(0,m,86400):v.bufferSource.noteGrainOn(0,m,y):a._loop?v.bufferSource.start(0,m,86400):v.bufferSource.start(0,m,y),b!==1/0&&(n._endTimers[a._id]=setTimeout(n._ended.bind(n,a),b)),t||setTimeout(function(){n._emit(\"play\",a._id),n._loadQueue();},0);};r.state===\"running\"&&r.ctx.state!==\"interrupted\"?P():(n._playLock=!0,n.once(\"resume\",P),n._clearTimer(a._id));}else {var F=function(){v.currentTime=m,v.muted=a._muted||n._muted||r._muted||v.muted,v.volume=a._volume*r.volume(),v.playbackRate=a._rate;try{var S=v.play();if(S&&typeof Promise<\"u\"&&(S instanceof Promise||typeof S.then==\"function\")?(n._playLock=!0,I(),S.then(function(){n._playLock=!1,v._unlocked=!0,t?n._loadQueue():n._emit(\"play\",a._id);}).catch(function(){n._playLock=!1,n._emit(\"playerror\",a._id,\"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.\"),a._ended=!0,a._paused=!0;})):t||(n._playLock=!1,I(),n._emit(\"play\",a._id)),v.playbackRate=a._rate,v.paused){n._emit(\"playerror\",a._id,\"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.\");return}e!==\"__default\"||a._loop?n._endTimers[a._id]=setTimeout(n._ended.bind(n,a),b):(n._endTimers[a._id]=function(){n._ended(a),v.removeEventListener(\"ended\",n._endTimers[a._id],!1);},v.addEventListener(\"ended\",n._endTimers[a._id],!1));}catch(C){n._emit(\"playerror\",a._id,C);}};v.src===\"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA\"&&(v.src=n._src,v.load());var N=window&&window.ejecta||!v.readyState&&r._navigator.isCocoonJS;if(v.readyState>=3||N)F();else {n._playLock=!0,n._state=\"loading\";var M=function(){n._state=\"loaded\",F(),v.removeEventListener(r._canPlayEvent,M,!1);};v.addEventListener(r._canPlayEvent,M,!1),n._clearTimer(a._id);}}return a._id},pause:function(e){var t=this;if(t._state!==\"loaded\"||t._playLock)return t._queue.push({event:\"pause\",action:function(){t.pause(e);}}),t;for(var n=t._getSoundIds(e),o=0;o\"u\"?l._node.bufferSource.noteOff(0):l._node.bufferSource.stop(0),t._cleanBuffer(l._node);}else (!isNaN(l._node.duration)||l._node.duration===1/0)&&l._node.pause();arguments[1]||t._emit(\"pause\",l?l._id:null);}return t},stop:function(e,t){var n=this;if(n._state!==\"loaded\"||n._playLock)return n._queue.push({event:\"stop\",action:function(){n.stop(e);}}),n;for(var o=n._getSoundIds(e),l=0;l\"u\"?s._node.bufferSource.noteOff(0):s._node.bufferSource.stop(0),n._cleanBuffer(s._node)):(!isNaN(s._node.duration)||s._node.duration===1/0)&&(s._node.currentTime=s._start||0,s._node.pause(),s._node.duration===1/0&&n._clearSound(s._node))),t||n._emit(\"stop\",s._id));}return n},mute:function(e,t){var n=this;if(n._state!==\"loaded\"||n._playLock)return n._queue.push({event:\"mute\",action:function(){n.mute(e,t);}}),n;if(typeof t>\"u\")if(typeof e==\"boolean\")n._muted=e;else return n._muted;for(var o=n._getSoundIds(t),l=0;l\"u\"){var l=e._getSoundIds(),s=l.indexOf(t[0]);s>=0?o=parseInt(t[0],10):n=parseFloat(t[0]);}else t.length>=2&&(n=parseFloat(t[0]),o=parseInt(t[1],10));var a;if(typeof n<\"u\"&&n>=0&&n<=1){if(e._state!==\"loaded\"||e._playLock)return e._queue.push({event:\"volume\",action:function(){e.volume.apply(e,t);}}),e;typeof o>\"u\"&&(e._volume=n),o=e._getSoundIds(o);for(var f=0;f\"u\");}}return l},_startFadeInterval:function(e,t,n,o,l,s){var a=this,f=t,m=n-t,y=Math.abs(m/.01),b=Math.max(4,y>0?o/y:o),T=Date.now();e._fadeTo=n,e._interval=setInterval(function(){var x=(Date.now()-T)/o;T=Date.now(),f+=m*x,f=Math.round(f*100)/100,m<0?f=Math.max(n,f):f=Math.min(n,f),a._webAudio?e._volume=f:a.volume(f,e._id,!0),s&&(a._volume=f),(nt&&f>=n)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,a.volume(n,e._id),a._emit(\"fade\",e._id));},b);},_stopFade:function(e){var t=this,n=t._soundById(e);return n&&n._interval&&(t._webAudio&&n._node.gain.cancelScheduledValues(r.ctx.currentTime),clearInterval(n._interval),n._interval=null,t.volume(n._fadeTo,e),n._fadeTo=null,t._emit(\"fade\",e)),t},loop:function(){var e=this,t=arguments,n,o,l;if(t.length===0)return e._loop;if(t.length===1)if(typeof t[0]==\"boolean\")n=t[0],e._loop=n;else return l=e._soundById(parseInt(t[0],10)),l?l._loop:!1;else t.length===2&&(n=t[0],o=parseInt(t[1],10));for(var s=e._getSoundIds(o),a=0;a=0?o=parseInt(t[0],10):n=parseFloat(t[0]);}else t.length===2&&(n=parseFloat(t[0]),o=parseInt(t[1],10));var a;if(typeof n==\"number\"){if(e._state!==\"loaded\"||e._playLock)return e._queue.push({event:\"rate\",action:function(){e.rate.apply(e,t);}}),e;typeof o>\"u\"&&(e._rate=n),o=e._getSoundIds(o);for(var f=0;f=0?o=parseInt(t[0],10):e._sounds.length&&(o=e._sounds[0]._id,n=parseFloat(t[0]));}else t.length===2&&(n=parseFloat(t[0]),o=parseInt(t[1],10));if(typeof o>\"u\")return 0;if(typeof n==\"number\"&&(e._state!==\"loaded\"||e._playLock))return e._queue.push({event:\"seek\",action:function(){e.seek.apply(e,t);}}),e;var a=e._soundById(o);if(a)if(typeof n==\"number\"&&n>=0){var f=e.playing(o);f&&e.pause(o,!0),a._seek=n,a._ended=!1,e._clearTimer(o),!e._webAudio&&a._node&&!isNaN(a._node.duration)&&(a._node.currentTime=n);var m=function(){f&&e.play(o,!0),e._emit(\"seek\",o);};if(f&&!e._webAudio){var y=function(){e._playLock?setTimeout(y,0):m();};setTimeout(y,0);}else m();}else if(e._webAudio){var b=e.playing(o)?r.ctx.currentTime-a._playStart:0,T=a._rateSeek?a._rateSeek-a._seek:0;return a._seek+(T+b*Math.abs(a._rate))}else return a._node.currentTime;return e},playing:function(e){var t=this;if(typeof e==\"number\"){var n=t._soundById(e);return n?!n._paused:!1}for(var o=0;o=0&&r._howls.splice(o,1);var l=!0;for(n=0;n=0){l=!1;break}return c&&l&&delete c[e._src],r.noAudio=!1,e._state=\"unloaded\",e._sounds=[],e=null,null},on:function(e,t,n,o){var l=this,s=l[\"_on\"+e];return typeof t==\"function\"&&s.push(o?{id:n,fn:t,once:o}:{id:n,fn:t}),l},off:function(e,t,n){var o=this,l=o[\"_on\"+e],s=0;if(typeof t==\"number\"&&(n=t,t=null),t||n)for(s=0;s=0;s--)(!l[s].id||l[s].id===t||e===\"load\")&&(setTimeout((function(a){a.call(this,t,n);}).bind(o,l[s].fn),0),l[s].once&&o.off(e,l[s].fn,l[s].id));return o._loadQueue(e),o},_loadQueue:function(e){var t=this;if(t._queue.length>0){var n=t._queue[0];n.event===e&&(t._queue.shift(),t._loadQueue()),e||n.action();}return t},_ended:function(e){var t=this,n=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;o--){if(n<=t)return;e._sounds[o]._ended&&(e._webAudio&&e._sounds[o]._node&&e._sounds[o]._node.disconnect(0),e._sounds.splice(o,1),n--);}}},_getSoundIds:function(e){var t=this;if(typeof e>\"u\"){for(var n=[],o=0;o=0;if(!e.bufferSource)return t;if(r._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),n))try{e.bufferSource.buffer=r._scratchBuffer;}catch(o){}return e.bufferSource=null,t},_clearSound:function(e){var t=/MSIE |Trident\\//.test(r._navigator&&r._navigator.userAgent);t||(e.src=\"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA\");}};var i=function(e){this._parent=e,this.init();};i.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite=\"__default\",e._id=++r._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,n=r._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=typeof r.ctx.createGain>\"u\"?r.ctx.createGainNode():r.ctx.createGain(),e._node.gain.setValueAtTime(n,r.ctx.currentTime),e._node.paused=!0,e._node.connect(r.masterGain)):r.noAudio||(e._node=r._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener(\"error\",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(r._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener(\"ended\",e._endFn,!1),e._node.src=t._src,e._node.preload=t._preload===!0?\"auto\":t._preload,e._node.volume=n*r.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite=\"__default\",e._id=++r._counter,e},_errorListener:function(){var e=this;e._parent._emit(\"loaderror\",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener(\"error\",e._errorFn,!1);},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(e._node.duration*10)/10,Object.keys(t._sprite).length===0&&(t._sprite={__default:[0,t._duration*1e3]}),t._state!==\"loaded\"&&(t._state=\"loaded\",t._emit(\"load\"),t._loadQueue()),e._node.removeEventListener(r._canPlayEvent,e._loadFn,!1);},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(e._node.duration*10)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=t._duration*1e3),t._ended(e)),e._node.removeEventListener(\"ended\",e._endFn,!1);}};var c={},d=function(e){var t=e._src;if(c[t]){e._duration=c[t].duration,_(e);return}if(/^data:[^;]+;base64,/.test(t)){for(var n=atob(t.split(\",\")[1]),o=new Uint8Array(n.length),l=0;l0?(c[t._src]=l,_(t,l)):n();};typeof Promise<\"u\"&&r.ctx.decodeAudioData.length===1?r.ctx.decodeAudioData(e).then(o).catch(n):r.ctx.decodeAudioData(e,o,n);},_=function(e,t){t&&!e._duration&&(e._duration=t.duration),Object.keys(e._sprite).length===0&&(e._sprite={__default:[0,e._duration*1e3]}),e._state!==\"loaded\"&&(e._state=\"loaded\",e._emit(\"load\"),e._loadQueue());},g=function(){if(r.usingWebAudio){try{typeof AudioContext<\"u\"?r.ctx=new AudioContext:typeof webkitAudioContext<\"u\"?r.ctx=new webkitAudioContext:r.usingWebAudio=!1;}catch(l){r.usingWebAudio=!1;}r.ctx||(r.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(r._navigator&&r._navigator.platform),t=r._navigator&&r._navigator.appVersion.match(/OS (\\d+)_(\\d+)_?(\\d+)?/),n=t?parseInt(t[1],10):null;if(e&&n&&n<9){var o=/safari/.test(r._navigator&&r._navigator.userAgent.toLowerCase());r._navigator&&!o&&(r.usingWebAudio=!1);}r.usingWebAudio&&(r.masterGain=typeof r.ctx.createGain>\"u\"?r.ctx.createGainNode():r.ctx.createGain(),r.masterGain.gain.setValueAtTime(r._muted?0:r._volume,r.ctx.currentTime),r.masterGain.connect(r.ctx.destination)),r._setup();}};typeof define==\"function\"&&define.amd&&define([],function(){return {Howler:r,Howl:u}}),typeof k<\"u\"&&(k.Howler=r,k.Howl=u),typeof global<\"u\"?(global.HowlerGlobal=A,global.Howler=r,global.Howl=u,global.Sound=i):typeof window<\"u\"&&(window.HowlerGlobal=A,window.Howler=r,window.Howl=u,window.Sound=i);})();(function(){HowlerGlobal.prototype._pos=[0,0,0],HowlerGlobal.prototype._orientation=[0,0,-1,0,1,0],HowlerGlobal.prototype.stereo=function(r){var u=this;if(!u.ctx||!u.ctx.listener)return u;for(var i=u._howls.length-1;i>=0;i--)u._howls[i].stereo(r);return u},HowlerGlobal.prototype.pos=function(r,u,i){var c=this;if(!c.ctx||!c.ctx.listener)return c;if(u=typeof u!=\"number\"?c._pos[1]:u,i=typeof i!=\"number\"?c._pos[2]:i,typeof r==\"number\")c._pos=[r,u,i],typeof c.ctx.listener.positionX<\"u\"?(c.ctx.listener.positionX.setTargetAtTime(c._pos[0],Howler.ctx.currentTime,.1),c.ctx.listener.positionY.setTargetAtTime(c._pos[1],Howler.ctx.currentTime,.1),c.ctx.listener.positionZ.setTargetAtTime(c._pos[2],Howler.ctx.currentTime,.1)):c.ctx.listener.setPosition(c._pos[0],c._pos[1],c._pos[2]);else return c._pos;return c},HowlerGlobal.prototype.orientation=function(r,u,i,c,d,h){var p=this;if(!p.ctx||!p.ctx.listener)return p;var _=p._orientation;if(u=typeof u!=\"number\"?_[1]:u,i=typeof i!=\"number\"?_[2]:i,c=typeof c!=\"number\"?_[3]:c,d=typeof d!=\"number\"?_[4]:d,h=typeof h!=\"number\"?_[5]:h,typeof r==\"number\")p._orientation=[r,u,i,c,d,h],typeof p.ctx.listener.forwardX<\"u\"?(p.ctx.listener.forwardX.setTargetAtTime(r,Howler.ctx.currentTime,.1),p.ctx.listener.forwardY.setTargetAtTime(u,Howler.ctx.currentTime,.1),p.ctx.listener.forwardZ.setTargetAtTime(i,Howler.ctx.currentTime,.1),p.ctx.listener.upX.setTargetAtTime(c,Howler.ctx.currentTime,.1),p.ctx.listener.upY.setTargetAtTime(d,Howler.ctx.currentTime,.1),p.ctx.listener.upZ.setTargetAtTime(h,Howler.ctx.currentTime,.1)):p.ctx.listener.setOrientation(r,u,i,c,d,h);else return _;return p},Howl.prototype.init=function(r){return function(u){var i=this;return i._orientation=u.orientation||[1,0,0],i._stereo=u.stereo||null,i._pos=u.pos||null,i._pannerAttr={coneInnerAngle:typeof u.coneInnerAngle<\"u\"?u.coneInnerAngle:360,coneOuterAngle:typeof u.coneOuterAngle<\"u\"?u.coneOuterAngle:360,coneOuterGain:typeof u.coneOuterGain<\"u\"?u.coneOuterGain:0,distanceModel:typeof u.distanceModel<\"u\"?u.distanceModel:\"inverse\",maxDistance:typeof u.maxDistance<\"u\"?u.maxDistance:1e4,panningModel:typeof u.panningModel<\"u\"?u.panningModel:\"HRTF\",refDistance:typeof u.refDistance<\"u\"?u.refDistance:1,rolloffFactor:typeof u.rolloffFactor<\"u\"?u.rolloffFactor:1},i._onstereo=u.onstereo?[{fn:u.onstereo}]:[],i._onpos=u.onpos?[{fn:u.onpos}]:[],i._onorientation=u.onorientation?[{fn:u.onorientation}]:[],r.call(this,u)}}(Howl.prototype.init),Howl.prototype.stereo=function(r,u){var i=this;if(!i._webAudio)return i;if(i._state!==\"loaded\")return i._queue.push({event:\"stereo\",action:function(){i.stereo(r,u);}}),i;var c=typeof Howler.ctx.createStereoPanner>\"u\"?\"spatial\":\"stereo\";if(typeof u>\"u\")if(typeof r==\"number\")i._stereo=r,i._pos=[r,0,0];else return i._stereo;for(var d=i._getSoundIds(u),h=0;h\"u\")if(typeof r==\"number\")d._pos=[r,u,i];else return d._pos;for(var h=d._getSoundIds(c),p=0;p\"u\")if(typeof r==\"number\")d._orientation=[r,u,i];else return d._orientation;for(var h=d._getSoundIds(c),p=0;p\"u\"&&(i.pannerAttr||(i.pannerAttr={coneInnerAngle:i.coneInnerAngle,coneOuterAngle:i.coneOuterAngle,coneOuterGain:i.coneOuterGain,distanceModel:i.distanceModel,maxDistance:i.maxDistance,refDistance:i.refDistance,rolloffFactor:i.rolloffFactor,panningModel:i.panningModel}),r._pannerAttr={coneInnerAngle:typeof i.pannerAttr.coneInnerAngle<\"u\"?i.pannerAttr.coneInnerAngle:r._coneInnerAngle,coneOuterAngle:typeof i.pannerAttr.coneOuterAngle<\"u\"?i.pannerAttr.coneOuterAngle:r._coneOuterAngle,coneOuterGain:typeof i.pannerAttr.coneOuterGain<\"u\"?i.pannerAttr.coneOuterGain:r._coneOuterGain,distanceModel:typeof i.pannerAttr.distanceModel<\"u\"?i.pannerAttr.distanceModel:r._distanceModel,maxDistance:typeof i.pannerAttr.maxDistance<\"u\"?i.pannerAttr.maxDistance:r._maxDistance,refDistance:typeof i.pannerAttr.refDistance<\"u\"?i.pannerAttr.refDistance:r._refDistance,rolloffFactor:typeof i.pannerAttr.rolloffFactor<\"u\"?i.pannerAttr.rolloffFactor:r._rolloffFactor,panningModel:typeof i.pannerAttr.panningModel<\"u\"?i.pannerAttr.panningModel:r._panningModel});else return d=r._soundById(parseInt(u[0],10)),d?d._pannerAttr:r._pannerAttr;else u.length===2&&(i=u[0],c=parseInt(u[1],10));for(var h=r._getSoundIds(c),p=0;p(t[e]=this.getProperty(e),t),{})}};\n\nexport { r as a };\n", "import { a as a$3, b as b$1 } from './chunk-F3A3WWOG.js';\nimport { a as a$2 } from './chunk-EMHHC6NB.js';\nimport { a as a$1 } from './chunk-7SW2PEHB.js';\nimport { a as a$4 } from './chunk-FGO2SSRS.js';\nimport { d } from './chunk-XLX4QIMT.js';\nimport { a as a$5 } from './chunk-SP3HSP4K.js';\nimport { a } from './chunk-PSQ6LAQA.js';\nimport { f as f$1 } from './chunk-36CGJKPG.js';\nimport { a as a$6 } from './chunk-WUHKODFA.js';\n\nvar f,w,b,o=class o{constructor(e,t){this.framework=\"web\";this.runtimeEnvironment={deviceOS:(f=a.getUserAgentInfo().getOS().name)!=null?f:\"\",browser:(w=a.getUserAgentInfo().getBrowser().name)!=null?w:\"\",browserVersion:(b=a.getUserAgentInfo().getBrowser().version)!=null?b:\"\",get deviceModelName(){let{model:e,vendor:t}=a.getUserAgentInfo().getDevice();return (t==null||t===\"\")&&(t=\"Unknown\"),(e==null||e===\"\")&&(e=\"Unknown\"),[t,e].join(\" \")}};this.settings=new a$1;this._frameSource=null;this._view=null;this.modes=new Set;this.components=[];this.listeners=[];this.updateListeners=new Set;this.cameraPropertiesReportListener=this.reportCameraProperties.bind(this);this.cameraAccessErrorListener=this.onCameraAccessError.bind(this);this.onWorkerMessageListener=this.onWorkerMessage.bind(this);this.onVisibilityChangeListener=this.onVisibilityChange.bind(this);this._frameHandlers=[];var a$3,r,p,l,c,C;this.licenseKey=e,this.deviceName=(a$3=t.deviceName)!=null?a$3:\"\",this.dataCaptureInstance=(r=t.dataCaptureInstance)!=null?r:a$2.mainDataCaptureLoader,this.delayedRegistration=(p=t.delayedRegistration)!=null?p:!1,this.highEndBlurryRecognition=(C=(c=(l=t.dataCaptureInstance)==null?void 0:l.highEndBlurryRecognition)!=null?c:a$2.mainDataCaptureLoader.highEndBlurryRecognition)!=null?C:!1;}get frameSource(){return this._frameSource}get workerCommand(){return this.dataCaptureInstance.workerCommand.bind(this.dataCaptureInstance)}static async create(){return o.createWithOptions({})}static async createWithOptions(e){var a;let t=new o((a=e.licenseKey)!=null?a:a$2.userLicenseKey,{deviceName:e.deviceName});return e.settings!=null&&await t.applySettings(e.settings),await t.initialize(),t}async setFrameSource(e){let t=e!==this._frameSource;if(this._frameSource!==null&&(this._frameSource.context=null),this._frameSource=e!=null?e:null,e&&(e.context=this,await this.workerCommand(\"setFrameSource\",{mirrorAxis:this.getMirrorAxisForFrameSource(e),isCameraFrameSource:f$1(e)})),await this.update([{type:\"frameSourceState\",newValue:this.frameSource}]),t)for(let a of this.listeners)a.didChangeFrameSource&&a.didChangeFrameSource(this,this._frameSource);}addListener(e){this.listeners.includes(e)||this.listeners.push(e);}async flushAnalytics(){await this.workerCommand(\"flushAnalytics\",{});}removeListener(e){this.listeners.includes(e)&&this.listeners.splice(this.listeners.indexOf(e),1);}async addMode(e){this.modes.add(e),await e.attachedToContext(this),this.updateCameraFrameFlow(),await this.update();}async removeMode(e){this.modes.delete(e),await e.detachedFromContext(),this.updateCameraFrameFlow(),await this.update();}async removeAllModes(){for(let e of this.modes)await this.removeMode(e);}async dispose(){d.instance().removeListener(\"cameraProperties\",this.cameraPropertiesReportListener),d.instance().removeListener(\"cameraAccessError\",this.cameraAccessErrorListener),this.unsubscribeToVisibilityChange(this.onVisibilityChangeListener),await this.workerCommand(\"dispose\",{});}async applySettings(e){this.settings=e,await this.update();}toJSONObject(){var e,t;return {licenseKey:this.licenseKey,framework:this.framework,deviceName:this.deviceName,...this.runtimeEnvironment,modes:[...this.modes].filter(a=>!a.skipSerialization).map(a=>a.toJSONObject()),components:this.components.map(a=>a.toJSONObject()),frameSource:this.frameSource?this.frameSource.toJSONObject():null,settings:this.settings.toJSONObject(),view:(t=(e=this._view)==null?void 0:e.toJSONObject())!=null?t:null}}getView(){return this._view}async setView(e){return this._view=e,this.update([{type:\"viewSet\",newValue:e}])}async getAppName(){let e=null;if(a$3()){let t=await b$1();if((t==null?void 0:t.appName)==null||t.appName===\"\")throw new Error(\"Cannot retrieve electron appName. Did you set it up in package.json? https://www.electronjs.org/docs/latest/api/app#appgetname\");e=t.appName;}return e}urlToHostname(e){try{return new URL(e!=null?e:\"\").hostname}catch(t){return \"\"}}getParentDomain(){var t;let e=\"\";return parent!==window&&(e||(e=this.urlToHostname((t=location.ancestorOrigins)==null?void 0:t[0])),e||(e=this.urlToHostname(document.referrer)),e||(e=\"\")),e.startsWith(\"[\")&&e.at(-1)===\"]\"&&(e=e.slice(1,-1)),e}async initialize(e=!0){await this.workerCommand(\"createContext\",{context:this.toJSONObject(),deviceId:o.deviceID,delayedRegistration:this.delayedRegistration,highEndBlurryRecognition:this.highEndBlurryRecognition,appName:await this.getAppName(),parentDomain:this.getParentDomain()}),this.subscribeToWorkerMessages(this.onWorkerMessageListener),e&&(this.subscribeToCameraManagerEvents(),this.subscribeToVisibilityChange(this.onVisibilityChangeListener));}subscribeToVisibilityChange(e){document.addEventListener(\"visibilitychange\",e);}unsubscribeToVisibilityChange(e){document.removeEventListener(\"visibilitychange\",e);}async requestFrameData(e){return this.workerCommand(\"requestFrameData\",{frameId:e})}performanceMark(e){a$4(globalThis.performance)&&typeof globalThis.performance.mark==\"function\"&&performance.mark(e);}async sendFrameToProcessor(e){let t=e instanceof ImageData?{data:e.data,width:e.width,height:e.height}:e;return await this.sendFrameToHandlers(t)?(this.performanceMark(\"processFrameBeforeSDC\"),this.sendFrameToSDC(t)):e}async sendFrameToHandlers(e){for(let t of this._frameHandlers)if(await t(e)===\"skip\")return !1;return !0}async sendFrameToSDC(e){return this.workerCommand(\"processFrame\",e,[e.data.buffer])}registerFrameHandler(e){this._frameHandlers.includes(e)||this._frameHandlers.push(e);}unregisterFrameHandler(e){this._frameHandlers.includes(e)&&this._frameHandlers.splice(this._frameHandlers.indexOf(e),1);}onVisibilityChange(){this.workerCommand(\"documentVisibility\",{state:document.visibilityState});}onWorkerMessage(e){if(e.type===\"contextDidChangeStatus\"){e.payload.isValid||a$5.log(a$5.Level.Error,e.payload);for(let t of this.listeners)t.didChangeStatus&&t.didChangeStatus(this,a$6.fromJSON(e.payload));}if(e.type===\"didStartObservingContext\")for(let t of this.listeners)t.didStartObservingContext&&t.didStartObservingContext(this);e.type===\"onFrameProcessingFinished\"&&this.performanceMark(\"processFrameAfterSDC\");}subscribeToCameraManagerEvents(){d.instance().addListener(\"cameraProperties\",this.cameraPropertiesReportListener),d.instance().addListener(\"cameraAccessError\",this.cameraAccessErrorListener);}async reportCameraProperties(e){return this.workerCommand(\"reportCameraProperties\",e)}onCameraAccessError(e){for(let t of this.listeners)t.didChangeStatus&&t.didChangeStatus(this,a$6.fromJSON({code:33794,isValid:!0,message:e.toString()}));}async update(e=[]){var t,a;await this.updateContext();for(let r of e){switch(r.type){case\"frameSourceState\":{await((t=this._view)==null?void 0:t.onFrameSourceChange(this.frameSource));break}case\"singleImageModeUploaderSettings\":{(a=this._view)==null||a.onSingleImageUploaderSettingsChange(r.newValue);break}}for(let p of this.updateListeners)p(r);}}async updateContext(){await this.workerCommand(\"updateContext\",{context:this.toJSONObject(),...this.getViewInfo()}).catch(e=>{a$5.log(a$5.Level.Warn,\"Error while updating context:\",e);});}getViewInfo(){return this._view!=null?{view:{width:this._view.width,height:this._view.height,visible:this._view.width>0&&this._view.height>0,orientation:this._view.orientation}}:{view:null}}getMirrorAxisForFrameSource(e){let t=\"None\";return f$1(e)&&e.getMirrorImageEnabled()&&(t=\"Y\"),t}async addComponent(e){if(!this.components.includes(e))return this.components.push(e),e._context=this,this.update()}subscribeToWorkerMessages(e){this.dataCaptureInstance.addWorkerListener(e);}unsubscribeToWorkerMessages(e){this.dataCaptureInstance.removeWorkerListener(e);}hasEnabledMode(){return [...this.modes].some(e=>e.isEnabled())}updateCameraFrameFlow(){let e=[...this.modes].some(t=>t._synchronousFrameFlow===!0);d.instance().setFrameHandling(e);}async isFeatureSupported(e){return (await this.workerCommand(\"isFeatureSupported\",{feature:e})).supported}};o.deviceID=a.getDeviceId();var S=o;\n\nexport { S as a };\n", "export { b as DataCaptureLoader, a as OverrideState } from './chunks/chunk-2QPETYTY.js';\nexport { a as WorkerMain } from './chunks/chunk-YOKMFKUG.js';\nimport { a as a$3 } from './chunks/chunk-ZAOFG2OQ.js';\nimport { a as a$1 } from './chunks/chunk-VJB527QZ.js';\nexport { c as CameraFOVSwitchControl, b as CameraSwitchControl, a as TorchSwitchControl } from './chunks/chunk-T5EUB6UG.js';\nexport { a as NoViewfinder } from './chunks/chunk-4ZMCJXZS.js';\nexport { a as convertToPublicFrameData } from './chunks/chunk-UHFABUTI.js';\nexport { a as ImageFrameSource } from './chunks/chunk-VRVSELOR.js';\nexport { a as LaserlineViewfinder } from './chunks/chunk-ONUQJGRK.js';\nexport { a as PrivateNoneLocationSelection, b as RadiusLocationSelection, c as RectangularLocationSelection } from './chunks/chunk-KW3YSGJX.js';\nexport { a as RectangularViewfinder } from './chunks/chunk-ANTPRJPM.js';\nexport { a as SingleImageUploader } from './chunks/chunk-CCNVXFEG.js';\nexport { a as SingleImageUploaderSettings } from './chunks/chunk-BTXDPF7O.js';\nexport { a as DataCaptureVersion } from './chunks/chunk-2Q7A7JWM.js';\nexport { a as DataCaptureView } from './chunks/chunk-RLD35PR2.js';\nimport { a as a$5 } from './chunks/chunk-N5YZEC56.js';\nexport { a as AnchorPositions } from './chunks/chunk-N5F43TUJ.js';\nimport { a } from './chunks/chunk-DTSV5FYV.js';\nexport { a as Localization } from './chunks/chunk-DTSV5FYV.js';\nexport { c as Feedback, b as Sound, a as Vibration } from './chunks/chunk-AWSARCBG.js';\nexport { a as AimerViewfinder } from './chunks/chunk-VXLIGYOC.js';\nexport { a as Brush } from './chunks/chunk-G7A5SQZE.js';\nexport { a as Camera } from './chunks/chunk-45EBHQYM.js';\nexport { a as CameraAccess } from './chunks/chunk-IWMYUNZ3.js';\nexport { a as DataCaptureContext } from './chunks/chunk-EGMJHFGI.js';\nimport { a as a$6, c } from './chunks/chunk-F3A3WWOG.js';\nimport { a as a$2 } from './chunks/chunk-EMHHC6NB.js';\nimport { b as b$1 } from './chunks/chunk-6H6FKGVE.js';\nexport { b as loadingStatus } from './chunks/chunk-6H6FKGVE.js';\nexport { a as DataCaptureContextSettings } from './chunks/chunk-7SW2PEHB.js';\nexport { a as throttle } from './chunks/chunk-T3AOBMAS.js';\nexport { a as Timeout } from './chunks/chunk-Q7JWDX4U.js';\nexport { a as wait } from './chunks/chunk-UZWBB65W.js';\nexport { a as waitTransitionEndForElement } from './chunks/chunk-72DAONJI.js';\nexport { a as defineCustomElements } from './chunks/chunk-3A4KLILV.js';\nexport { a as html } from './chunks/chunk-U6BTTEV6.js';\nexport { a as match } from './chunks/chunk-ZVBD3EW5.js';\nexport { a as ScanditHTMLElement } from './chunks/chunk-EV4OEANA.js';\nexport { a as css } from './chunks/chunk-GE4CBD4E.js';\nexport { a as unknownErrorToString } from './chunks/chunk-AIRWHLJH.js';\nexport { a as isObject } from './chunks/chunk-FGO2SSRS.js';\nexport { a as isWorkerScope } from './chunks/chunk-QCRFVRSS.js';\nexport { a as Deferred } from './chunks/chunk-O7TZTIHO.js';\nexport { a as debounce } from './chunks/chunk-R6E4CT22.js';\nexport { a as assert, b as assertUnreachable, c as assertUnreachableThrowException } from './chunks/chunk-FTD535WI.js';\nimport { a as a$9 } from './chunks/chunk-GPJEB376.js';\nimport { a as a$4 } from './chunks/chunk-SP3HSP4K.js';\nexport { a as Logger } from './chunks/chunk-SP3HSP4K.js';\nimport { a as a$7 } from './chunks/chunk-QCZSSQAQ.js';\nexport { a as DataCaptureError } from './chunks/chunk-QCZSSQAQ.js';\nimport { a as a$8 } from './chunks/chunk-PSQ6LAQA.js';\nexport { a as BrowserHelper } from './chunks/chunk-PSQ6LAQA.js';\nexport { a as Feature } from './chunks/chunk-5LIWL2C4.js';\nexport { c as CameraPosition, g as CameraSettings, e as FocusGestureStrategy, a as FrameSourceState, b as TorchState, d as VideoResolution, f as isCameraFrameSource } from './chunks/chunk-36CGJKPG.js';\nexport { c as LaserlineViewfinderStyle, d as RectangularViewfinderAnimation, b as RectangularViewfinderLineStyle, a as RectangularViewfinderStyle } from './chunks/chunk-JUG6FO4O.js';\nexport { a as LogoStyle, c as SwipeToZoom, b as TapToFocus } from './chunks/chunk-GX4YCYCH.js';\nexport { q as Anchor, n as Color, p as Direction, m as MarginsWithUnit, c as MeasureUnit, d as NumberWithUnit, o as Orientation, a as Point, e as PointWithUnit, b as Quadrilateral, f as Rect, g as RectWithUnit, i as Size, j as SizeWithAspect, h as SizeWithUnit, l as SizeWithUnitAndAspect, k as SizingMode } from './chunks/chunk-N4NOODAT.js';\nexport { a as ContextStatus, b as PrivateMirrorAxis } from './chunks/chunk-WUHKODFA.js';\n\nvar p=a$2;a.getInstance().updateIfMissing(a$1);async function w(){var r;a$2.configurePhase=\"unconfigured\",(r=p.mainDataCaptureLoader)!=null&&r.terminateDataCaptureWorker&&await p.mainDataCaptureLoader.terminateDataCaptureWorker(!0);}function l({percentage:r}){for(let e of a$5.values())e.setProgressBarPercentage(r);}function h(){var o,u;function r(x){return [\"auto\",\"off\",\"on\"].includes(x)}let e=new URLSearchParams(window.location.search),[i=\"auto\",a=\"auto\"]=[(o=e.get(\"pthreads\"))==null?void 0:o.toLowerCase(),(u=e.get(\"simd\"))==null?void 0:u.toLowerCase()];return {overrideThreadsSupport:r(i)?i:\"auto\",overrideSimdSupport:r(a)?a:\"auto\"}}async function S(r){if(a$6()&&typeof r.licenseDataPath!=\"string\")throw new a$7({name:\"MisconfigurationError\",message:'\"licenseDataPath\" string is missing or not valid'});if(a$6()&&typeof r.licenseDataPath==\"string\"){let e=await c({licenseDataPath:r.licenseDataPath});if(e==null)throw new Error(\"Cannot retrieve license key for Electron\");r.licenseKey=e.licenseKey;}if(r.licenseKey==null||r.licenseKey.trim().length<64)throw new a$7({name:\"NoLicenseKeyError\",message:\"No license key provided\"});if(typeof r.libraryLocation!=\"string\")throw new a$7({name:\"MisconfigurationError\",message:'Option \"libraryLocation\" was not provided'});if(!Array.isArray(r.moduleLoaders)||r.moduleLoaders.length===0)throw new a$7({name:\"MisconfigurationError\",message:'Option \"moduleLoaders\" is missing or empty'})}async function b(r,e){let i=new Map,a=new Map;for(let o of r)a.set(o.moduleName,o.load(e));await Promise.all(a.values());for(let[o,u]of a)i.set(o,await u);return i}async function ne(r){var a;if(p.configurePhase!==\"unconfigured\"&&p.configurePromise!=null)return p.configurePromise;await S(r);let e={...h(),...r,libraryLocation:a$3(r.libraryLocation),logLevel:(a=r.logLevel)!=null?a:a$4.Level.Debug,verifyResponseHash:!0,loadProgressNotifier:b$1.notify.bind(b$1)};a$2.userLicenseKey=e.licenseKey,a$4.setLevel(e.logLevel);async function i(){a$2.configurePhase=\"started\",b$1.subscribe(l);let o=a$8.checkBrowserCompatibility();if(!o.fullSupport&&!o.scannerSupport)throw new a$9(o);a$8.isSupportedIOSVersion()||a$4.log(a$4.Level.Warn,`Warning: Minimum supported iOS version is 14.6.\nPlease check the minimum system requirements here:\nhttps://docs.scandit.com/data-capture-sdk/web/requirements.html`),a$2.dataCaptureLoaders=await b(e.moduleLoaders,e),a$2.mainDataCaptureLoader=[...a$2.dataCaptureLoaders.entries()][0][1],a$2.configurePhase=\"done\",b$1.unsubscribe(l);}return a$2.configurePromise=i().catch(o=>{throw w(),b$1.unsubscribe(l),o}),a$2.configurePromise}function me(r){a$2.mainDataCaptureLoader=r;}\n\nexport { ne as configure, w as resetConfigure, me as setMainDataCaptureLoader };\n", "import { Color } from 'scandit-web-datacapture-core';\n\nvar e=class i{constructor(o,n,l,r){this.inListItemColor=o,this.notInListItemColor=n,this.hapticEnabled=r,this.soundEnabled=l;}static fromJSON(o){return new i(Color.fromJSON(o.inListItemColor),Color.fromJSON(o.notInListItemColor),o.soundEnabled,o.hapticEnabled)}toJSONObject(){return {inListItemColor:this.inListItemColor.toJSON(),notInListItemColor:this.notInListItemColor.toJSON(),soundEnabled:this.soundEnabled,hapticEnabled:this.hapticEnabled}}};\n\nexport { e as a };\n", "var e=class t{get isFixed(){return this.minimum===this.maximum||this.step<=0}get maximum(){return this._maximum}get minimum(){return this._minimum}get step(){return this._step}static fromJSON(i){let m=new t;return m._minimum=i.minimum,m._maximum=i.maximum,m._step=i.step,m}toJSONObject(){return {maximum:this.maximum,minimum:this.minimum,step:this.step}}};\n\nexport { e as a };\n", "import { a } from './chunk-7SWSAHI5.js';\n\nvar o=class t{constructor(e){if(e!=null)return t.all[t.all.findIndex(i=>i.identifier===e)]}static get all(){return this.defaults().SymbologyDescriptions}get activeSymbolCountRange(){return this._activeSymbolCountRange}get defaultSymbolCountRange(){return this._defaultSymbolCountRange}get identifier(){return this._identifier}get isAvailable(){return this._isAvailable}get isColorInvertible(){return this._isColorInvertible}get readableName(){return this._readableName}get supportedExtensions(){return [...this._supportedExtensions]}get symbology(){return this.identifier}static forIdentifier(e){return t.all.findIndex(r=>r.identifier===e)===-1?null:new t(e)}static fromJSON(e){let i=new t;return i._identifier=e.identifier,i._readableName=e.readableName,i._isAvailable=e.isAvailable,i._isColorInvertible=e.isColorInvertible,i._activeSymbolCountRange=a.fromJSON(e.activeSymbolCountRange),i._defaultSymbolCountRange=a.fromJSON(e.defaultSymbolCountRange),i._supportedExtensions=new Set(e.supportedExtensions),i}};\n\nexport { o as a };\n", "var s=class o{get enabledExtensions(){return [...this.extensions]}get symbology(){return this._symbology}static fromJSON(e){let t=new o;return t.extensions=new Set(e.extensions),t.isEnabled=e.enabled,t.isColorInvertedEnabled=e.colorInvertedEnabled,t.checksums=new Set(e.checksums),t.activeSymbolCounts=e.activeSymbolCounts,t}setExtensionEnabled(e,t){t?this.extensions.add(e):this.extensions.delete(e);}toJSONObject(){return {activeSymbolCounts:[...this.activeSymbolCounts],checksums:[...this.checksums],colorInvertedEnabled:this.isColorInvertedEnabled,enabled:this.isEnabled,extensions:[...this.extensions]}}};\n\nexport { s as a };\n", "import { a as a$2 } from './chunk-3UG34CP2.js';\nimport { a } from './chunk-KBO3YYBN.js';\nimport { a as a$1 } from './chunk-LBAL6OCN.js';\nimport { Color, MeasureUnit, FocusGestureStrategy, VideoResolution, TorchState, CameraSettings } from 'scandit-web-datacapture-core';\n\nvar S=e=>({SymbologySettings:Object.keys(e.SymbologySettings).reduce((t,o)=>(t[o]=a$1.fromJSON(JSON.parse(e.SymbologySettings[o])),t),{}),SymbologyDescriptions:e.SymbologyDescriptions.map(t=>a.fromJSON(JSON.parse(t))),CompositeTypeDescriptions:e.CompositeTypeDescriptions.map(t=>JSON.parse(t)),BarcodeCapture:{BarcodeCaptureOverlay:{defaultStyle:e.BarcodeCapture.BarcodeCaptureOverlay.defaultStyle,DefaultBrush:{fillColor:Color.fromJSON(e.BarcodeCapture.BarcodeCaptureOverlay.DefaultBrush.fillColor),strokeColor:Color.fromJSON(e.BarcodeCapture.BarcodeCaptureOverlay.DefaultBrush.strokeColor),strokeWidth:e.BarcodeCapture.BarcodeCaptureOverlay.DefaultBrush.strokeWidth},styles:Object.fromEntries(Object.keys(e.BarcodeCapture.BarcodeCaptureOverlay.styles).map(t=>[t,{DefaultBrush:{fillColor:Color.fromJSON(e.BarcodeCapture.BarcodeCaptureOverlay.styles[t].DefaultBrush.fillColor),strokeColor:Color.fromJSON(e.BarcodeCapture.BarcodeCaptureOverlay.styles[t].DefaultBrush.strokeColor),strokeWidth:e.BarcodeCapture.BarcodeCaptureOverlay.styles[t].DefaultBrush.strokeWidth}}]))},BarcodeCaptureSettings:{codeDuplicateFilter:e.BarcodeCapture.BarcodeCaptureSettings.codeDuplicateFilter},RecommendedCameraSettings:CameraSettings.fromJSON(e.BarcodeCapture.RecommendedCameraSettings)},BarcodeTracking:{BarcodeTrackingBasicOverlay:{defaultStyle:e.BarcodeTracking.BarcodeTrackingBasicOverlay.defaultStyle,DefaultBrush:{fillColor:Color.fromJSON(e.BarcodeTracking.BarcodeTrackingBasicOverlay.DefaultBrush.fillColor),strokeColor:Color.fromJSON(e.BarcodeTracking.BarcodeTrackingBasicOverlay.DefaultBrush.strokeColor),strokeWidth:e.BarcodeTracking.BarcodeTrackingBasicOverlay.DefaultBrush.strokeWidth},styles:Object.fromEntries(Object.keys(e.BarcodeTracking.BarcodeTrackingBasicOverlay.styles).map(t=>[t,{DefaultBrush:{fillColor:Color.fromJSON(e.BarcodeTracking.BarcodeTrackingBasicOverlay.styles[t].DefaultBrush.fillColor),strokeColor:Color.fromJSON(e.BarcodeTracking.BarcodeTrackingBasicOverlay.styles[t].DefaultBrush.strokeColor),strokeWidth:e.BarcodeTracking.BarcodeTrackingBasicOverlay.styles[t].DefaultBrush.strokeWidth}}]))},RecommendedCameraSettings:CameraSettings.fromJSON(e.BarcodeTracking.RecommendedCameraSettings)},BarcodeFind:{CameraSettings:{hiddenProperties:{exposureTargetBias:e.BarcodeFind.CameraSettings.hiddenProperties.exposureTargetBias,grayScaleFrameReader:e.BarcodeFind.CameraSettings.hiddenProperties.grayScaleFrameReader},settings:CameraSettings.fromJSON(e.BarcodeFind.CameraSettings.settings)},BarcodeFindViewSettings:{settings:a$2.fromJSON(e.BarcodeFind.BarcodeFindViewSettings.settings)}},SparkScan:{SparkScanFeedback:{errorVibrationPattern:e.SparkScan.SparkScanFeedback.errorVibrationPattern},SparkScanSettings:{codeDuplicateFilter:e.SparkScan.SparkScanSettings.codeDuplicateFilter,locationSelection:{radius:e.SparkScan.SparkScanSettings.locationSelection.radius,unit:e.SparkScan.SparkScanSettings.locationSelection.unit},targetModeLocationSelection:{radius:e.SparkScan.SparkScanSettings.targetModeLocationSelection.radius,unit:e.SparkScan.SparkScanSettings.targetModeLocationSelection.unit},hiddenProperties:{zoom1x:{motion_scan_suppression_mode:e.SparkScan.SparkScanSettings.hiddenProperties.zoom1x.motion_scan_suppression_mode},zoom2x:{motion_scan_suppression_mode:e.SparkScan.SparkScanSettings.hiddenProperties.zoom2x.motion_scan_suppression_mode}}},SparkScanOverlay:{DefaultBrush:{fillColor:Color.fromJSON(e.SparkScan.SparkScanOverlay.DefaultBrush.fillColor),strokeColor:Color.fromJSON(e.SparkScan.SparkScanOverlay.DefaultBrush.strokeColor),strokeWidth:e.SparkScan.SparkScanOverlay.DefaultBrush.strokeWidth},defaultStyle:\"frame\"},CameraSettings:{hiddenProperties:{exposureTargetBias:e.SparkScan.CameraSettings.hiddenProperties.exposureTargetBias,grayScaleFrameReader:e.SparkScan.CameraSettings.hiddenProperties.grayScaleFrameReader,repeatedTriggerInterval:e.SparkScan.CameraSettings.hiddenProperties.repeatedTriggerInterval},settings:CameraSettings.fromJSON(e.SparkScan.CameraSettings.settings)},SparkScanViewSettings:{triggerButtonCollapseTimeout:e.SparkScan.SparkScanViewSettings.triggerButtonCollapseTimeout,defaultTorchState:e.SparkScan.SparkScanViewSettings.defaultTorchState,soundEnabled:e.SparkScan.SparkScanViewSettings.soundEnabled,hapticEnabled:e.SparkScan.SparkScanViewSettings.hapticEnabled,defaultHandMode:e.SparkScan.SparkScanViewSettings.defaultHandMode,holdToScanEnabled:e.SparkScan.SparkScanViewSettings.holdToScanEnabled,visualFeedbackEnabled:e.SparkScan.SparkScanViewSettings.visualFeedbackEnabled,inactiveStateTimeout:e.SparkScan.SparkScanViewSettings.inactiveStateTimeout,zoomFactorOut:e.SparkScan.SparkScanViewSettings.zoomFactorOut,zoomFactorIn:e.SparkScan.SparkScanViewSettings.zoomFactorIn}},SparkCapture:{SparkCaptureSettings:{codeDuplicateFilter:e.SparkCapture.SparkCaptureSettings.codeDuplicateFilter}}}),m=S({BarcodeCapture:{BarcodeCaptureSettings:{codeDuplicateFilter:0},BarcodeCaptureOverlay:{defaultStyle:\"frame\",DefaultBrush:{fillColor:\"#00000000\",strokeColor:\"#FFFFFFFF\",strokeWidth:3},styles:{frame:{DefaultBrush:{fillColor:\"#00000000\",strokeColor:\"#FFFFFFFF\",strokeWidth:3}}}},RecommendedCameraSettings:{zoomFactor:1,zoomGestureZoomFactor:2,focusGestureStrategy:\"manualUntilCapture\",preferredResolution:\"auto\"}},SymbologySettings:{ean13Upca:JSON.stringify({activeSymbolCounts:[12],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),ean8:JSON.stringify({activeSymbolCounts:[8],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),upce:JSON.stringify({activeSymbolCounts:[6],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),code128:JSON.stringify({activeSymbolCounts:[40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[\"strip_leading_fnc1\"]}),code39:JSON.stringify({activeSymbolCounts:[40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),code93:JSON.stringify({activeSymbolCounts:[40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),interleavedTwoOfFive:JSON.stringify({activeSymbolCounts:[40,38,36,34,32,30,28,26,24,22,20,18,16,14,12,10,8,6],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),qr:JSON.stringify({activeSymbolCounts:[],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),dataMatrix:JSON.stringify({activeSymbolCounts:[],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[\"strip_leading_fnc1\"]}),pdf417:JSON.stringify({activeSymbolCounts:[],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),msiPlessey:JSON.stringify({activeSymbolCounts:[32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),databar:JSON.stringify({activeSymbolCounts:[2],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),databarExpanded:JSON.stringify({activeSymbolCounts:[],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),codabar:JSON.stringify({activeSymbolCounts:[20,19,18,17,16,15,14,13,12,11,10,9,8,7],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),aztec:JSON.stringify({activeSymbolCounts:[],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),maxicode:JSON.stringify({activeSymbolCounts:[],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),code11:JSON.stringify({activeSymbolCounts:[20,19,18,17,16,15,14,13,12,11,10,9,8,7],checksums:[\"mod11\"],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),databarLimited:JSON.stringify({activeSymbolCounts:[1],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),code25:JSON.stringify({activeSymbolCounts:[20,19,18,17,16,15,14,13,12,11,10,9,8,7],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),microPdf417:JSON.stringify({activeSymbolCounts:[],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),rm4scc:JSON.stringify({activeSymbolCounts:[24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),kix:JSON.stringify({activeSymbolCounts:[24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),dotcode:JSON.stringify({activeSymbolCounts:[],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),microQr:JSON.stringify({activeSymbolCounts:[],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),code32:JSON.stringify({activeSymbolCounts:[8],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),lapa4sc:JSON.stringify({activeSymbolCounts:[16],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),iata2of5:JSON.stringify({activeSymbolCounts:[20,19,18,17,16,15,14,13,12,11,10,9,8,7],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),matrix2of5:JSON.stringify({activeSymbolCounts:[20,19,18,17,16,15,14,13,12,11,10,9,8,7],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]}),uspsIntelligentMail:JSON.stringify({activeSymbolCounts:[65],checksums:[],colorInvertedEnabled:!1,enabled:!1,extensions:[]})},BarcodeTracking:{BarcodeTrackingBasicOverlay:{defaultStyle:\"frame\",DefaultBrush:{fillColor:\"#00000000\",strokeColor:\"#FFFFFFFF\",strokeWidth:3},styles:{frame:{DefaultBrush:{fillColor:\"#00000000\",strokeColor:\"#FFFFFFFF\",strokeWidth:3}},dot:{DefaultBrush:{fillColor:\"#FFFFFFFF\",strokeColor:\"#FFFFFFFF\",strokeWidth:1}},legacy:{DefaultBrush:{fillColor:\"#00000000\",strokeColor:\"#FFFFFFFF\",strokeWidth:1}}}},RecommendedCameraSettings:{zoomFactor:1,zoomGestureZoomFactor:2,focusGestureStrategy:\"manualUntilCapture\",preferredResolution:\"fullHd\"}},BarcodeFind:{CameraSettings:{hiddenProperties:{exposureTargetBias:-1,grayScaleFrameReader:!0},settings:{zoomFactor:1,zoomGestureZoomFactor:1,focusGestureStrategy:\"manualUntilCapture\",preferredResolution:\"fullHd\"}},BarcodeFindViewSettings:{settings:{inListItemColor:Color.fromHex(\"#2EC1CE\").toJSON(),notInListItemColor:Color.fromHex(\"#FFFFFF\").toJSON(),hapticEnabled:!0,soundEnabled:!0}}},SparkScan:{SparkScanFeedback:{errorVibrationPattern:[600]},SparkScanSettings:{codeDuplicateFilter:1e3,locationSelection:{radius:.5,unit:MeasureUnit.Fraction},targetModeLocationSelection:{radius:.07,unit:MeasureUnit.Fraction},hiddenProperties:{zoom1x:{motion_scan_suppression_mode:1},zoom2x:{motion_scan_suppression_mode:2}}},SparkScanOverlay:{DefaultBrush:{fillColor:\"#00000000\",strokeColor:\"#FFFFFFFF\",strokeWidth:3},defaultStyle:\"frame\"},CameraSettings:{hiddenProperties:{exposureTargetBias:-1,grayScaleFrameReader:!0,repeatedTriggerInterval:1},settings:{focus:{focusGestureStrategy:FocusGestureStrategy.None},preferredResolution:VideoResolution.FullHD,zoomFactor:1,zoomGestureZoomFactor:2}},SparkScanViewSettings:{defaultHandMode:\"right\",defaultTorchState:TorchState.Off,hapticEnabled:!0,holdToScanEnabled:!0,soundEnabled:!0,triggerButtonCollapseTimeout:Number.POSITIVE_INFINITY,visualFeedbackEnabled:!0,inactiveStateTimeout:1e4,zoomFactorOut:1,zoomFactorIn:2}},CompositeTypeDescriptions:[JSON.stringify({symbologies:[\"ean8\",\"ean13Upca\",\"microPdf417\",\"databarLimited\",\"upce\",\"databar\",\"databarExpanded\"],types:[\"A\"]}),JSON.stringify({symbologies:[\"ean8\",\"ean13Upca\",\"microPdf417\",\"databarLimited\",\"upce\",\"databar\",\"databarExpanded\"],types:[\"B\"]}),JSON.stringify({symbologies:[\"code128\",\"pdf417\"],types:[\"C\"]})],SparkCapture:{SparkCaptureSettings:{codeDuplicateFilter:1e3}},SymbologyDescriptions:[JSON.stringify({activeSymbolCountRange:{maximum:12,minimum:12,step:1},defaultSymbolCountRange:{maximum:12,minimum:12,step:1},identifier:\"ean13Upca\",isAvailable:!0,isColorInvertible:!0,readableName:\"EAN-13/UPC-A\",supportedChecksums:[],supportedExtensions:[\"two_digit_add_on\",\"strict\",\"remove_leading_upca_zero\",\"relaxed_sharp_quiet_zone_check\",\"five_digit_add_on\"]}),JSON.stringify({activeSymbolCountRange:{maximum:8,minimum:8,step:1},defaultSymbolCountRange:{maximum:8,minimum:8,step:1},identifier:\"ean8\",isAvailable:!0,isColorInvertible:!0,readableName:\"EAN-8\",supportedChecksums:[],supportedExtensions:[\"two_digit_add_on\",\"strict\",\"relaxed_sharp_quiet_zone_check\",\"five_digit_add_on\"]}),JSON.stringify({activeSymbolCountRange:{maximum:6,minimum:6,step:1},defaultSymbolCountRange:{maximum:6,minimum:6,step:1},identifier:\"upce\",isAvailable:!0,isColorInvertible:!0,readableName:\"UPC-E\",supportedChecksums:[],supportedExtensions:[\"two_digit_add_on\",\"strict\",\"return_as_upca\",\"remove_leading_upca_zero\",\"five_digit_add_on\"]}),JSON.stringify({activeSymbolCountRange:{maximum:50,minimum:4,step:1},defaultSymbolCountRange:{maximum:40,minimum:6,step:1},identifier:\"code128\",isAvailable:!0,isColorInvertible:!0,readableName:\"Code 128\",supportedChecksums:[],supportedExtensions:[\"strict\"]}),JSON.stringify({activeSymbolCountRange:{maximum:50,minimum:3,step:1},defaultSymbolCountRange:{maximum:40,minimum:6,step:1},identifier:\"code39\",isAvailable:!0,isColorInvertible:!0,readableName:\"Code 39\",supportedChecksums:[\"mod43\"],supportedExtensions:[\"strict\",\"relaxed_sharp_quiet_zone_check\",\"full_ascii\"]}),JSON.stringify({activeSymbolCountRange:{maximum:60,minimum:5,step:1},defaultSymbolCountRange:{maximum:40,minimum:6,step:1},identifier:\"code93\",isAvailable:!0,isColorInvertible:!1,readableName:\"Code 93\",supportedChecksums:[],supportedExtensions:[\"strict\"]}),JSON.stringify({activeSymbolCountRange:{maximum:50,minimum:4,step:2},defaultSymbolCountRange:{maximum:40,minimum:6,step:2},identifier:\"interleavedTwoOfFive\",isAvailable:!0,isColorInvertible:!1,readableName:\"Interleaved Two of Five\",supportedChecksums:[],supportedExtensions:[\"strict\"]}),JSON.stringify({activeSymbolCountRange:{maximum:0,minimum:0,step:0},defaultSymbolCountRange:{maximum:0,minimum:0,step:0},identifier:\"qr\",isAvailable:!0,isColorInvertible:!0,readableName:\"QR Code\",supportedChecksums:[],supportedExtensions:[\"guess_encoding\"]}),JSON.stringify({activeSymbolCountRange:{maximum:0,minimum:0,step:0},defaultSymbolCountRange:{maximum:0,minimum:0,step:0},identifier:\"dataMatrix\",isAvailable:!0,isColorInvertible:!0,readableName:\"Data Matrix\",supportedChecksums:[],supportedExtensions:[\"direct_part_marking_mode\"]}),JSON.stringify({activeSymbolCountRange:{maximum:0,minimum:0,step:0},defaultSymbolCountRange:{maximum:0,minimum:0,step:0},identifier:\"pdf417\",isAvailable:!0,isColorInvertible:!1,readableName:\"PDF417\",supportedChecksums:[],supportedExtensions:[]}),JSON.stringify({activeSymbolCountRange:{maximum:32,minimum:3,step:1},defaultSymbolCountRange:{maximum:32,minimum:6,step:1},identifier:\"msiPlessey\",isAvailable:!0,isColorInvertible:!1,readableName:\"MSI Plessey\",supportedChecksums:[\"mod11\",\"mod1010\",\"mod1110\"],supportedExtensions:[\"strict\"]}),JSON.stringify({activeSymbolCountRange:{maximum:2,minimum:2,step:1},defaultSymbolCountRange:{maximum:2,minimum:2,step:1},identifier:\"databar\",isAvailable:!0,isColorInvertible:!1,readableName:\"GS1 DataBar 14\",supportedChecksums:[],supportedExtensions:[\"strict\"]}),JSON.stringify({activeSymbolCountRange:{maximum:0,minimum:0,step:0},defaultSymbolCountRange:{maximum:0,minimum:0,step:0},identifier:\"databarExpanded\",isAvailable:!0,isColorInvertible:!1,readableName:\"GS1 DataBar Expanded\",supportedChecksums:[],supportedExtensions:[\"strict\"]}),JSON.stringify({activeSymbolCountRange:{maximum:34,minimum:3,step:1},defaultSymbolCountRange:{maximum:20,minimum:7,step:1},identifier:\"codabar\",isAvailable:!0,isColorInvertible:!1,readableName:\"Codabar\",supportedChecksums:[\"mod11\",\"mod16\"],supportedExtensions:[\"strict\"]}),JSON.stringify({activeSymbolCountRange:{maximum:0,minimum:0,step:0},defaultSymbolCountRange:{maximum:0,minimum:0,step:0},identifier:\"aztec\",isAvailable:!0,isColorInvertible:!1,readableName:\"Aztec\",supportedChecksums:[],supportedExtensions:[]}),JSON.stringify({activeSymbolCountRange:{maximum:0,minimum:0,step:0},defaultSymbolCountRange:{maximum:0,minimum:0,step:0},identifier:\"maxicode\",isAvailable:!0,isColorInvertible:!1,readableName:\"MaxiCode\",supportedChecksums:[],supportedExtensions:[]}),JSON.stringify({activeSymbolCountRange:{maximum:34,minimum:5,step:1},defaultSymbolCountRange:{maximum:20,minimum:7,step:1},identifier:\"code11\",isAvailable:!0,isColorInvertible:!1,readableName:\"Code 11\",supportedChecksums:[\"mod11\"],supportedExtensions:[\"strict\"]}),JSON.stringify({activeSymbolCountRange:{maximum:1,minimum:1,step:1},defaultSymbolCountRange:{maximum:1,minimum:1,step:1},identifier:\"databarLimited\",isAvailable:!0,isColorInvertible:!1,readableName:\"GS1 DataBar Limited\",supportedChecksums:[],supportedExtensions:[\"strict\"]}),JSON.stringify({activeSymbolCountRange:{maximum:32,minimum:3,step:1},defaultSymbolCountRange:{maximum:20,minimum:7,step:1},identifier:\"code25\",isAvailable:!0,isColorInvertible:!1,readableName:\"Code 25\",supportedChecksums:[],supportedExtensions:[\"strict\"]}),JSON.stringify({activeSymbolCountRange:{maximum:0,minimum:0,step:0},defaultSymbolCountRange:{maximum:0,minimum:0,step:0},identifier:\"microPdf417\",isAvailable:!0,isColorInvertible:!1,readableName:\"MicroPDF417\",supportedChecksums:[],supportedExtensions:[]}),JSON.stringify({activeSymbolCountRange:{maximum:50,minimum:4,step:1},defaultSymbolCountRange:{maximum:24,minimum:7,step:1},identifier:\"rm4scc\",isAvailable:!0,isColorInvertible:!1,readableName:\"RM4SCC\",supportedChecksums:[],supportedExtensions:[]}),JSON.stringify({activeSymbolCountRange:{maximum:50,minimum:4,step:1},defaultSymbolCountRange:{maximum:24,minimum:7,step:1},identifier:\"kix\",isAvailable:!0,isColorInvertible:!1,readableName:\"KIX\",supportedChecksums:[],supportedExtensions:[]}),JSON.stringify({activeSymbolCountRange:{maximum:0,minimum:0,step:0},defaultSymbolCountRange:{maximum:0,minimum:0,step:0},identifier:\"dotcode\",isAvailable:!0,isColorInvertible:!0,readableName:\"DotCode\",supportedChecksums:[],supportedExtensions:[]}),JSON.stringify({activeSymbolCountRange:{maximum:0,minimum:0,step:0},defaultSymbolCountRange:{maximum:0,minimum:0,step:0},identifier:\"microQr\",isAvailable:!0,isColorInvertible:!0,readableName:\"Micro QR\",supportedChecksums:[],supportedExtensions:[]}),JSON.stringify({activeSymbolCountRange:{maximum:8,minimum:8,step:1},defaultSymbolCountRange:{maximum:8,minimum:8,step:1},identifier:\"code32\",isAvailable:!0,isColorInvertible:!1,readableName:\"Code 32\",supportedChecksums:[],supportedExtensions:[\"strict\"]}),JSON.stringify({activeSymbolCountRange:{maximum:16,minimum:16,step:1},defaultSymbolCountRange:{maximum:16,minimum:16,step:1},identifier:\"lapa4sc\",isAvailable:!0,isColorInvertible:!1,readableName:\"LAPA4SC\",supportedChecksums:[],supportedExtensions:[]}),JSON.stringify({activeSymbolCountRange:{maximum:32,minimum:3,step:1},defaultSymbolCountRange:{maximum:20,minimum:7,step:1},identifier:\"iata2of5\",isAvailable:!0,isColorInvertible:!1,readableName:\"IATA 2 of 5\",supportedChecksums:[\"mod1010\"],supportedExtensions:[\"strict\"]}),JSON.stringify({activeSymbolCountRange:{maximum:32,minimum:3,step:1},defaultSymbolCountRange:{maximum:20,minimum:7,step:1},identifier:\"matrix2of5\",isAvailable:!0,isColorInvertible:!1,readableName:\"Matrix 2 of 5\",supportedChecksums:[],supportedExtensions:[\"strict\"]}),JSON.stringify({activeSymbolCountRange:{maximum:65,minimum:65,step:1},defaultSymbolCountRange:{maximum:65,minimum:65,step:1},identifier:\"uspsIntelligentMail\",isAvailable:!0,isColorInvertible:!1,readableName:\"USPS Intelligent Mail\",supportedChecksums:[],supportedExtensions:[]})]});function C(e){m=e;}a.defaults=()=>({SymbologyDescriptions:m.SymbologyDescriptions});\n\nexport { S as a, m as b, C as c };\n", "var a=class t{get endIndex(){return this._endIndex}get ianaName(){return this._ianaName}get startIndex(){return this._startIndex}static fromJSON(n){let e=new t;return e._ianaName=n.ianaName,e._startIndex=n.startIndex,e._endIndex=n.endIndex,e}toJSONObject(){return {endIndex:this.endIndex,ianaName:this.ianaName,startIndex:this.startIndex}}};\n\nexport { a };\n", "import { a as a$1 } from './chunk-J4VFWBJ7.js';\n\nvar a=class o{get barcodeSetId(){return this._barcodeSetId}get completeData(){return this._completeData}get encodingRanges(){return this._encodingRanges}get isComplete(){return this._complete}get rawCompleteData(){return this._rawCompleteData}get scannedSegmentCount(){return this._scannedSegmentCount}get totalSegmentCount(){return this._totalSegmentCount}static fromJSON(e){if(e==null)return null;let t=new o;return t._complete=e.complete,t._barcodeSetId=e.barcodeSetId,t._scannedSegmentCount=e.scannedSegmentCount,t._totalSegmentCount=e.totalSegmentCount,t._encodingRanges=e.completeDataEncodings.map(r=>a$1.fromJSON(r)),t._completeData=e.completeDataUtf8String,t._rawCompleteData=e.completeDataRaw,t}toJSONObject(){return {complete:this._complete,barcodeSetId:this.barcodeSetId,scannedSegmentCount:this.scannedSegmentCount,totalSegmentCount:this.totalSegmentCount,completeDataEncodings:this._encodingRanges.map(e=>e.toJSONObject()),completeDataUtf8String:this.completeData,completeDataRaw:this.rawCompleteData}}};\n\nexport { a };\n", "import { a as a$1 } from './chunk-IEE5MKEA.js';\nimport { a } from './chunk-J4VFWBJ7.js';\nimport { Quadrilateral } from 'scandit-web-datacapture-core';\n\nvar l=(t=>(t.EAN13UPCA=\"ean13Upca\",t.UPCE=\"upce\",t.EAN8=\"ean8\",t.Code39=\"code39\",t.Code93=\"code93\",t.Code128=\"code128\",t.Code11=\"code11\",t.Code25=\"code25\",t.Codabar=\"codabar\",t.InterleavedTwoOfFive=\"interleavedTwoOfFive\",t.MSIPlessey=\"msiPlessey\",t.QR=\"qr\",t.DataMatrix=\"dataMatrix\",t.Aztec=\"aztec\",t.MaxiCode=\"maxicode\",t.DotCode=\"dotcode\",t.KIX=\"kix\",t.RM4SCC=\"rm4scc\",t.GS1Databar=\"databar\",t.GS1DatabarExpanded=\"databarExpanded\",t.GS1DatabarLimited=\"databarLimited\",t.PDF417=\"pdf417\",t.MicroPDF417=\"microPdf417\",t.MicroQR=\"microQr\",t.Code32=\"code32\",t.Lapa4SC=\"lapa4sc\",t.IATATwoOfFive=\"iata2of5\",t.MatrixTwoOfFive=\"matrix2of5\",t.USPSIntelligentMail=\"uspsIntelligentMail\",t))(l||{}),D=(r=>(r.A=\"A\",r.B=\"B\",r.C=\"C\",r))(D||{}),m=(i=>(i.Mod10=\"mod10\",i.Mod11=\"mod11\",i.Mod16=\"mod16\",i.Mod43=\"mod43\",i.Mod47=\"mod47\",i.Mod103=\"mod103\",i.Mod10AndMod11=\"mod1110\",i.Mod10AndMod10=\"mod1010\",i))(m||{}),g=(n=>(n.None=\"none\",n.Unknown=\"unknown\",n.Linked=\"linked\",n.GS1TypeA=\"gs1TypeA\",n.GS1TypeB=\"gs1TypeB\",n.GS1TypeC=\"gs1TypeC\",n))(g||{}),s=class c{get isStructuredAppend(){return this._structuredAppendData!=null}get structuredAppendData(){return this._structuredAppendData}get addOnData(){return this._addOnData}get compositeData(){return this._compositeData}get compositeFlag(){return this._compositeFlag}get compositeRawData(){return this._compositeRawData}get data(){return this._data}get encodingRanges(){return this._encodingRanges}get frameID(){return this._frameID}get isColorInverted(){return this._isColorInverted}get isGS1DataCarrier(){return this._isGS1DataCarrier}get location(){return this._location}get rawData(){return this._rawData}get symbolCount(){return this._symbolCount}get symbology(){return this._symbology}static fromJSON(e){var r;let a$2=new c;return a$2._symbology=e.symbology,a$2._data=e.data,a$2._rawData=e.rawData,a$2._compositeData=e.compositeData,a$2._compositeRawData=e.compositeRawData,a$2._addOnData=(r=e.addOnData)!=null?r:null,a$2._isGS1DataCarrier=e.isGS1DataCarrier,a$2._compositeFlag=e.compositeFlag,a$2._isColorInverted=e.isColorInverted,a$2._symbolCount=e.symbolCount,a$2._frameID=e.frameId,a$2._encodingRanges=e.encodingRanges.map(o=>a.fromJSON(o)),a$2._location=Quadrilateral.fromJSON(e.location),a$2._structuredAppendData=a$1.fromJSON(e.structuredAppendData),a$2}toJSONObject(){var e,a,r;return {symbology:this.symbology.toString(),data:this.data,rawData:this.rawData,compositeData:this.compositeData,compositeRawData:this.compositeRawData,addOnData:(e=this.addOnData)!=null?e:null,isGS1DataCarrier:this.isGS1DataCarrier,compositeFlag:this.compositeFlag.toString(),isColorInverted:this.isColorInverted,symbolCount:this.symbolCount,frameId:this.frameID,encodingRanges:this.encodingRanges.map(o=>o.toJSONObject()),location:this.location.toJSONObject(),structuredAppendData:(r=(a=this.structuredAppendData)==null?void 0:a.toJSONObject())!=null?r:null}}};\n\nexport { l as a, D as b, m as c, g as d, s as e };\n", "import { DataCaptureLoader, Logger } from 'scandit-web-datacapture-core';\n\nvar u=URL.createObjectURL(new Blob(['\"use strict\";(()=>{var u={\"scandit-datacapture-sdk-barcode-pthreads.wasm\":{bytes:6971587},\"scandit-datacapture-sdk-barcode.wasm\":{bytes:7294658},\"scandit-datacapture-sdk-barcode-simd-pthreads.wasm\":{bytes:7136016},\"scandit-datacapture-sdk-parser-pthreads.wasm\":{bytes:5237179},\"scandit-datacapture-sdk-barcode-simd.wasm\":{bytes:7492951},\"scandit-datacapture-sdk-parser-simd-pthreads.wasm\":{bytes:5233910},\"scandit-datacapture-sdk-parser-simd.wasm\":{bytes:5661082},\"scandit-datacapture-sdk-parser.wasm\":{bytes:5629124}};function v(t){return typeof t==\"object\"&&t!=null}function M(t){if(typeof t==\"string\")return t;if(v(t)){if(typeof t.message==\"string\")return t.message}else if(typeof t?.toString==\"function\")return t.toString();return\"unknown error\"}var d;(t=>{(s=>(s.Debug=\"debug\",s.Info=\"info\",s.Warn=\"warn\",s.Error=\"error\",s.Quiet=\"quiet\"))(t.Level||(t.Level={}));let e=new Map([[\"debug\",1],[\"info\",2],[\"warn\",3],[\"error\",4],[\"quiet\",5]]),a=\"debug\";function r(s){a=s}t.setLevel=r;function i(s,...n){if(!(e.get(a)>e.get(s)))switch(s){case\"debug\":console.debug(...n);break;case\"info\":console.log(...n);break;case\"warn\":console.warn(...n);break;case\"error\":console.error(...n);break}}t.log=i})(d||(d={}));var O=class Q extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,Q.prototype),this.name=e.name}toString(){return`${this.name}: ${this.message}`}};var L=Promise.resolve(),J=!1,V=!1,k,U={writableDataPath:\"\"};async function ee(t){if(k==null)return;J=!0;let e=new Promise((a,r)=>{setTimeout(()=>{r(new O({name:\"BlockedIndexedDB\",message:\"IndexedDB database is blocked\"}))},1500)});try{await Promise.race([new Promise((a,r)=>{k?.(t,i=>{if(i!=null){r(i);return}a()})}),e])}finally{J=!1}}async function te(t){return V||(J?(V=!0,L=L.then(async()=>(V=!1,ee(t)))):L=ee(t)),L}async function ae(t){U=t,k=FS.syncfs,FS.syncfs=(e,a)=>{let r=a,i=s=>{r(s)};te(e).then(i).catch(i)};try{FS.mkdir(U.writableDataPath)}catch(e){if(e.code!==\"EEXIST\")throw k=void 0,e}return FS.mount(IDBFS,{},U.writableDataPath),te(!0)}var $=(t,e)=>(e=Symbol[t])?e:Symbol.for(\"Symbol.\"+t);var G=function(t,e){this[0]=t,this[1]=e},re=(t,e,a)=>{var r=(n,o,c,l)=>{try{var h=a[n](o),b=(o=h.value)instanceof G,m=h.done;Promise.resolve(b?o[0]:o).then(g=>b?r(n===\"return\"?n:\"next\",o[1]?{done:g.done,value:g.value}:g,c,l):c({value:g,done:m})).catch(g=>r(\"throw\",g,c,l))}catch(g){l(g)}},i=n=>s[n]=o=>new Promise((c,l)=>r(n,o,c,l)),s={};return a=a.apply(t,e),s[$(\"asyncIterator\")]=()=>s,i(\"next\"),i(\"throw\"),i(\"return\"),s},ie=(t,e,a)=>(e=t[$(\"asyncIterator\")])?e.call(t):(t=t[$(\"iterator\")](),e={},a=(r,i)=>(i=t[r])&&(e[r]=s=>new Promise((n,o,c)=>(s=i.call(t,s),c=s.done,Promise.resolve(s.value).then(l=>n({value:l,done:c}),o)))),a(\"next\"),a(\"return\"),e);var se={};function Oe(t){return[...new Uint8Array(t)].map(e=>{let a=e.toString(16);return a.length===1?`0${a}`:a}).join(\"\")}function Le(t){return re(this,null,function*(){let e=t.getReader();try{for(;;){let{done:a,value:r}=yield new G(e.read());if(a)return;yield r}}finally{e.releaseLock()}})}async function Ie(t){let e=[],a=0,r=0;try{for(var i=ie(Le(t)),s,n,o;s=!(n=await i.next()).done;s=!1){let l=n.value;e.push(l),a+=l.length}}catch(l){o=[l]}finally{try{s&&(n=i.return)&&await n.call(i)}finally{if(o)throw o[0]}}let c=new Uint8Array(a);for(let l of e)c.set(l,r),r+=l.length;return c.buffer}var Ae=(t=>(t.VALID=\"VALID\",t.INVALID=\"INVALID\",t.NOT_VERIFIABLE=\"NOT_VERIFIABLE\",t))(Ae||{});async function We(t,e,a){if(typeof crypto.subtle.digest!=\"function\")return d.log(d.Level.Warn,`Insecure context (see https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts): The hash of the Scandit Data Capture library WASM file found at ${a} could not be verified`),\"NOT_VERIFIABLE\";try{let r=t instanceof Promise?await t:t,i=await crypto.subtle.digest(\"SHA-256\",r),s=Oe(i);return e==null?(d.log(d.Level.Warn,\"The library hash is not defined or empty, cannot correctly verify integrity.\"),\"NOT_VERIFIABLE\"):s===e?(d.log(d.Level.Debug,\"Data Capture library WASM integrity has been verified correctly.\"),\"VALID\"):(d.log(d.Level.Warn,`The Scandit Data Capture library WASM file found at ${a} seems invalid: expected file hash doesn\\'t match (received: ${s}, expected: ${e}). Please ensure the correct Scandit Data Capture file (with correct version) is retrieved.`),\"INVALID\")}catch(r){return d.log(d.Level.Warn,\"Wasm response could not be verified\",r),\"NOT_VERIFIABLE\"}}var j=new Map([[\"br\",4.4],[\"gzip\",2.9],[\"none\",1]]);function Be(t){var e;let a=\"content-encoding\";if(t==null||t.get(a)==null)return j.get(\"none\");let r=new Set(((e=t.get(a))!=null?e:\"\").split(\",\").map(i=>i.trim()));for(let[i,s]of j)if(r.has(i))return s;return j.get(\"none\")}function Pe(t){var e,a;if(t==null)return 0;let r=(e=Be(t))!=null?e:1,i=Number.parseInt((a=t.get(\"content-length\"))!=null?a:\"0\",10);return Number.isNaN(i)?0:Math.floor(i*r*100)/100}function Ee(t){let{pathname:e}=new URL(t);for(let[a,r]of Object.entries(se))if(e.endsWith(a))return r.bytes;return 0}function ne(t){se=t}var Re=(t,e)=>{let a=Pe(e);return a===0?Ee(t):a};function Ne(t,e,a,{onProgress:r,onError:i,onComplete:s}){if(!e.body)return[e];let n=Re(t,e.headers),o=0,c=0,[l,h]=a?e.body.tee():[e.body],b=l.pipeThrough(new TransformStream({async transform(m,g){try{o+=m.length,c=Number((o/n*100).toFixed(2)),n>0&&m.length>0&&c<100?r?.({percentage:c,loadedBytes:o,privateUri:t}):n===0&&m.length>0&&r?.({percentage:null,loadedBytes:o,privateUri:t}),g.enqueue(m)}catch(y){g.error(y),i?.({error:y})}},flush(m){r?.({percentage:100,loadedBytes:o,privateUri:t}),s?.({percentage:100,loadedBytes:o,privateUri:t}),m.terminate()}}));return[new Response(b,{headers:new Headers(e.headers),status:e.status,statusText:e.statusText}),h]}async function q({wasmURI:t,expectedHash:e,verifyResponseHash:a,onProgress:r,onComplete:i,onError:s,referredOrigin:n}){let o=await fetch(t,{referrerPolicy:\"origin\",referrer:n??\"\"});if(!o.ok)throw new Error(`HTTP status code is not ok: ${o.status}, ${o.statusText}`);let[c,l]=Ne(t,o,a,{onProgress:r,onError:s,onComplete:i});return l!=null&&We(Ie(l),e,t),c}function oe({wasmURI:t,expectedHash:e,verifyResponseHash:a,progressCallback:r,successCallback:i,importObject:s,referredOrigin:n}){async function o(l){try{let h=await q({wasmURI:t,expectedHash:e,verifyResponseHash:a,onProgress:r,referredOrigin:n}),b=await(l??h).arrayBuffer(),m=await globalThis.WebAssembly.instantiate(b,s);i(m.instance,m.module)}catch(h){d.log(d.Level.Error,h),d.log(d.Level.Error,`Couldn\\'t instantiate Scandit SDK DataCapture library at ${t}, did you configure the path for it correctly?`)}}async function c(){let l;try{l=await q({wasmURI:t,expectedHash:e,verifyResponseHash:a,onProgress:r,referredOrigin:n});let h=await globalThis.WebAssembly.instantiateStreaming(l,s);i(h.instance,h.module)}catch(h){d.log(d.Level.Warn,h),d.log(d.Level.Warn,\"WebAssembly streaming compile failed. Falling back to ArrayBuffer instantiation (this will make things slower)\"),o(l?.bodyUsed===!0?void 0:l)}}typeof globalThis.WebAssembly.instantiateStreaming==\"function\"?c():o()}async function K(t,e,a,r){return new Promise((i,s)=>{t().then(i).catch(n=>{let o=e*2;if(o>a){s(n);return}r(n),globalThis.setTimeout(()=>{K(t,o,a,r).then(i).catch(s)},e)})})}function X(t){var e,a;let r=\"\";if((e=t.href)!=null&&e.startsWith(\"blob:null/\"))r=\"localhost\";else{let i=((a=t.pathname)==null?void 0:a.length)>1&&!t.pathname.startsWith(\"/\");r=new URL(i?t.pathname:t.origin).hostname}return r.startsWith(\"[\")&&r.endsWith(\"]\")&&(r=r.slice(1,-1)),r}async function de(t,e){async function a(){return importScripts(t)}try{await K(a,250,4e3,i=>{d.log(d.Level.Warn,i),d.log(d.Level.Warn,`Couldn\\'t retrieve Scandit Data Capture library at ${t}, retrying...`)}),self.Module.mainScriptUrlOrBlob=t;let r=globalThis.SDC_WASM_JS_VERSION;return r!==e&&d.log(d.Level.Warn,`The Scandit Data Capture library JS file found at ${t} seems invalid: expected version doesn\\'t match (received: ${r}, expected: ${e}). Please ensure the correct Scandit Data Capture file (with correct version) is retrieved.`),!0}catch(r){return d.log(d.Level.Error,r),!1}}function _e(t){return/^https?:\\\\/\\\\/(?:[^./]*\\\\.)*cdn.jsdelivr.net\\\\//.test(t)?{result:!0,cdnBaseURL:\"https://cdn.jsdelivr.net/npm/\"}:/^https?:\\\\/\\\\/(?:[^./]*\\\\.)*unpkg.com\\\\//.test(t)?{result:!0,cdnBaseURL:\"https://unpkg.com/\"}:{result:!1,cdnBaseURL:\"\"}}function He(t){let e=/scandit-web-datacapture-[a-z]+/i.exec(t);return e?e[0]:null}function ce(t,e,a){let r=e,i=_e(r);if(i.result){let n=He(r);n!=null&&(r=`${i.cdnBaseURL}${n}@${t}/build/engine/`)}let s=a.replace(\".wasm\",\"\");return i.result?{jsURI:`${r}${s}.js`,wasmURI:`${r}${s}.wasm`}:{jsURI:`${r}${s}.js?v=${t}`,wasmURI:`${r}${s}.wasm?v=${t}`}}var I;(t=>{function e(){return\"6.28.7\"}t.sdkVersion=e})(I||(I={}));var le=class{constructor(){this.promise=new Promise((t,e)=>{this.reject=e,this.resolve=t})}};var ze=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),Ve=()=>(async t=>{try{return typeof MessageChannel<\"u\"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(t)}catch{return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]));function Ue(){return typeof crossOriginIsolated>\"u\"?!1:crossOriginIsolated}function Je(){try{return new WebAssembly.Memory({initial:1,maximum:1,shared:!0}).buffer.constructor.name===\"SharedArrayBuffer\"}catch{return!1}}async function ue(){return ze()}async function $e(){if(!await Ve())return!1;let t=null;try{t=new Worker(URL.createObjectURL(new Blob([\\'postMessage(\"Worker\" in self);\\'],{type:\"text/javascript\"})),{name:\"nestedWorkerTest\"})}catch{return!1}return new Promise(e=>{if(t==null){e(!1);return}t.onmessage=a=>{t?.terminate(),e(a.data)}})}async function pe(){let t=await $e();return Ue()&&Je()&&t}var he=class me{constructor(e,a){this.hintPresenterV2=null,this.MAX_NUMBER_OF_IMAGES_IN_FRAME_DATA_POOL=10,this.redrawInterval=1e3/30,this.redrawRequests=[],this._isDrawLoopRunning=!1,this.frameDataPool=new Map,this.lastFrameCounter=-1,this.poorMansBenchmarkLogs=!1,this.writableDataPathStandard=\"/scandit_sync_folder\",this.resourceFilesSubfolder=\"resources\",this.performanceMetricsReporterTimer=void 0,this.performanceMetrics={frameDataPoolSize:0,processedFramesCount:0,redrawRequestsCount:0,actualRedrawsCount:0},this.gestureListener=null,this.webPlatformHintPresenter=null,this.moduleHandler=e,this.workerFunctions=a,this._loadProgressCallback=this._loadProgressCallback.bind(this),ne(this.getWasmMetadata())}get Module(){return this.moduleHandler.get()}set isDrawLoopRunning(e){this._isDrawLoopRunning=e,!e&&typeof this.loopTimeoutId==\"number\"&&(clearTimeout(this.loopTimeoutId),this.loopTimeoutId=void 0)}get isDrawLoopRunning(){return this._isDrawLoopRunning}convertToLoadableFrameData(e){let a=this.getNextFrameId();this.frameDataPool.set(a,new Uint8ClampedArray(e.getFrameData()));let r=this.lastUsedModuleMirrorAxis==null?!1:this.lastUsedModuleMirrorAxis!==this.Module.Axis.None;return{frameId:a,width:e.getWidth(),height:e.getHeight(),isFrameSourceMirrored:r}}createContext(e){var a,r,i,s,n;let o=this.getModeDeserializers(),c=X(location);(c===\"localhost\"||c===\"127.0.0.1\")&&navigator.userAgent.includes(\"Electron\")&&e.appName!=null&&(c+=`-${e.appName}`),this.parentDomain=e.parentDomain,this.contextDeserializer=new this.Module.DataCaptureContextDeserializer(this.writableDataPath,e.deviceId,e.context.deviceModelName,c,this.parentDomain,o,e.delayedRegistration,e.highEndBlurryRecognition,this.resourcePath);let l=this.contextDeserializer.contextFromJson(JSON.stringify(e.context));if(l==null)throw new Error(\"Could not create the context\");let h=l.getView();this.context=l.getContext(),l.delete();let b=this.Module.DataCaptureContextListener.extend(\"DataCaptureContextListener\",{didChangeStatus:(p,S)=>{this.contextDidChangeStatus(JSON.parse(S.toJson()))},didStartObservingContext:()=>{this.didStartObservingContext()}}),m=this.Module.DataCaptureContextFrameListener.extend(\"DataCaptureContextFrameListener\",{onObservationStarted:p=>{},onObservationStopped:p=>{},onFrameProcessingStarted:(p,S)=>{this.workerFunctions.postMessage({type:\"onFrameProcessingStarted\"})},onFrameProcessingFinished:(p,S)=>{this.workerFunctions.postMessage({type:\"onFrameProcessingFinished\"})},onFrameSkipped:(p,S)=>{this.workerFunctions.postMessage({type:\"onFrameSkipped\"})}}),g=this.Module.GestureRecognizer.extend(\"GestureRecognizer\",{setGestureListener:(p,S)=>{var T;(T=this.gestureListener)==null||T.delete(),this.gestureListener=p.clone()}});(a=this.gestureRecognizer)==null||a.delete(),this.gestureRecognizer=new g;let y=new b;this.context.addListener(y),y.delete();let w=new m;this.context.addFrameListener(w),w.delete(),this.setView(h),(r=this.view)==null||r.setGestureRecognizer(this.gestureRecognizer);let F=this.Module.PlatformHintPresenter.extend(\"PlatformHintPresenter\",{setHintPresenter:p=>{},showToast:p=>{this.workerFunctions.postMessage({type:\"showToast\",payload:JSON.parse(p)})},hideToast:p=>{this.workerFunctions.postMessage({type:\"hideToast\",payload:JSON.parse(p)})},showGuidance:p=>{this.workerFunctions.postMessage({type:\"showGuidance\",payload:JSON.parse(p)})},hideGuidance:p=>{this.workerFunctions.postMessage({type:\"hideGuidance\",payload:JSON.parse(p)})},startUpdateTimer:p=>{this.workerFunctions.postMessage({type:\"startUpdateTimer\",payload:{duration:{unit:\"ms\",value:p}}})},stopUpdateTimer:()=>{this.workerFunctions.postMessage({type:\"stopUpdateTimer\"})}});(i=this.hintPresenterV2)==null||i.delete(),(s=this.webPlatformHintPresenter)==null||s.delete(),this.webPlatformHintPresenter=new F,this.hintPresenterV2=new this.Module.HintPresenterV2(this.webPlatformHintPresenter),(n=this.view)==null||n.setHintPresenterV2(this.hintPresenterV2)}onTap(e){var a;(a=this.gestureListener)==null||a.onTap(JSON.stringify(e))}hintPresenterV2Update(){var e;(e=this.hintPresenterV2)==null||e.update()}startReportingPerformanceMetrics(){this.performanceMetricsReporterTimer==null&&(this.performanceMetricsReporterTimer=setInterval(()=>{this.reportPerformanceMetrics();for(let e of Object.keys(this.performanceMetrics))this.performanceMetrics[e]=0},1e3))}async reportPerformanceMetrics(){this.workerFunctions.postMessage({type:\"performanceMetricsReport\",payload:{...this.performanceMetrics}})}deleteFrameData(e){this.frameDataPool.delete(e)}dispose(){var e,a;this.context.dispose(),this.frameDataPool.clear(),this.isDrawLoopRunning=!1,this.lastFrameCounter=-1,(e=this.gestureRecognizer)==null||e.delete(),this.gestureRecognizer=null,(a=this.gestureListener)==null||a.delete(),this.gestureListener=null}flushAnalytics(){this.context.flushAnalytics()}extractCentaurusLicense(e){return{payload:{centaurus:{licenseKey:this.Module.LicenseUtils[me.get3dPartyLicenseKeyMethodName](e)}}}}getModeDeserializers(){return new this.Module.VectorDataCaptureModeDeserializer}loadLibrary(e){return this.libraryLoadingPromise!=null?this.libraryLoadingPromise:(this.libraryLoadingPromise=this.setup(e),this.libraryLoadingPromise)}processFrame(e){var a;if(this.context==null)return{payload:e,transferables:[e.data.buffer]};let r=e.data,i=e.colorType===\"GRAYSCALE\"?this.Module.ImageBufferFormat.Grayscale8:this.Module.ImageBufferFormat.Rgba8888,s=this.Module.allocateUint8Array(r.byteLength);return this.Module.HEAPU8.set(r,s),(a=this.imageFrameSource)==null||a.outputFrame(s,e.width,e.height,i),{payload:e,transferables:[e.data.buffer]}}reportCameraProperties(e){this.context.setCameraProperties(e.deviceId,e.isFrontFacing,e.hasAutofocus)}requestFrameData(e){let a=this.frameDataPool.get(e);return a==null?{payload:{data:null}}:{payload:{data:a},transferables:[a.buffer]}}scheduleRedraw(e,a){this.addRedrawRequest(a),this.isDrawLoopRunning||this.startDrawLoop(e)}sendViewRefreshCommands(e){this.workerFunctions.postMessage({type:\"draw\",payload:e},[e.buffer])}setFrameSource(e,a){var r;this.lastUsedModuleMirrorAxis=this.mapMirrorAxisOnModule(e),(r=this.imageFrameSource)==null||r.delete(),this.imageFrameSource=new this.Module.ImageBufferFrameSource(this.lastUsedModuleMirrorAxis,a,0),this.context.setFrameSource(this.imageFrameSource)}startDrawLoop(e){this.isDrawLoopRunning=!0;let a=s=>this.redrawRequests.length>0&&this.redrawRequests[0]<=s,r=s=>{for(;this.redrawRequests.length>0&&this.redrawRequests[0]<=s;)this.redrawRequests.shift()},i=()=>{this.loopTimeoutId=setTimeout(()=>{if(!this.isDrawLoopRunning)return;let s=performance.now();if(a(s)){r(s),e.draw();let n=e.getDrawCommands();this.sendViewRefreshCommands(new Uint8Array(n))}i()},this.redrawInterval)};i()}updateContext(e){if(this.context!=null&&this.contextDeserializer!=null){e.view!=null&&!e.view.visible&&this.context.flushAnalytics();let a=this.contextDeserializer.updateContextFromJson(this.context,this.view,JSON.stringify(e.context));if(a==null)throw new Error(\"Could not update the context\");this.context.delete(),this.context=a.getContext();let r=a.getView();a.delete(),r!=null&&e.view!=null&&r.setViewSize(e.view.width,e.view.height,e.view.orientation),this.hintPresenterV2!=null&&r?.setHintPresenterV2(this.hintPresenterV2),this.gestureRecognizer!=null&&r?.setGestureRecognizer(this.gestureRecognizer),this.setView(r),d.log(d.Level.Debug,\"context updated\",e)}}onDocumentVisibilityChange(e){e===\"hidden\"&&this.context.flushAnalytics()}isFeatureSupported(e){return{payload:{supported:this.context.isFeatureSupported(e)}}}getViewfinderInfo(){var e,a;return{payload:{isDisplayingViewfinder:(a=(e=this.view)==null?void 0:e.isDisplayingViewfinder())!=null?a:!1,rect:JSON.parse(this.view.getViewfinderRect())}}}getNextFrameId(){return this.lastFrameCounter++,this.lastFrameCounter>=this.MAX_NUMBER_OF_IMAGES_IN_FRAME_DATA_POOL&&(this.lastFrameCounter=0),this.lastFrameCounter}getWasmDynamicLibraries(e){return this.getWasmSideModuleFileName()==null?[]:[`${e.replace(/\\\\/[^/]*$/,\"/\")}${this.getWasmSideModuleFileName()}`]}getWasmCoreExpectedHash(e,a){return a?e?\"0497629ae7746bbb2c9befc2ba9086882c73e1a5029e40f52382e9329c744110\":\"acd5b393969de53839d18ea0584116f7efba63469c188410a6769f8fc9120243\":e?\"abf5780ce18056e02d433c67dc5c59496430285c990240ed100b1842ae9bd352\":\"\"}getWasmCoreFileName(e,a){return a?e?\"scandit-datacapture-sdk-barcode-simd-pthreads.wasm\":\"scandit-datacapture-sdk-barcode-pthreads.wasm\":e?\"scandit-datacapture-sdk-barcode-simd.wasm\":\"\"}getWasmMetadata(){return u}getWasmSideModuleFileName(){return\"\"}_loadProgressCallback(e){this.workerFunctions.postMessage({type:\"loadLibraryProgress\",payload:e})}addRedrawRequest(e){this.redrawRequests.push(Math.round(performance.now())+e),this.redrawRequests.sort((a,r)=>a-r)}contextDidChangeStatus(e){e.code===260?e.message=e.message.replace(\"domain name\",`domain name (${X(location)})`):e.code===265&&(e.message=e.message.replace(\"domain name\",`domain name (${this.parentDomain})`)),this.workerFunctions.postMessage({type:\"contextDidChangeStatus\",payload:e})}didStartObservingContext(){this.workerFunctions.postMessage({type:\"didStartObservingContext\"})}mapMirrorAxisOnModule(e){switch(e){case\"None\":return this.Module.Axis.None;case\"X\":return this.Module.Axis.X;case\"Y\":return this.Module.Axis.Y;default:return this.Module.Axis.None}}setView(e){this.view=e,this.setViewRefreshHandler(e),e==null&&(this.isDrawLoopRunning=!1,this.sendViewRefreshCommands(new Uint8Array([])))}setViewRefreshHandler(e){if(e==null||e.isViewRefreshHandlerSet)return;let a=this.Module.NeedsRedrawDelegate.extend(\"NeedsRedrawDelegate\",{setNeedsRedrawIn:this.scheduleRedraw.bind(this,e)}),r=new a;e.setNeedsRedrawDelegate(r),e.isViewRefreshHandlerSet=!0}setupDataDecoding(){let e=this.moduleHandler.get(),a=e.DataDecoding.extend(\"DataDecoding\",{decode(r,i){try{let s=JSON.parse(i),n=[];for(let o of s){let c=new TextDecoder(o.ianaName,{fatal:!0});n.push(c.decode(r.slice(o.startIndex,o.endIndex)))}return n.join(\"\")}catch{return\"\"}}});e.setDataDecoding(new a)}start(e,a,r){e&&a&&(this.setupDataDecoding(),this.moduleHandler.get().callMain(),typeof this.moduleHandler.get().PThread==\"object\"||r())}getWritableDataPath(e){return e!=null?(d.log(d.Level.Debug,`IndexedDB database name override in use to recover from blocked standard database: ${e}`),e):this.writableDataPathStandard}numOfMBToPages(e){return Math.ceil(1024*e*1024/64/1024)}async setup({libraryLocation:e,locationPath:a,writableDataPathOverride:r,overrideThreadsSupport:i,overrideSimdSupport:s,verifyResponseHash:n,referredOrigin:o,fixedWasmMemory:c}){var l;let h=!1,b=!1;this.writableDataPath=this.getWritableDataPath(r),this.resourcePath=`${e}${this.resourceFilesSubfolder}/`,globalThis.path=a;let{resolve:m,reject:g,promise:y}=new le,w=I.sdkVersion();if(w===\"\")throw new O({name:\"Invalid library version\",message:\"Library version is not defined or empty, cannot generate proper path to library files.\"});let[F,p]=await Promise.all([ue(),pe()]);i!==\"auto\"&&(p=i===\"on\"),s!==\"auto\"&&(F=s===\"on\");let S=this.getWasmCoreFileName(F,p),T=ce(w,e,S),{jsURI:z,wasmURI:Z}=T,De={instantiateWasm:(f,Te)=>(oe({importObject:f,wasmURI:Z,expectedHash:this.getWasmCoreExpectedHash(F,p),verifyResponseHash:n,successCallback:Te,progressCallback:this._loadProgressCallback,referredOrigin:o}),{})},x=c===null?null:new WebAssembly.Memory({initial:this.numOfMBToPages(c),maximum:this.numOfMBToPages(c),shared:p});return x!==null&&d.log(d.Level.Debug,\"Fixed wasmMemory set\",x),this.moduleHandler.set({...x?{wasmMemory:x}:{},mainScriptUrlOrBlob:z,canvas:(l=this.workerFunctions.getOffscreenCanvas())!=null?l:{getContext:()=>null},...De,dynamicLibraries:this.getWasmDynamicLibraries(Z),locateFile:f=>e+f,noInitialRun:!0,preRun:[async()=>{try{await ae({writableDataPath:this.writableDataPath})}catch(f){if(f.name===\"BlockedIndexedDB\"){g(f.toString());return}d.log(d.Level.Debug,\"No IndexedDB support, some data will not be persisted:\",f)}b=!0,this.start(b,h,m)}],onMainComplete:()=>{if([h,b].includes(!1)){d.log(d.Level.Warn,{runtimeLoaded:h,fileSystemSynced:b},\"Both runtimeLoaded and fileSystemSynced should be true when calling onMainComplete\"),g(\"onMainComplete has been called but runtime or file system was not ready.\");return}m()},onRuntimeInitialized:()=>{h=!0,this.start(b,h,m)},print:f=>{d.log(d.Level.Info,f)}}),await de(z,w)||g(`Couldn\\'t retrieve Scandit Data Capture library at ${z}, did you configure the path for it correctly?`),y}};he.get3dPartyLicenseKeyMethodName=atob(\"Z2V0QmxpbmtJZExpY2Vuc2VLZXk=\");var C=he;function ge(t){return typeof t==\"object\"&&t!=null&&t.document==null&&\"addEventListener\"in t&&typeof t.importScripts==\"function\"}function be(t){console.warn(\"Reached unexpected case\",t)}var Y=class{constructor(t,e){this.onMessageListener=this.onMessage.bind(this),this.workerSelf=t,this.dataCaptureInstance=new C(e,{postMessage:this.postMessage.bind(this),getOffscreenCanvas:this.getOffscreenCanvas.bind(this)}),ge(t)&&this.listenToMessages()}listenToMessages(){this.workerSelf.addEventListener(\"message\",this.onMessageListener),this.workerSelf.addEventListener(\"error\",t=>{d.log(d.Level.Error,t)}),this.workerSelf.addEventListener(\"messageerror\",t=>{d.log(d.Level.Error,t)})}postMessage(t,e){this.workerSelf.postMessage(t,e??[])}getOffscreenCanvas(){if(typeof this.workerSelf.OffscreenCanvas==\"function\")return new this.workerSelf.OffscreenCanvas(32,32)}hasPayload(t){return v(t)&&\"payload\"in t}hasTransferables(t){return v(t)&&Array.isArray(t.transferables)}async respondWith(t,e,a){let r=null,i;try{i=a(),i instanceof Promise&&(i=await i)}catch(n){i=void 0,r=M(n)}let s={type:\"workerTaskId\",command:t,id:e,payload:this.hasPayload(i)?i.payload:void 0};r!=null&&(s.error=r),this.postMessage(s,this.hasTransferables(i)?i.transferables:[])}onMessage(t){switch(t.data.command){case\"loadLibrary\":{{let{data:e}=t;this.respondWith(e.command,e.id,async()=>this.dataCaptureInstance.loadLibrary({libraryLocation:e.libraryLocation,locationPath:e.locationPath,referredOrigin:e.referredOrigin,writableDataPathOverride:e.writableDataPathOverride,overrideThreadsSupport:e.overrideThreadsSupport,overrideSimdSupport:e.overrideSimdSupport,verifyResponseHash:e.verifyResponseHash,fixedWasmMemory:e.fixedWasmMemory}))}break}case\"onTap\":{{let{data:e}=t;this.respondWith(e.command,e.id,async()=>{this.dataCaptureInstance.onTap(e.point)})}break}case\"hintPresenterV2update\":{{let{data:e}=t;this.respondWith(e.command,e.id,async()=>{this.dataCaptureInstance.hintPresenterV2Update()})}break}case\"createContext\":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.createContext({context:e.context,deviceId:e.deviceId,delayedRegistration:e.delayedRegistration,highEndBlurryRecognition:e.highEndBlurryRecognition,appName:e.appName,parentDomain:e.parentDomain}))}break}case\"setFrameSource\":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.setFrameSource(e.mirrorAxis,e.isCameraFrameSource))}break}case\"processFrame\":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.processFrame({data:e.data,width:e.width,height:e.height,colorType:e.colorType}))}break}case\"requestFrameData\":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.requestFrameData(e.frameId))}break}case\"deleteFrameData\":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>{this.dataCaptureInstance.deleteFrameData(e.frameId)})}break}case\"updateContext\":{{let{data:e}=t;this.respondWith(e.command,e.id,async()=>this.dataCaptureInstance.updateContext(e))}break}case\"dispose\":{this.respondWith(t.data.command,t.data.id,()=>this.dataCaptureInstance.dispose());break}case\"flushAnalytics\":{this.respondWith(t.data.command,t.data.id,()=>{this.dataCaptureInstance.flushAnalytics()});break}case\"reportCameraProperties\":{{let{data:e}=t;this.respondWith(e.command,e.id,async()=>this.dataCaptureInstance.reportCameraProperties(e))}break}case\"setLogLevel\":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>{d.setLevel(e.level)})}break}case\"extractCentaurusLicense\":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.extractCentaurusLicense(e.licenseKey))}break}case\"documentVisibility\":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>{this.dataCaptureInstance.onDocumentVisibilityChange(e.state)})}break}case\"isFeatureSupported\":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.isFeatureSupported(e.feature))}break}case\"getViewfinderInfo\":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.getViewfinderInfo())}break}default:return be(t.data),!1}return!0}};var fe=(t=>(t.Body=\"body\",t.Footnote=\"footnote\",t))(fe||{}),A=(t=>(t.Start=\"start\",t.Center=\"center\",t.End=\"end\",t))(A||{}),ye=(t=>(t.Normal=\"normal\",t.Wider=\"wider\",t.FitText=\"fitText\",t))(ye||{}),Se=(t=>(t.Normal=\"normal\",t.Taller=\"taller\",t))(Se||{}),we=(t=>(t.Square=\"square\",t.Rounded=\"rounded\",t))(we||{}),W=(t=>(t.None=\"none\",t.Check=\"check\",t.ExclamationMark=\"exclamationMark\",t))(W||{}),B=(t=>(t.Top=\"top\",t.AboveViewFinder=\"aboveViewFinder\",t.BelowViewFinder=\"belowViewFinder\",t))(B||{}),Fe=(t=>(t.AboveViewFinder=\"aboveViewFinder\",t.BelowViewFinder=\"belowViewFinder\",t))(Fe||{}),ve=(t=>(t.BlackOnWhite=\"blackOnWhite\",t.WhiteOnBlack=\"whiteOnBlack\",t.Transparent=\"transparent\",t))(ve||{}),D=(t=>(t.Success=\"success\",t.Error=\"error\",t.Warning=\"warning\",t.Info=\"info\",t.Notification=\"notification\",t))(D||{}),Me=(t=>(t[t.Ocr=0]=\"Ocr\",t[t.HideLogo=1]=\"HideLogo\",t[t.ShowTestLicenseMessage=2]=\"ShowTestLicenseMessage\",t[t.AugmentedReality=5]=\"AugmentedReality\",t[t.ActivityPingStatsAddon=8]=\"ActivityPingStatsAddon\",t[t.ActivityPing=9]=\"ActivityPing\",t[t.Registration=10]=\"Registration\",t[t.Parser=11]=\"Parser\",t[t.BarcodeCapture=14]=\"BarcodeCapture\",t[t.Analytics=17]=\"Analytics\",t[t.AnalyticsBatchMode=18]=\"AnalyticsBatchMode\",t[t.AnalyticsScanContent=19]=\"AnalyticsScanContent\",t[t.AnalyticsOnlineVerification=20]=\"AnalyticsOnlineVerification\",t[t.SparkScan=21]=\"SparkScan\",t[t.AamvaIdBarcodeVerification=22]=\"AamvaIdBarcodeVerification\",t[t.MappingForTracking=23]=\"MappingForTracking\",t[t.BarcodeFind=24]=\"BarcodeFind\",t[t.MandatoryRegistration=25]=\"MandatoryRegistration\",t[t.FeatureTracking=26]=\"FeatureTracking\",t[t.IdCaptureViz=27]=\"IdCaptureViz\",t[t.IdCaptureMrz=28]=\"IdCaptureMrz\",t[t.IdCaptureBarcode=29]=\"IdCaptureBarcode\",t[t.BarcodeSelectionAimToScan=30]=\"BarcodeSelectionAimToScan\",t[t.BarcodeSelectionTapToScan=31]=\"BarcodeSelectionTapToScan\",t[t.BarcodeCount=32]=\"BarcodeCount\",t[t.BarcodePick=33]=\"BarcodePick\",t[t.IdVerificationDataComparison=34]=\"IdVerificationDataComparison\",t[t.SmartLabelBarcode=35]=\"SmartLabelBarcode\",t[t.SmartLabelText=36]=\"SmartLabelText\",t[t.VoidedIdDetection=37]=\"VoidedIdDetection\",t[t.BarcodeArFull=38]=\"BarcodeArFull\",t))(Me||{});var P=class{constructor(e,a,r){this.captureListenerSet=!1;this.coreEngine=e,this.Module=a,this.workerFunctions=r,this.setup()}barcodeCaptureDidUpdateSession(e){this.workerFunctions.postMessage({type:\"barcodeCaptureDidUpdateSession\",payload:JSON.parse(e.toJson())})}barcodeTrackingDidUpdateSession(e){this.workerFunctions.postMessage({type:\"barcodeTrackingDidUpdateSession\",payload:JSON.parse(e.toJson())})}getCaptureDeserializer(){return this.barcodeCaptureDeserializer}getTrackingDeserializer(){return this.barcodeTrackingDeserializer}setup(){let e=this.Module.BarcodeCaptureListener.extend(\"BarcodeCaptureListener\",{didScan:(n,o,c)=>{this.barcodeCaptureDidScan(o,c)},didUpdateSession:(n,o)=>{this.barcodeCaptureDidUpdateSession(o)}}),a=this.Module.Feedback.extend(\"Feedback\",{emit:()=>{this.successFeedback()}}),r=new e,i=new a,s=this.Module.BarcodeCaptureDeserializerListener.extend(\"BarcodeCaptureDeserializerListener\",{onModeDeserializationFinished:(n,o)=>{o.addListener(r,1),o.setSuccessFeedback(i)},onModeDeserializationStarted(){},onSettingsDeserializationStarted(){},onSettingsDeserializationFinished(){}});this.barcodeCaptureDeserializer=new this.Module.BarcodeCaptureDeserializer,this.barcodeCaptureDeserializer.setListener(new s)}successFeedback(){this.workerFunctions.postMessage({type:\"successFeedback\"})}barcodeCaptureDidScan(e,a){let r=this.coreEngine.convertToLoadableFrameData(a);this.workerFunctions.postMessage({type:\"barcodeCaptureDidScan\",payload:{session:JSON.parse(e.toJson()),frameData:r}})}};function Ge(t){return t.charAt(0).toUpperCase()+t.slice(1)}function ke(t){return t}var E=class{constructor(e,a,r){this.barcodeFind=null;this.basicOverlay=null;this.transparentGuidanceHintStyle={backgroundColor:\"00000000\",cornerRadius:4,fitToText:!1,isAnimatedToView:!1,textAlignment:A.Center,hintIcon:W.None,hintAnchor:B.AboveViewFinder,hintAnchorOffset:-12,horizontalMargin:0,iconColor:\"00000000\",lineHeight:-1,maxLines:1,maxWidthFraction:.8,textColor:\"ffffffff\",textSize:15,textWeight:600};this.customerTransformation=ke;this.coreEngine=e,this.Module=a,this.workerFunctions=r}async forSettings(e){this.barcodeFind?.delete(),this.barcodeFind=new this.Module.BarcodeFind(this.coreEngine.context,JSON.stringify(e));let a=this.Module.Feedback.extend(\"Feedback\",{emit:()=>{this.listUpdatedFeedback()}}),r=this.Module.Feedback.extend(\"Feedback\",{emit:()=>{this.barcodeFindFeedback()}}),i=this.Module.BarcodeFindTransformer.extend(\"BarcodeFindTransformer\",{transformBarcodeData:n=>this.customerTransformation(n)}),s=this.Module.BarcodeFindListener.extend(\"BarcodeFindListener\",{didUpdateSession:(n,o,c)=>{let l=this.coreEngine.convertToLoadableFrameData(c);this.workerFunctions.postMessage({type:\"barcodeFindDidUpdateSession\",payload:{session:JSON.parse(o.toJson()),frameData:l}})},onSearchPaused:n=>{let o=[];for(let c=0;c{let o=[];for(let c=0;c{this.workerFunctions.postMessage({type:\"barcodeFindSearchStarted\",payload:{}})}});this.barcodeFind.setBarcodeFindTransformer(new i),this.barcodeFind.addListener(new s,1),this.barcodeFind.setItemListUpdatedFeedback(new a),this.barcodeFind.setFeedback(new r),this.Module.addBarcodeFindToContext(this.coreEngine.context,this.barcodeFind)}barcodeFindFeedback(){this.workerFunctions.postMessage({type:\"barcodeFindFeedback\",payload:{}})}start(){this.barcodeFind?.start()}stop(){this.barcodeFind?.stop()}pause(){this.barcodeFind?.pause()}setEnabled(e){this.barcodeFind?.setEnabled(e)}setItemList(e){this.barcodeFind?.setItemList(JSON.stringify(e))}async removeMode(){this.barcodeFind!=null&&this.Module.removeBarcodeFindFromContext(this.coreEngine.context,this.barcodeFind)}addBasicOverlay(){this.basicOverlay?.delete(),this.basicOverlay=null,this.barcodeFind!=null&&(this.basicOverlay=new this.Module.BarcodeFindBasicOverlay(this.barcodeFind)),this.coreEngine.view!=null&&this.basicOverlay!=null&&(this.basicOverlay.setGuidanceHandler(this.createWebFindGuidanceHandler()),this.Module.addBarcodeFindBasicOverlayToView(this.coreEngine.view,this.basicOverlay))}removeBasicOverlay(){this.coreEngine.view!=null&&this.basicOverlay!=null&&this.Module.removeBarcodeFindBasicOverlayFromView(this.coreEngine.view,this.basicOverlay)}async applySettings(e){this.barcodeFind?.applySettings(JSON.stringify(e))}updateBasicOverlay(e){let a=Object.entries(e).filter(([r,i])=>r!==\"type\");for(let[r,i]of a){let s=`set${Ge(r)}`;this.basicOverlay!=null&&typeof this.basicOverlay[s]==\"function\"&&i!=null&&this.basicOverlay[s](i)}}setTransformerFunction(e){this.customerTransformation=e??ke}successFeedback(){this.workerFunctions.postMessage({type:\"successFeedback\"})}listUpdatedFeedback(){this.workerFunctions.postMessage({type:\"barcodeFindListUpdatedFeedback\",payload:{}})}setToast(e,a){let r=this.coreEngine.hintPresenterV2;e?r?.showToast(JSON.stringify(a)):r?.hideToast(a.tag)}setGuidance(e,a,r){let i={tag:r,text:a,hintStyle:this.transparentGuidanceHintStyle};this.workerFunctions.postMessage({type:e?\"showGuidance\":\"hideGuidance\",payload:i})}createWebFindGuidanceHandler(){let e=this.Module.BarcodeFindGuidanceHandler.extend(\"BarcodeFindGuidanceHandler\",{setInitialGuidance:(a,r)=>{this.setGuidance(a,r,\"InitialGuidance\")},setMoveCloserGuidance:(a,r)=>{this.setGuidance(!1,r,\"InitialGuidance\"),this.setGuidance(a,r,\"MoveCloserGuidance\")},setAllItemsFound:(a,r)=>{let i={text:r,toastHintStyle:D.Success,tag:\"AllItemsFound\"};this.setToast(a,i)},setTapShutterToPause:(a,r)=>{this.setGuidance(!1,r,\"InitialGuidance\"),this.setGuidance(a,r,\"TapShutterToPause\")},setTapShutterToResume:(a,r)=>{this.setGuidance(!1,r,\"InitialGuidance\"),this.setGuidance(a,r,\"TapShutterResume\")},setItemListUpdated:(a,r)=>{let i={text:r,toastHintStyle:D.Info,tag:\"ItemListUpdated\"};this.setToast(a,i)}});return new e}};var R=class{constructor(e,a,r){this.trackingListenerSet=!1;this.coreEngine=e,this.Module=a,this.workerFunctions=r,this.setup()}barcodeTrackingDidUpdateSession(e){this.workerFunctions.postMessage({type:\"barcodeTrackingDidUpdateSession\",payload:JSON.parse(e.toJson())})}getTrackingDeserializer(){return this.barcodeTrackingDeserializer}setup(){let e=this.Module.BarcodeTrackingListener.extend(\"BarcodeTrackingListener\",{didUpdateSession:(r,i)=>{this.barcodeTrackingDidUpdateSession(i)},onTrackedBarcodeTapped:(r,i)=>{this.onTrackedBarcodeTapped(i)}}),a=this.Module.BarcodeTrackingDeserializerListener.extend(\"BarcodeTrackingDeserializerListener\",{onModeDeserializationFinished:(r,i)=>{this.trackingListenerSet||(i.addListener(new e,1),this.trackingListenerSet=!0)},onModeDeserializationStarted(){},onSettingsDeserializationStarted(){},onSettingsDeserializationFinished(){}});this.barcodeTrackingDeserializer=new this.Module.BarcodeTrackingDeserializer,this.barcodeTrackingDeserializer.setListener(new a)}onTrackedBarcodeTapped(e){this.workerFunctions.postMessage({type:\"didTapTrackedBarcode\",payload:JSON.parse(e.toJson())})}};var N=class{constructor(e,a,r){this.captureListenerSet=!1;this.coreEngine=e,this.Module=a,this.workerFunctions=r,this.setup()}sparkScanDidUpdateSession(e){this.workerFunctions.postMessage({type:\"sparkScanDidUpdateSession\",payload:JSON.parse(e.toJson())})}getSparkScanDeserializer(){return this.sparkScanDeserializer}setup(){let e=this.Module.SparkScanListener.extend(\"SparkScanListener\",{didScan:(i,s,n)=>{this.sparkScanDidScan(s,n)},didUpdateSession:(i,s)=>{this.sparkScanDidUpdateSession(s)}}),a=this.Module.Feedback.extend(\"Feedback\",{emit:()=>{this.successFeedback()}}),r=this.Module.SparkScanDeserializerListener.extend(\"SparkScanDeserializerListener\",{onModeDeserializationFinished:(i,s)=>{this.captureListenerSet||(s.addListener(new e,1),s.setSuccessFeedback(new a),this.captureListenerSet=!0)},onModeDeserializationStarted(){},onSettingsDeserializationStarted(){},onSettingsDeserializationFinished(){},onOverlayDeserializationStarted(){},onOverlayDeserializationFinished:(i,s,n)=>{this.sparkScanOverlay?.delete(),this.sparkScanOverlay=s.clone()}});this.sparkScanDeserializer=new this.Module.SparkScanDeserializer,this.sparkScanDeserializer.setListener(new r)}emitErrorFeedback(e){this.sparkScanOverlay?.onErrorFeedbackEmitted(e)}successFeedback(){this.workerFunctions.postMessage({type:\"successFeedback\"})}sparkScanDidScan(e,a){let r=this.coreEngine.convertToLoadableFrameData(a);this.workerFunctions.postMessage({type:\"sparkScanDidScan\",payload:{session:JSON.parse(e.toJson()),frameData:r}})}};var _=class extends C{constructor(e,a){super(e,a)}getModeDeserializers(){this.barcodeCaptureMode=new P(this,this.Module,this.workerFunctions),this.barcodeTrackingMode=new R(this,this.Module,this.workerFunctions),this.sparkScanMode=new N(this,this.Module,this.workerFunctions),this.barcodeFindMode=new E(this,this.Module,this.workerFunctions);let e=super.getModeDeserializers();return e.push_back(this.barcodeCaptureMode.getCaptureDeserializer()),e.push_back(this.barcodeTrackingMode.getTrackingDeserializer()),e.push_back(this.sparkScanMode.getSparkScanDeserializer()),e}sparkScanEmitErrorFeedback(e){this.sparkScanMode.emitErrorFeedback(e)}getWasmSideModuleFileName(){return\"\"}getWasmCoreFileName(e,a){return a?e?\"scandit-datacapture-sdk-barcode-simd-pthreads.wasm\":\"scandit-datacapture-sdk-barcode-pthreads.wasm\":e?\"scandit-datacapture-sdk-barcode-simd.wasm\":\"scandit-datacapture-sdk-barcode.wasm\"}getWasmCoreExpectedHash(e,a){return a?e?\"0497629ae7746bbb2c9befc2ba9086882c73e1a5029e40f52382e9329c744110\":\"acd5b393969de53839d18ea0584116f7efba63469c188410a6769f8fc9120243\":e?\"abf5780ce18056e02d433c67dc5c59496430285c990240ed100b1842ae9bd352\":\"d41473a70eb9068f034b244edf7778e8fbaf46049928792f494473f6ff0e08b9\"}getWasmMetadata(){return u}};function je(t){return(a=>/^[$A-Z_a-z][\\\\w$]*\\\\s*\\\\(.*\\\\)\\\\s*\\\\{/.test(a)&&!a.startsWith(\"function\"))(t)?`function ${t}`:t}var qe=[\"fetch\",\"XMLHttpRequest\",\"eval\",\"Function\",\"self\",\"globalThis\",\"Module\",\"importScripts\",\"this\",\"console\",\"window\",\"document\",\"import\",\"Worker\",\"ServiceWorker\"];function Ke(t){return qe.map(a=>new RegExp(`\\\\\\\\b${a}\\\\\\\\b`,\"g\")).some(a=>a.test(t))}function Ce(t){if(t==null)return null;let e=je(t);if(Ke(e))throw new Error(\"Function should be pure. Shouldn\\'t introduce side effects, or rely on global scope\");let a=`\\'use strict\\';\\n return (${e});`;try{return new Function(a)()}catch{return null}}var H=class extends Y{constructor(e,a){super(e,a),this.dataCaptureInstance=new _(a,{postMessage:this.postMessage.bind(this),getOffscreenCanvas:this.getOffscreenCanvas.bind(this)})}async respondWith(e,a,r){let i=null,s;try{s=r(),s instanceof Promise&&(s=await s)}catch(o){s=void 0,i=M(o)}let n={type:\"workerTaskId\",command:e,id:a,payload:this.hasPayload(s)?s.payload:void 0};i!=null&&(n.error=i),this.postMessage(n,this.hasTransferables(s)?s.transferables:[])}onMessage(e){switch(e.data.command){case\"sparkScanEmitErrorFeedback\":{let{data:a}=e;return this.respondWith(a.command,a.id,()=>{this.dataCaptureInstance.sparkScanEmitErrorFeedback(a.shouldRemoveBrush)}),!0}case\"barcodeFindForSettings\":{let{data:a}=e;return this.respondWith(a.command,a.id,async()=>this.dataCaptureInstance.barcodeFindMode.forSettings(a.settings)),!0}case\"barcodeFindModeRemove\":{let{data:a}=e;return this.respondWith(a.command,a.id,async()=>this.dataCaptureInstance.barcodeFindMode.removeMode()),!0}case\"barcodeFindSearchStart\":return this.respondWith(e.data.command,e.data.id,()=>{this.dataCaptureInstance.barcodeFindMode.start()}),!0;case\"barcodeFindSearchPause\":return this.respondWith(e.data.command,e.data.id,()=>{this.dataCaptureInstance.barcodeFindMode.pause()}),!0;case\"barcodeFindSearchStop\":return this.respondWith(e.data.command,e.data.id,()=>{this.dataCaptureInstance.barcodeFindMode.stop()}),!0;case\"barcodeFindSetItemList\":{let{data:a}=e;return this.respondWith(e.data.command,e.data.id,()=>{this.dataCaptureInstance.barcodeFindMode.setItemList(a.itemList)}),!0}case\"barcodeFindSetEnabled\":{let{data:a}=e;return this.respondWith(e.data.command,e.data.id,()=>{this.dataCaptureInstance.barcodeFindMode.setEnabled(a.enabled)}),!0}case\"barcodeFindApplySettings\":{let{data:a}=e;return this.respondWith(a.command,a.id,async()=>this.dataCaptureInstance.barcodeFindMode.applySettings(a.settings)),!0}case\"barcodeFindAddBasicOverlay\":{let{data:a}=e;return this.respondWith(a.command,a.id,async()=>{this.dataCaptureInstance.barcodeFindMode.addBasicOverlay()}),!0}case\"barcodeFindRemoveBasicOverlay\":{let{data:a}=e;return this.respondWith(a.command,a.id,async()=>{this.dataCaptureInstance.barcodeFindMode.removeBasicOverlay()}),!0}case\"barcodeFindUpdateBasicOverlay\":{let{data:a}=e;return this.respondWith(a.command,a.id,async()=>{this.dataCaptureInstance.barcodeFindMode.updateBasicOverlay(a.jsonOverlay)}),!0}case\"barcodeFindSetTransformerFunction\":{let{data:a}=e;return this.respondWith(a.command,a.id,async()=>{let r=Ce(a.functionAsString);this.dataCaptureInstance.barcodeFindMode.setTransformerFunction(r)}),!0}default:return super.onMessage(e)}}};var Ha=new H(globalThis,{get:()=>globalThis.Module,set:t=>{globalThis.Module=t}});function za(t){}})();\\n'],{type:\"application/javascript\"}));function i(r){return new Worker(u,r)}var n=class r extends DataCaptureLoader{constructor(){super(...arguments);this._name=\"BarcodeCapture\";}get dataCaptureWorker(){return (this._dataCaptureWorker)!=null||(this._dataCaptureWorker=i({name:this.name})),this._dataCaptureWorker}get name(){return this._name}static async create(e){var a;let t=new r(e);return await t.workerCommand(\"setLogLevel\",{level:(a=e.logLevel)!=null?a:Logger.Level.Debug}),await t.load(),t}async workerCommand(e,t,a){return new Promise((o,d)=>{let s=this.workerCommandId++;this.workerTasks.set(s,{resolve:o,reject:d,command:e});let c={...t,command:e,id:s};this.dataCaptureWorker.postMessage(c,a);})}};\n\nexport { n as a };\n", "var n={};\n\nexport { n as a };\n", "import { a as a$1 } from './chunk-CEZOMS4Y.js';\nimport { a } from './chunk-LKZBVQXD.js';\nimport { Localization } from 'scandit-web-datacapture-core';\n\nfunction l(r){return Localization.getInstance().updateIfMissing({...a}),{moduleName:\"BarcodeCapture\",load:async t=>{var e;let n=t;return await a$1.create({...n,highEndBlurryRecognition:(e=r==null?void 0:r.highEndBlurryRecognition)!=null?e:!1})}}}\n\nexport { l as a };\n", "import { Feedback } from 'scandit-web-datacapture-core';\n\nvar e=class a{constructor(){this.success=Feedback.defaultFeedback;}static get default(){return new a}toJSONObject(){return {success:this.success.toJSONObject()}}};\n\nexport { e as a };\n", "import { Quadrilateral } from 'scandit-web-datacapture-core';\n\nvar r=class t{get frameID(){return this._frameID}get location(){return this._location}static fromJSON(e){let a=new t;return a._location=Quadrilateral.fromJSON(e.location),a._frameID=e.frameId,a}toJSONObject(){return {frameId:this.frameID,location:this.location.toJSONObject()}}};\n\nexport { r as a };\n", "import { a } from './chunk-VRFFR4LU.js';\nimport { e } from './chunk-BW3FAMLI.js';\n\nvar d=class n{get newlyRecognizedBarcode(){return this._newlyRecognizedBarcode}get newlyLocalizedBarcodes(){return this._newlyLocalizedBarcodes}get frameSequenceID(){return this._frameSequenceID}get newlyRecognizedBarcodes(){return this._newlyRecognizedBarcodes}static fromJSON(e$1){let r=new n;return r._newlyRecognizedBarcodes=e$1.newlyRecognizedBarcodes.map(c=>e.fromJSON(c)),e$1.newlyRecognizedBarcode&&(r._newlyRecognizedBarcode=e.fromJSON(e$1.newlyRecognizedBarcode)),r._newlyLocalizedBarcodes=e$1.newlyLocalizedBarcodes.map(c=>a.fromJSON(c)),r._frameSequenceID=e$1.frameSequenceId,r}toJSON(){var e,r;return JSON.stringify({newlyLocalizedBarcodes:this.newlyLocalizedBarcodes.map(c=>c.toJSONObject()),newlyRecognizedBarcodes:this.newlyRecognizedBarcodes.map(c=>c.toJSONObject()),newlyRecognizedBarcode:(r=(e=this.newlyRecognizedBarcode)==null?void 0:e.toJSONObject())!=null?r:null,frameSequenceId:this.frameSequenceID})}};\n\nexport { d as a };\n", "import { a } from './chunk-JYVE7GVH.js';\nimport { a as a$1 } from './chunk-D3GTNMBR.js';\nimport { b } from './chunk-TRWFJYCT.js';\nimport { CameraSettings, Logger, convertToPublicFrameData } from 'scandit-web-datacapture-core';\n\nvar p=class u{constructor(){this.type=\"barcodeCapture\";this._isEnabled=!0;this._feedback=a.default;this._context=null;this.listeners=new Set;this.allowedRemainingWorkerMessages=new Set;this.workerMessageListener=this.onWorkerMessage.bind(this);}static get recommendedCameraSettings(){return new CameraSettings(b.BarcodeCapture.RecommendedCameraSettings)}get context(){return this._context}get feedback(){return this._feedback}set feedback(e){this._feedback=e,Logger.log(Logger.Level.Info,\"Please use BarcodeCapture.setFeedback instead of BarcodeCapture.feedback setter\"),this.notifyContext();}static async forContext(e,a){let t=new u;return t.settings=a,e&&await e.addMode(t),t}async setFeedback(e){return this._feedback=e,this.notifyContext()}isEnabled(){return this._isEnabled}async setEnabled(e){this._isEnabled=e,await this.notifyContext();}async applySettings(e){return this.settings=e,this.notifyContext()}addListener(e){this.listeners.has(e)||this.listeners.add(e);}removeListener(e){this.listeners.delete(e);}toJSONObject(){return {type:this.type,enabled:this._isEnabled,feedback:this.feedback.toJSONObject(),settings:this.settings.toJSONObject()}}attachedToContext(e){this._context=e,this._context.subscribeToWorkerMessages(this.workerMessageListener);}async detachedFromContext(){var e;(e=this._context)==null||e.unsubscribeToWorkerMessages(this.workerMessageListener),this._context=null;}sendClearFrameDataRequest(e){setTimeout(()=>{var a;(a=this.context)==null||a.workerCommand(\"deleteFrameData\",{frameId:e});},0);}async onDidScan(e){if(this.context==null)return;let a=a$1.fromJSON(e.payload.session),{frameData:t}=e.payload;if(!this._isEnabled){this.sendClearFrameDataRequest(t.frameId),this.allowedRemainingWorkerMessages.clear();return}this.allowedRemainingWorkerMessages.add(\"successFeedback\");let n=[];for(let r of this.listeners)if(r.didScan)try{let s=r.didScan(this,a,convertToPublicFrameData(t,this.context));s instanceof Promise&&await s;}catch(s){n.push(s);}this.sendClearFrameDataRequest(t.frameId),this.allowedRemainingWorkerMessages.add(\"barcodeCaptureDidUpdateSession\");for(let r of n)Logger.log(Logger.Level.Error,r);}onDidUpdateSession(e){let a=a$1.fromJSON(e.payload);if(!(!this._isEnabled&&!this.allowedRemainingWorkerMessages.has(e.type))){this.allowedRemainingWorkerMessages.delete(e.type);for(let t of this.listeners)t.didUpdateSession&&t.didUpdateSession(this,a);}}onSuccessFeedback(e){!this._isEnabled&&!this.allowedRemainingWorkerMessages.has(e.type)||(this.allowedRemainingWorkerMessages.delete(e.type),this.feedback.success.emit());}async onWorkerMessage(e){switch(e.type){case\"barcodeCaptureDidScan\":{this.onDidScan(e);break}case\"barcodeCaptureDidUpdateSession\":{this.onDidUpdateSession(e);break}case\"successFeedback\":{this.onSuccessFeedback(e);break}}}async notifyContext(){this.context!=null&&await this.context.update();}};\n\nexport { p as a };\n", "import { b } from './chunk-TRWFJYCT.js';\nimport { Brush, NoViewfinder } from 'scandit-web-datacapture-core';\n\nvar c=(e=>(e.Frame=\"frame\",e))(c||{}),i=class o{constructor(){this.type=\"barcodeCapture\";this._shouldShowScanAreaGuides=!1;this._shouldRemoveLocationsAfterScan=!0;this._style=b.BarcodeCapture.BarcodeCaptureOverlay.defaultStyle;this._viewfinder=null;}get style(){return this._style}static async withBarcodeCapture(e){return o.withBarcodeCaptureForView(e,null)}static async withBarcodeCaptureForView(e,a){return o.withBarcodeCaptureForViewWithStyle(e,a,b.BarcodeCapture.BarcodeCaptureOverlay.defaultStyle)}static async withBarcodeCaptureForViewWithStyle(e,a,u){let r=new o;return r.barcodeCapture=e,r._style=u,await r.setBrush(new Brush(b.BarcodeCapture.BarcodeCaptureOverlay.styles[r.style].DefaultBrush.fillColor,b.BarcodeCapture.BarcodeCaptureOverlay.styles[r.style].DefaultBrush.strokeColor,b.BarcodeCapture.BarcodeCaptureOverlay.styles[r.style].DefaultBrush.strokeWidth)),a&&await a.addOverlay(r),r}getBrush(){return this._brush}getViewfinder(){return this._viewfinder}async setBrush(e){this._brush=e,await this.barcodeCapture.notifyContext();}async setShouldShowScanAreaGuides(e){this._shouldShowScanAreaGuides=e,await this.barcodeCapture.notifyContext();}async setShouldRemoveLocationsAfterScan(e){this._shouldRemoveLocationsAfterScan=e,await this.barcodeCapture.notifyContext();}async setViewfinder(e){this._viewfinder=e,await this.barcodeCapture.notifyContext();}shouldShowScanAreaGuides(){return this._shouldShowScanAreaGuides}shouldRemoveLocationsAfterScan(){return this._shouldRemoveLocationsAfterScan}toJSONObject(){var e,a;return {type:this.type,brush:this._brush.toJSONObject(),drawLocalizedOnlyBarcodes:!1,shouldShowScanAreaGuides:this._shouldShowScanAreaGuides,shouldRemoveLocationsAfterScan:this._shouldRemoveLocationsAfterScan,viewfinder:(a=(e=this._viewfinder)==null?void 0:e.toJSONObject())!=null?a:NoViewfinder.toJSONObject(),style:this.style}}};\n\nexport { c as a, i as b };\n", "import { b } from './chunk-TRWFJYCT.js';\nimport { PrivateNoneLocationSelection } from 'scandit-web-datacapture-core';\n\nvar p=class{constructor(){this.codeDuplicateFilter=b.BarcodeCapture.BarcodeCaptureSettings.codeDuplicateFilter;this.locationSelection=null;this.enabledCompositeTypes=[];this.properties={};this.symbologies={};}get enabledSymbologies(){return Object.keys(this.symbologies).filter(e=>{var o;return (o=this.symbologies[e])==null?void 0:o.isEnabled})}get compositeTypeDescriptions(){return b.CompositeTypeDescriptions.reduce((e,o)=>(e[o.types[0]]=o,e),{})}settingsForSymbology(e){if(!this.symbologies[e]){let o=b.SymbologySettings[e];o._symbology=e,this.symbologies[e]=o;}return this.symbologies[e]}setProperty(e,o){this.properties[e]=o;}getProperty(e){return this.properties[e]}enableSymbologies(e){for(let o of e)this.enableSymbology(o,!0);}enableSymbology(e,o){this.settingsForSymbology(e).isEnabled=o;}enableSymbologiesForCompositeTypes(e){for(let o of e)this.enableSymbologies(this.compositeTypeDescriptions[o].symbologies);}toJSONObject(){var o,i,s;let e={};return {codeDuplicateFilter:this.codeDuplicateFilter,enabledCompositeTypes:[...this.enabledCompositeTypes],locationSelection:(i=(o=this.locationSelection)==null?void 0:o.toJSONObject())!=null?i:PrivateNoneLocationSelection,properties:{...this.properties},symbologies:Object.keys(this.symbologies).reduce((n,l)=>{var y;let r=(y=this.symbologies[l])==null?void 0:y.toJSONObject();return r&&(n[l]=r),n},e),scanIntention:(s=this.scanIntention)!=null?s:null}}};\n\nexport { p as a };\n", "import {\n Camera,\n CameraSwitchControl,\n DataCaptureContext,\n DataCaptureView,\n FrameSourceState,\n RectangularViewfinder,\n RectangularViewfinderLineStyle,\n RectangularViewfinderStyle,\n TorchSwitchControl,\n configure,\n} from \"scandit-web-datacapture-core\";\nimport {\n BarcodeCapture,\n BarcodeCaptureOverlay,\n BarcodeCaptureOverlayStyle,\n BarcodeCaptureSettings,\n barcodeCaptureLoader,\n} from \"scandit-web-datacapture-barcode\";\n\nexport class Scandit {\n constructor (license, barcodeTypes, container, control) {\n this.enabledSymbologies = barcodeTypes;\n this.container = container;\n this.control = control;\n this.license = license;\n }\n\n async open(handleScan) {\n await configure({\n licenseKey: this.license,\n // TODO: update\n // highly recommended to handle the serving of these files yourself on your website/server\n // https://docs.scandit.com/stable/web/#configuration\n libraryLocation: new URL(\"/scandit-engine\", document.baseURI).toString(),\n moduleLoaders: [barcodeCaptureLoader()],\n });\n\n const context = await DataCaptureContext.create();\n const camera = Camera.default;\n await context.setFrameSource(camera);\n\n const view = await DataCaptureView.forContext(context);\n view.connectToElement(this.container);\n\n const settings = new BarcodeCaptureSettings();\n settings.enableSymbologies(this.enabledSymbologies, true);\n settings.codeDuplicateFilter = -1;\n\n const barcodeCapture = await BarcodeCapture.forContext(context, settings);\n await barcodeCapture.setEnabled(true);\n\n barcodeCapture.addListener({\n didScan: async (barcodeCapture, session) => {\n await barcodeCapture.setEnabled(false);\n\n handleScan(session.newlyRecognizedBarcodes[0].data);\n context.dispose();\n view.detachFromElement(this.container);\n await camera.switchToDesiredState(FrameSourceState.Off);\n if (this.stream) this.stream.getTracks().forEach((track) => track.stop());\n },\n });\n\n const barcodeCaptureOverlay = await BarcodeCaptureOverlay.withBarcodeCaptureForViewWithStyle(\n barcodeCapture,\n view,\n BarcodeCaptureOverlayStyle.Frame,\n );\n\n await camera.switchToDesiredState(FrameSourceState.On);\n\n const viewfinder = new RectangularViewfinder(\n RectangularViewfinderStyle.Square,\n RectangularViewfinderLineStyle.Light,\n );\n\n await barcodeCaptureOverlay.setViewfinder(viewfinder);\n\n view.addControl(new CameraSwitchControl());\n view.addControl(new TorchSwitchControl());\n\n this.control.disabled = true;\n this.container.classList.add(\"pt-20\");\n }\n\n close() {\n this.control.disabled = false;\n this.container.classList.remove(\"pt-20\");\n }\n}\n\nexport default Scandit;\n", "import ErrorNotifier from \"../../error_notifier\";\n\n// TODO: maintain this here for import from npm?\n// TODO: drop keys we don't need?\nconst CodeToKey = {\n DCT: \"firstNameAndMiddleName\",\n DCA: \"jurisdictionVehicleClass\",\n DCB: \"jurisdictionRestrictionCodes\",\n DCD: \"jurisdictionEndorsementCodes\",\n DBA: \"dateOfExpiry\",\n DCS: \"lastName\",\n DAC: \"firstName\",\n DAD: \"middleName\",\n DBD: \"dateOfIssue\",\n DBB: \"dateOfBirth\",\n DBC: \"sex\",\n DAY: \"eyeColor\",\n DAU: \"height\",\n DAG: \"addressStreet\",\n DAI: \"addressCity\",\n DAJ: \"addressState\",\n DAK: \"addressPostalCode\",\n DAQ: \"documentNumber\",\n DCF: \"documentDiscriminator\",\n DCG: \"issuer\",\n DDE: \"lastNameTruncated\",\n DDF: \"firstNameTruncated\",\n DDG: \"middleNameTruncated\",\n // optional\n DAZ: \"hairColor\",\n DAH: \"addressStreet2\",\n DCI: \"placeOfBirth\",\n DCJ: \"auditInformation\",\n DCK: \"inventoryControlNumber\",\n DBN: \"otherLastName\",\n DBG: \"otherFirstName\",\n DBS: \"otherSuffixName\",\n DCU: \"nameSuffix\",\n DCE: \"weightRange\",\n DCL: \"race\",\n DCM: \"standardVehicleClassification\",\n DCN: \"standardEndorsementCode\",\n DCO: \"standardRestrictionCode\",\n DCP: \"jurisdictionVehicleClassificationDescription\",\n DCQ: \"jurisdictionEndorsementCodeDescription\",\n DCR: \"jurisdictionRestrictionCodeDescription\",\n DDA: \"complianceType\",\n DDB: \"dateCardRevised\",\n DDC: \"dateOfExpiryHazmatEndorsement\",\n DDD: \"limitedDurationDocumentIndicator\",\n DAW: \"weightLb\",\n DAX: \"weightKg\",\n DDH: \"dateAge18\",\n DDI: \"dateAge19\",\n DDJ: \"dateAge21\",\n DDK: \"organDonor\",\n DDL: \"veteran\",\n};\n\n// TODO: remove parsing for keys we don't need?\nexport const parseId = (str, options = { suppressErrors: false }) => {\n const props = {};\n const rawLines = str.trim().split(\"\\n\");\n\n const lines = rawLines.map((rawLine) => sanitizeData(rawLine));\n let started;\n lines.slice(0, -1).forEach((line) => {\n if (!started) {\n if (line.indexOf(\"ANSI \") === 0) {\n started = true;\n\n if (line.includes(\"DLDAQ\")) {\n const lineArray = line.split(\"DLDAQ\");\n line = \"DAQ\" + lineArray[1];\n } else {\n return;\n }\n } else {\n return;\n }\n }\n\n const code = getCode(line);\n let value = getValue(line);\n const key = getKey(code);\n\n if (!key) {\n if (options.suppressErrors) {\n return;\n } else {\n ErrorNotifier.notify({\n error: \"ID Scanning error\",\n context: { code, line, started, str },\n });\n throw new Error(\"unknown code: \" + code);\n }\n }\n\n if (isSexField(code)) value = getSex(code, value);\n\n props[key] = isDateField(key) ? getDateFormat(value) : value;\n });\n\n return props;\n};\n\nconst sanitizeData = (rawLine) =>\n rawLine\n .match(/[\\011\\012\\015\\040-\\177]*/g)\n .join(\"\")\n .trim();\n\nconst getCode = (line) => line.slice(0, 3);\nconst getValue = (line) => line.slice(3);\nconst getKey = (code) => CodeToKey[code];\n\nconst isSexField = (code) => code === \"DBC\";\n\nconst getSex = (code, value) => (value === \"1\" ? \"M\" : \"F\");\n\nconst isDateField = (key) => key.indexOf(\"date\") === 0;\n\nconst getDateFormat = (value) => {\n const [mm, dd, yyyy] = [value.slice(0, 2), value.slice(2, 4), value.slice(4)];\n return [yyyy, mm, dd];\n};\n", "export const titleize = string => {\n if (string === null || string === undefined || string.length === 0) {\n return \"\";\n }\n\n return string.toLowerCase().split(/\\s+/).map(function (word) {\n return (word.charAt(0).toUpperCase() + word.slice(1));\n }).join(\" \");\n};\n", "import { Controller } from \"@hotwired/stimulus\";\nimport fetch from \"@/utils/fetch\";\nimport Scandit from \"@/ui/scandit\";\nimport { parseId } from \"@/ui/scandit/id_parser\";\nimport { trackEvent } from \"@/utils/analytics\";\nimport { titleize } from \"@/utils/strings\";\nimport { debounce } from \"@/utils/debounce\";\nimport { Symbology } from \"scandit-web-datacapture-barcode\";\n\nexport default class extends Controller {\n static targets = [\n \"scandit\",\n \"scanditError\",\n \"control\",\n \"andFirstName\",\n \"capsLock\",\n \"exact\",\n \"firstName\",\n \"lastName\",\n \"matches\",\n \"noMatches\",\n \"phoneOrEmail\",\n \"related\",\n \"searchBar\",\n \"spinner\",\n ];\n\n static values = {\n upsheetId: String,\n scannerLicense: String,\n };\n\n static outlets = [\n \"contact--editor\",\n ];\n\n inProgress = false;\n\n search = debounce((firstName, lastName, emailTargets, phoneTargets) => {\n this.#lookup(firstName, lastName, emailTargets, phoneTargets);\n return true; // so IE does not cancel tabbing to the next field\n }, 500);\n\n connect() {\n this.form = $(\"#contact_form\");\n\n if (this.hasScanditTarget && this.hasControlTarget) {\n this.scandit = new Scandit(this.scannerLicenseValue, [Symbology.PDF417], this.scanditTarget, this.controlTarget);\n }\n\n this.form.submit(() => {\n this.submitClicked = true;\n });\n }\n\n #handleScan(data) {\n trackEvent({\n action: \"scan-license\",\n category: \"scandit\",\n label: \"scan-license-start\",\n });\n\n const {\n firstName, middleName, lastName, nameSuffix, dateOfBirth, addressStreet,\n addressCity, addressState, addressPostalCode,\n } = parseId(data, { suppressErrors: true });\n\n this.firstNameTarget.value = titleize(firstName);\n this.lastNameTarget.value = titleize(lastName);\n this.contactEditorOutlet.populateFromScan({\n firstName: titleize(firstName),\n middleName: titleize(middleName),\n lastName: titleize(lastName),\n nameSuffix,\n dateOfBirth,\n addressStreet: titleize(addressStreet),\n addressCity: titleize(addressCity),\n addressState,\n addressPostalCode,\n });\n this.checkExisting();\n }\n\n toggleCamera() {\n trackEvent({\n action: \"scan-license\",\n category: \"scandit\",\n label: \"scan-license-toggle-camera\",\n });\n\n this.scandit\n .open((data) => this.#handleScan(data))\n .then(() => {\n this.scanditErrorTarget.classList.add(\"hidden\");\n })\n .catch(() => {\n this.scandit.close();\n this.scanditTarget.innerHTML = \"\";\n this.scanditErrorTarget.classList.remove(\"hidden\");\n });\n }\n\n matchesTargetConnected() {\n this.form.find(\":focus\").blur();\n this.matchesTarget.classList.replace(\"max-h-0\", \"max-h-[1000vh]\");\n this.noMatchesTarget.classList.add(\"hidden\");\n }\n\n exactTargetConnected() {\n this.form.find(\":focus\").blur();\n this.#setLabel(\"Found exact match\");\n }\n\n #searchable(first, last, email, phone) {\n const searchCombos = [\n [first, last],\n [first, email],\n [first, phone],\n [last, email],\n [last, phone],\n ];\n\n // A combo whose field has no input yet arrives as undefined, not \"\" \u2014\n // without the coalesce a first-name-only probe counts as searchable, fires\n // an early lookup, and prematurely reveals \"Continue to add new contact\"\n // while the real (debounced) lookup is still in flight, where #continue is\n // a silent no-op.\n return searchCombos.some(combo => combo.every(value => (value ?? \"\").trim() !== \"\"));\n }\n\n #lookup (firstName, lastName, emailTargets, phoneTargets) {\n const emails = this.#valuesFor(emailTargets);\n const phones = this.#valuesFor(phoneTargets);\n\n if (!this.#searchable(firstName, lastName, emails[0], phones[0])) {\n return true;\n }\n\n const data = {\n \"contact[first_name]\": firstName,\n \"contact[last_name]\": lastName,\n \"phone_numbers[][number]\": phones[0] ?? \"\",\n \"email_addresses[][address]\": emails[0] ?? \"\",\n upsheet_id: this.upsheetIdValue,\n };\n\n this.inProgress = true;\n $(\"#search_status\").show();\n const name = this.firstNameTarget.value + \" \" + this.lastNameTarget.value;\n this.#setLabel(`Searching for \"${name}\"... `);\n this.spinnerTarget.classList.remove(\"hidden\");\n\n fetch(`/contacts/find_existing.json?${new URLSearchParams(data)}`)\n .then(response => response.json())\n .then(json => this.lookupComplete(json))\n .catch(_ => {\n // Reset the flag or one failed request wedges #continue forever.\n this.inProgress = false;\n alert(\n \"There was an error while searching for contacts. \" +\n \"Please refresh the page and try again.\",\n );\n });\n\n // this will cancel the form submit even if dups are not found so @lookupComplete\n // will need to submit the form in the event that no dups were found\n return false;\n }\n\n /**\n * @param elements {HTMLFormElement[]}\n * @returns string[]\n */\n #valuesFor (elements) {\n return Array.from(elements)\n .map(element => element.value)\n .filter(value => value.trim() !== \"\");\n }\n\n #hideMatches() {\n if (this.hasMatchesTarget) {\n this.matchesTarget.classList.replace(\"animate-fade-in\", \"animate-fade-out\");\n this.matchesTarget.classList.replace(\"max-h-[1000vh]\", \"max-h-0\");\n }\n\n this.#setLabel(\"No matches found yet.\");\n this.noMatchesTarget.classList.remove(\"hidden\");\n }\n\n lookupComplete (input) {\n this.inProgress = false;\n this.spinnerTarget.classList.add(\"hidden\");\n\n if (input.contact_count === 0) {\n if (this.submitClicked) { this.#resubmit(); }\n this.#hideMatches();\n } else if (input.fuzzy) {\n if (this.submitClicked) { this.#resubmit(); }\n this.#setLabel(`${input.contact_count} contacts found. Please continue adding information.`);\n } else if (input.exact) {\n $(\"#exact\").replaceWith(input.html);\n } else {\n const singleOrPlural = input.contact_count > 1 ? \"matches\" : \"match\";\n this.#setLabel(`Showing ${input.contact_count} ${singleOrPlural}.`);\n $(\"#matches\").replaceWith(input.html);\n }\n\n $(\"#search_status\").hide();\n this.submitClicked = false;\n }\n\n // requestSubmit fires a real submit event, so the editor's repeat guard and its\n // email/phone checks run; jQuery's submit() falls through to form.submit(), which skips both.\n #resubmit() {\n const form = this.form[0];\n if (form.requestSubmit) {\n form.requestSubmit();\n } else {\n this.form.submit();\n }\n }\n\n hide() {\n this.element.classList.add(\"hidden\");\n }\n\n #setLabel(label) {\n this.searchBarTarget.textContent = label;\n }\n\n checkExisting() {\n const isEmail = this.phoneOrEmailTarget.value.indexOf(\"@\") !== -1;\n\n this.search(\n this.firstNameTarget.value,\n this.lastNameTarget.value,\n isEmail ? [this.phoneOrEmailTarget] : [],\n isEmail ? [] : [this.phoneOrEmailTarget],\n );\n }\n\n checkCaps({ target: { value } }) {\n const capsIssue = value.length > 2 && value === value.toUpperCase();\n this.capsLockTarget.classList.toggle(\"hidden\", !capsIssue);\n }\n\n checkAnd({ target: { value } }) {\n if (value.match(/and|&|@|\\/|\\\\|\\+|,/)) {\n const s = value.split(/and|&|@|\\/|\\\\|\\+|,/);\n this.andFirstNameTarget.textContent = s[0];\n this.relatedTarget.classList.remove(\"hidden\");\n } else {\n this.relatedTarget.classList.add(\"hidden\");\n }\n }\n\n contactEditorOutletConnected() {\n if (this.contactEditorOutlet.newRecordValue) {\n this.firstNameTarget.focus();\n }\n }\n\n continue () {\n // Don't continue if we're searching so they won't miss the existing contact\n if (this.inProgress) {\n return;\n }\n\n this.hide();\n\n this.contactEditorOutlet.populate({\n firstName: this.firstNameTarget.value,\n lastName: this.lastNameTarget.value,\n phoneOrEmail: this.phoneOrEmailTarget.value,\n });\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Sends theme + field-visibility updates to the credit-app preview iframe via\n// postMessage. The iframe (rendered by app/views/layouts/credit_app.html.erb)\n// listens for `autoraptor:credit_app:theme` messages and updates CSS variables\n// + hides/shows sections without reloading.\nexport default class extends Controller {\n static values = { iframeSelector: String, originalLogoUrl: String };\n static targets = [\n \"primary\", \"formBg\", \"pageBg\",\n \"hideMiddleName\", \"hidePhone\", \"hideEmail\", \"hideVehicle\",\n \"logoFile\", \"removeLogo\",\n ];\n\n connect() {\n // Push initial state once the iframe finishes loading so refreshes pick up\n // unsaved-but-visible edits immediately.\n const iframe = this.iframe();\n if (iframe) iframe.addEventListener(\"load\", () => this.update());\n }\n\n update(event) {\n this.enforceContactExclusion(event);\n\n const iframe = this.iframe();\n if (!iframe || !iframe.contentWindow) return;\n iframe.contentWindow.postMessage({\n type: \"autoraptor:credit_app:theme\",\n primary: this.value(\"primary\"),\n formBg: this.value(\"formBg\"),\n pageBg: this.value(\"pageBg\"),\n fields: {\n middle_name: !this.checked(\"hideMiddleName\"),\n phone: !this.checked(\"hidePhone\"),\n email: !this.checked(\"hideEmail\"),\n vehicle: !this.checked(\"hideVehicle\"),\n ssn: this.fieldStateVisible(\"crs_credential[ssn_field_state]\"),\n birth_date: this.fieldStateVisible(\"crs_credential[birth_date_field_state]\"),\n },\n required: {\n ssn: this.fieldStateRequired(\"crs_credential[ssn_field_state]\"),\n birth_date: this.fieldStateRequired(\"crs_credential[birth_date_field_state]\"),\n },\n }, \"*\");\n }\n\n // SSN/DOB tristate radios: (\"hidden\" / \"optional\" / \"required\").\n // `fieldStateVisible` answers \"should this field be in the form?\";\n // `fieldStateRequired` answers \"must the user fill it before submit?\"\n // The iframe applies both via separate maps in the message \u2014 visibility\n // toggles the section's `hidden` attribute, required toggles the input's\n // `required` HTML attribute plus the \"(optional)\" label suffix and the\n // helper hint underneath.\n fieldStateVisible(name) {\n const checked = this.element.querySelector(`input[name=\"${name}\"]:checked`);\n if (!checked) return true; // default to shown when no radio is rendered\n return checked.value !== \"hidden\";\n }\n\n fieldStateRequired(name) {\n const checked = this.element.querySelector(`input[name=\"${name}\"]:checked`);\n if (!checked) return false;\n return checked.value === \"required\";\n }\n\n // Hiding both phone and email leaves the consumer with no way to be contacted,\n // which the model rejects (at_least_one_contact_field). Enforce mutual exclusion\n // in the UI so the user can't reach an invalid state in the first place.\n enforceContactExclusion(event) {\n if (!event || !event.target) return;\n if (!event.target.checked) return;\n const t = event.target;\n if (this.hasHideEmailTarget && t === this.hideEmailTarget && this.hasHidePhoneTarget) {\n this.hidePhoneTarget.checked = false;\n } else if (this.hasHidePhoneTarget && t === this.hidePhoneTarget && this.hasHideEmailTarget) {\n this.hideEmailTarget.checked = false;\n }\n }\n\n // Logo upload preview: read the file in the browser and ship a data URL to the\n // iframe. The actual upload still happens on form submit; this is just preview.\n previewLogoFile() {\n if (!this.hasLogoFileTarget) return;\n const file = this.logoFileTarget.files && this.logoFileTarget.files[0];\n if (!file) return;\n if (this.hasRemoveLogoTarget) this.removeLogoTarget.checked = false;\n const reader = new FileReader();\n reader.onload = (e) => this.sendLogo(e.target.result);\n reader.readAsDataURL(file);\n }\n\n previewLogoRemove() {\n if (!this.hasRemoveLogoTarget) return;\n if (this.removeLogoTarget.checked) {\n // Toggling \"Remove current logo\" also discards any unsaved file pick.\n if (this.hasLogoFileTarget) this.logoFileTarget.value = \"\";\n this.sendLogo(null);\n } else {\n this.sendLogo(this.originalLogoUrlValue || null);\n }\n }\n\n sendLogo(logoUrl) {\n const iframe = this.iframe();\n if (!iframe || !iframe.contentWindow) return;\n iframe.contentWindow.postMessage({\n type: \"autoraptor:credit_app:theme\",\n logo: logoUrl,\n }, \"*\");\n }\n\n iframe() {\n return document.querySelector(this.iframeSelectorValue);\n }\n\n value(target) {\n return this[`has${cap(target)}Target`] ? this[`${target}Target`].value : null;\n }\n\n checked(target) {\n return this[`has${cap(target)}Target`] ? this[`${target}Target`].checked : false;\n }\n}\n\nfunction cap(s) { return s.charAt(0).toUpperCase() + s.slice(1); }\n", "import { Controller } from \"@hotwired/stimulus\";\n\nexport default class extends Controller {\n static targets = [\"displayMode\", \"editMode\"];\n\n connect() {\n this.isEditMode = false;\n }\n\n toggleEditMode() {\n this.isEditMode = !this.isEditMode;\n this.updateDisplay();\n }\n\n cancelEdit() {\n this.isEditMode = false;\n this.updateDisplay();\n this.resetFormFields();\n }\n\n saveChanges() {\n this.isEditMode = false;\n this.updateDisplay();\n window.location.reload();\n }\n\n updateDisplay() {\n if (this.isEditMode) {\n this.displayModeTarget.classList.add(\"hidden\");\n this.editModeTarget.classList.remove(\"hidden\");\n } else {\n this.displayModeTarget.classList.remove(\"hidden\");\n this.editModeTarget.classList.add(\"hidden\");\n }\n }\n\n resetFormFields() {\n const formElements = this.editModeTarget.querySelectorAll(\"input, select, textarea\");\n formElements.forEach(element => {\n if (element.type === \"checkbox\") {\n element.checked = element.defaultChecked;\n } else {\n element.value = element.defaultValue;\n }\n });\n }\n\n updateValue(event) {\n const customFieldId = event.target.dataset.customFieldId;\n const upsheetId = event.target.dataset.upsheetId;\n const value = event.target.value;\n\n this.sendUpdate(upsheetId, customFieldId, value);\n }\n\n updateBooleanValue(event) {\n const customFieldId = event.target.dataset.customFieldId;\n const upsheetId = event.target.dataset.upsheetId;\n const value = event.target.checked ? \"true\" : \"false\";\n\n this.sendUpdate(upsheetId, customFieldId, value);\n }\n\n sendUpdate(upsheetId, customFieldId, value) {\n const url = `/upsheets/${upsheetId}/custom_field_values/${customFieldId}`;\n const csrfToken = document.querySelector(\"[name=\\\"csrf-token\\\"]\")?.content;\n\n if (!csrfToken) {\n this.showError(\"Security token not found\");\n return;\n }\n\n fetch(url, {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CSRF-Token\": csrfToken,\n },\n body: JSON.stringify({\n value,\n }),\n })\n .then(response => {\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n return response.json();\n })\n .then(data => {\n if (data.success) {\n this.showSuccess();\n } else {\n this.showError(data.error);\n }\n })\n .catch(error => {\n console.error(\"Error updating custom field:\", error);\n });\n }\n\n showSuccess() {\n }\n\n showError(message) {\n alert(\"Error updating custom field: \" + message);\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Drag-and-drop builder for the Home Dashboard settings page.\n//\n// Tiles are placed on a fixed-cell grid: each tile is { uid, key, w, h, x, y }\n// where w/h are the column/row span and x/y the top-left cell (0-based). A tile\n// can sit in any cell, leaving empty cells between tiles \u2014 gaps are intentional\n// and preserved (the rendered home page pins tiles to the same cells). On Save\n// the list is serialized to a hidden JSON field and the form is submitted.\nexport default class extends Controller {\n static targets = [\n \"grid\", \"endZone\", \"empty\", \"count\", \"configField\", \"form\",\n \"tileTemplate\", \"paletteItem\", \"paletteGroup\", \"helpDialog\", \"helpContent\",\n ];\n\n static values = { config: Array, catalog: Object, max: Number, storageKey: String };\n\n connect() {\n this.uid = 0;\n this.nodes = new Map();\n this.dragging = null; // { kind: 'palette', key } | { kind: 'tile', uid }\n this.tiles = (this.configValue || [])\n .filter((p) => this.catalogValue[p.key])\n .reduce((acc, p) => {\n if (!acc.some((t) => t.key === p.key)) acc.push(this.buildTile(p.key, p.w, p.h, p.x, p.y));\n return acc;\n }, []);\n this.seedPositions();\n this.render();\n this.restoreGroups();\n }\n\n // ---------- palette group collapse (persisted per user in localStorage) ----------\n // Default open state is server-rendered (Personal open, rest collapsed); a saved\n // map overrides it so the user's choices stick across reloads.\n // The `restoringGroups` flag suppresses re-entry in browsers that fire `toggle`\n // synchronously; where `toggle` is async the flag is already cleared, but the\n // resulting groupToggled() write equals the just-restored state (idempotent).\n restoreGroups() {\n const saved = this.savedGroups();\n if (!saved) return;\n this.restoringGroups = true;\n this.paletteGroupTargets.forEach((el) => {\n const name = el.dataset.group;\n if (Object.prototype.hasOwnProperty.call(saved, name)) el.open = !!saved[name];\n });\n this.restoringGroups = false;\n }\n\n groupToggled() {\n if (this.restoringGroups || !this.hasStorageKeyValue) return;\n const state = {};\n this.paletteGroupTargets.forEach((el) => { state[el.dataset.group] = el.open; });\n try {\n window.localStorage.setItem(this.storageKeyValue, JSON.stringify(state));\n } catch (_) {\n // storage unavailable (private mode / quota) \u2014 non-fatal, defaults still apply\n }\n }\n\n savedGroups() {\n if (!this.hasStorageKeyValue) return null;\n try {\n return JSON.parse(window.localStorage.getItem(this.storageKeyValue) || \"null\");\n } catch (_) {\n return null;\n }\n }\n\n get maxTiles() {\n return this.maxValue || 12;\n }\n\n // w = column span (1..maxCols), h = row span (1..maxRows). x/y = top-left cell;\n // left undefined here so seedPositions / dropAtCell assign a real slot. When a\n // size is passed (restoring a saved layout) it is used as-is; otherwise the tile\n // seeds from the widget's catalog default footprint (default_w/default_h),\n // falling back to 1x1 for an unknown key.\n buildTile(key, w, h, x, y) {\n const def = this.def(key);\n return {\n uid: ++this.uid,\n key,\n w: this.clampW(w ?? def.default_w),\n h: this.clampH(h ?? def.default_h),\n x: this.coord(x),\n y: this.coord(y),\n };\n }\n\n clampW(w) {\n const n = parseInt(w, 10);\n return Number.isFinite(n) ? Math.min(this.maxCols, Math.max(1, n)) : 1;\n }\n\n clampH(h) {\n const n = parseInt(h, 10);\n return Number.isFinite(n) ? Math.min(this.maxRows, Math.max(1, n)) : 1;\n }\n\n coord(v) {\n const n = parseInt(v, 10);\n return Number.isFinite(n) && n >= 0 ? n : null;\n }\n\n get maxCols() {\n return 5;\n }\n\n get maxRows() {\n return 2;\n }\n\n // Hard ceiling on the row index so a stray drop can't open an enormous gap.\n get maxGridRows() {\n return this.maxTiles;\n }\n\n // Live column count from the rendered grid (drops with the responsive\n // breakpoints), falling back to the design width.\n get cols() {\n const tracks = getComputedStyle(this.gridTarget).gridTemplateColumns.split(\" \").filter(Boolean).length;\n return tracks || this.maxCols;\n }\n\n def(key) {\n return this.catalogValue[key] || { name: key, preview_type: \"line\" };\n }\n\n indexOfUid(uid) {\n return this.tiles.findIndex((t) => t.uid === uid);\n }\n\n tileByUid(uid) {\n return this.tiles[this.indexOfUid(uid)];\n }\n\n // A report may appear at most once, and never beyond the server cap.\n canAdd(key) {\n return this.catalogValue[key] && !this.tiles.some((t) => t.key === key) && this.tiles.length < this.maxTiles;\n }\n\n // ---------- help modal ----------\n openHelp() {\n if (!this.helpDialogTarget.open) this.helpDialogTarget.showModal();\n }\n\n closeHelp(event) {\n if (event) event.preventDefault();\n if (this.helpDialogTarget.open) this.helpDialogTarget.close();\n }\n\n helpBackdrop(event) {\n if (!this.helpContentTarget.contains(event.target)) this.closeHelp();\n }\n\n // ---------- palette ----------\n addFromPalette(event) {\n const key = event.currentTarget.dataset.key;\n if (!this.canAdd(key)) return;\n const tile = this.buildTile(key);\n [tile.x, tile.y] = this.firstFreeCell(tile.w, tile.h);\n this.tiles.push(tile);\n this.render();\n }\n\n paletteDragStart(event) {\n const item = event.target.closest(\".db-palette-item\");\n if (!item) return;\n this.dragging = { kind: \"palette\", key: item.dataset.key };\n item.classList.add(\"is-dragging\");\n try {\n event.dataTransfer.effectAllowed = \"copy\";\n event.dataTransfer.setData(\"text/plain\", \"palette\");\n } catch (_) {}\n }\n\n // ---------- tiles ----------\n tileDragStart(event) {\n const tile = event.target.closest(\".db-tile\");\n if (!tile) return;\n this.dragging = { kind: \"tile\", uid: Number(tile.dataset.uid) };\n tile.classList.add(\"is-dragging\");\n try {\n event.dataTransfer.effectAllowed = \"move\";\n event.dataTransfer.setData(\"text/plain\", \"tile\");\n } catch (_) {}\n }\n\n gridDragOver(event) {\n if (!this.dragging) return;\n if (this.dragging.kind === \"palette\" && !this.canAdd(this.dragging.key)) return;\n event.preventDefault();\n this.setDropEffect(event);\n this.gridTarget.classList.add(\"is-drop-target\");\n const span = this.draggedSpan();\n const cell = this.cellFromEvent(event, span);\n this.showPlaceholder(cell.x, cell.y, span.w, span.h);\n }\n\n gridDragLeave(event) {\n // Only when the pointer actually leaves the grid (not on a child boundary).\n if (event.relatedTarget && this.gridTarget.contains(event.relatedTarget)) return;\n this.gridTarget.classList.remove(\"is-drop-target\");\n this.hidePlaceholder();\n }\n\n gridDrop(event) {\n if (!this.dragging) return;\n event.preventDefault();\n event.stopPropagation();\n const span = this.draggedSpan();\n const cell = this.cellFromEvent(event, span);\n this.dropAtCell(cell.x, cell.y);\n }\n\n // Remove button only \u2014 sizing is via the drag handle (resizeStart).\n gridClick(event) {\n const button = event.target.closest(\"button.db-tile-remove\");\n if (!button) return;\n const tile = button.closest(\".db-tile\");\n if (!tile) return;\n const idx = this.indexOfUid(Number(tile.dataset.uid));\n if (idx === -1) return;\n this.tiles.splice(idx, 1);\n this.render();\n }\n\n // ---------- drag-to-resize ----------\n // Pointer-drag the bottom-right handle: right \u2192 wider (1..maxCols columns, but\n // never past the right edge from the tile's column), down \u2192 taller (1..maxRows\n // rows). Snaps to the grid; widened/heightened tiles push neighbours down.\n resizeStart(event) {\n const node = event.target.closest(\".db-tile\");\n if (!node) return;\n const t = this.tileByUid(Number(node.dataset.uid));\n if (!t) return;\n event.preventDefault();\n event.stopPropagation();\n\n node.draggable = false; // don't let the reorder-drag fire while resizing\n node.classList.add(\"is-resizing\");\n\n const metrics = this.gridMetrics();\n const rect = node.getBoundingClientRect();\n const left = rect.left;\n const top = rect.top;\n\n const onMove = (e) => {\n const w = Math.min(this.cols - t.x, Math.max(1, Math.round((e.clientX - left) / (metrics.cellW + metrics.colGap))));\n const h = Math.min(this.maxRows, Math.max(1, Math.round((e.clientY - top) / (metrics.rowH + metrics.rowGap))));\n if (w !== t.w || h !== t.h) {\n t.w = w;\n t.h = h;\n this.pushDown(t);\n this.render();\n }\n };\n const onUp = () => {\n window.removeEventListener(\"pointermove\", onMove);\n window.removeEventListener(\"pointerup\", onUp);\n node.classList.remove(\"is-resizing\");\n node.draggable = true;\n };\n window.addEventListener(\"pointermove\", onMove);\n window.addEventListener(\"pointerup\", onUp);\n }\n\n // ---------- end zone / empty ----------\n endDragOver(event) {\n if (!this.dragging) return;\n if (this.dragging.kind === \"palette\" && !this.canAdd(this.dragging.key)) return;\n event.preventDefault();\n this.setDropEffect(event);\n event.currentTarget.classList.add(\"is-over\");\n }\n\n endDragLeave(event) {\n event.currentTarget.classList.remove(\"is-over\");\n }\n\n // Drop on the \"add another\" zone / empty state: append at the first free slot.\n endDrop(event) {\n if (!this.dragging) return;\n event.preventDefault();\n event.stopPropagation();\n this.dropAtCell(null, null);\n }\n\n dragEnd() {\n this.dragging = null;\n this.clearHighlight();\n this.element.querySelectorAll(\".is-dragging\").forEach((el) => el.classList.remove(\"is-dragging\"));\n }\n\n // ---------- mutations ----------\n // Place the dragged item at cell (x, y); a null cell means first-fit append.\n // Existing tiles overlapping the new rect are pushed down to make room.\n dropAtCell(x, y) {\n const d = this.dragging;\n this.dragging = null;\n this.clearHighlight();\n if (!d) return;\n\n let tile;\n if (d.kind === \"palette\") {\n if (!this.canAdd(d.key)) {\n this.render();\n return;\n }\n tile = this.buildTile(d.key);\n this.tiles.push(tile);\n } else {\n tile = this.tileByUid(d.uid);\n if (!tile) {\n this.render();\n return;\n }\n }\n\n if (x === null || y === null) {\n [tile.x, tile.y] = this.firstFreeCell(tile.w, tile.h, tile.uid);\n } else {\n tile.x = Math.min(Math.max(0, x), Math.max(0, this.cols - tile.w));\n tile.y = Math.min(Math.max(0, y), this.maxGridRows - 1);\n }\n this.pushDown(tile);\n this.render();\n }\n\n clearAll() {\n this.tiles = [];\n this.render();\n }\n\n save() {\n this.configFieldTarget.value = JSON.stringify({\n widgets: this.tiles.map((t) => ({ key: t.key, w: t.w, h: t.h, x: t.x, y: t.y })),\n });\n this.formTarget.requestSubmit();\n }\n\n // ---------- placement geometry ----------\n // The span (w, h) of whatever is currently being dragged.\n draggedSpan() {\n if (this.dragging?.kind === \"tile\") {\n const t = this.tileByUid(this.dragging.uid);\n if (t) return { w: t.w, h: t.h };\n }\n return { w: 1, h: 1 }; // a fresh palette tile is 1x1\n }\n\n gridMetrics() {\n const style = getComputedStyle(this.gridTarget);\n const rect = this.gridTarget.getBoundingClientRect();\n const cols = this.cols;\n const padL = parseFloat(style.paddingLeft) || 0;\n const padT = parseFloat(style.paddingTop) || 0;\n const padR = parseFloat(style.paddingRight) || 0;\n const colGap = parseFloat(style.columnGap) || 0;\n const rowGap = parseFloat(style.rowGap) || 0;\n const innerW = rect.width - padL - padR;\n const cellW = (innerW - colGap * (cols - 1)) / cols;\n const rowH = parseFloat(style.gridAutoRows) || cellW;\n return { rect, cols, padL, padT, colGap, rowGap, cellW, rowH };\n }\n\n // The cell the dragged tile's top-left would snap to under the pointer,\n // clamped so a w\u00D7h tile stays on the grid.\n cellFromEvent(event, span) {\n const m = this.gridMetrics();\n let cx = Math.floor((event.clientX - m.rect.left - m.padL) / (m.cellW + m.colGap));\n let cy = Math.floor((event.clientY - m.rect.top - m.padT) / (m.rowH + m.rowGap));\n cx = Math.min(Math.max(0, cx), m.cols - span.w);\n // Allow at most one new row below the current content (no runaway gaps).\n const bottom = this.tiles.reduce((max, t) => Math.max(max, t.y + t.h), 0);\n cy = Math.min(Math.max(0, cy), Math.min(this.maxGridRows - 1, bottom));\n return { x: cx, y: cy };\n }\n\n // First free w\u00D7h slot scanning rows top-down, left-to-right (excludes the\n // tile being moved, if any).\n firstFreeCell(w, h, excludeUid) {\n return this.scanFreeCell(this.occupancy(excludeUid), w, h, this.cols);\n }\n\n // First free w\u00D7h slot in `occupied` within `cols` columns. A row always\n // exists below the lowest occupied cell, so this terminates. Width is capped at\n // `cols` so a tile wider than the (responsive) grid still resolves a slot at\n // x=0 rather than spinning the x-loop forever \u2014 CSS clamps the visual span.\n scanFreeCell(occupied, w, h, cols) {\n const ww = Math.min(w, cols);\n for (let y = 0; ; y++) {\n for (let x = 0; x <= cols - ww; x++) {\n if (this.rectFree(occupied, x, y, ww, h)) return [x, y];\n }\n }\n }\n\n occupancy(excludeUid) {\n const set = new Set();\n this.tiles.forEach((t) => {\n if (t.uid === excludeUid || t.x == null || t.y == null) return;\n for (let dy = 0; dy < t.h; dy++) for (let dx = 0; dx < t.w; dx++) set.add(`${t.x + dx},${t.y + dy}`);\n });\n return set;\n }\n\n rectFree(occupied, x, y, w, h) {\n for (let dy = 0; dy < h; dy++) {\n for (let dx = 0; dx < w; dx++) {\n if (occupied.has(`${x + dx},${y + dy}`)) return false;\n }\n }\n return true;\n }\n\n // Push every tile overlapping `moved` straight down below it, cascading to the\n // tiles they then overlap. `moved` stays put; each push only increases y, so\n // this terminates. Gaps above are left untouched (no upward compaction).\n pushDown(moved) {\n const queue = [moved];\n const overlaps = (a, b) =>\n a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;\n while (queue.length) {\n const cur = queue.shift();\n this.tiles.forEach((t) => {\n if (t === cur || t.x == null) return;\n if (overlaps(cur, t)) {\n t.y = cur.y + cur.h;\n queue.push(t);\n }\n });\n }\n }\n\n // ---------- rendering ----------\n render() {\n this.clearHighlight();\n const has = this.tiles.length > 0;\n this.gridTarget.hidden = !has;\n this.endZoneTarget.hidden = !has;\n if (this.hasEmptyTarget) this.emptyTarget.hidden = has;\n\n // Render in reading order (top-to-bottom, left-to-right) so the narrow-width\n // flow fallback and DOM/tab order stay sensible.\n const ordered = [...this.tiles].sort((a, b) => a.y - b.y || a.x - b.x);\n const live = new Set();\n ordered.forEach((t) => {\n live.add(t.uid);\n const node = this.nodes.get(t.uid) || this.createNode(t);\n this.updateNode(node, t);\n this.gridTarget.appendChild(node); // moves into correct order\n });\n\n this.nodes.forEach((node, uid) => {\n if (!live.has(uid)) {\n node.remove();\n this.nodes.delete(uid);\n }\n });\n\n if (this.placeholder) this.gridTarget.appendChild(this.placeholder); // keep last\n this.updateMeta();\n }\n\n createNode(t) {\n const node = this.tileTemplateTarget.content.firstElementChild.cloneNode(true);\n node.dataset.uid = t.uid;\n // Prefer the per-widget preview (real labels for KPI/stat tiles); fall back\n // to the shared per-type template.\n const tmpl =\n this.element.querySelector(`template[data-preview-key=\"${t.key}\"]`) ||\n this.element.querySelector(`template[data-preview-type=\"${this.def(t.key).preview_type}\"]`);\n if (tmpl) node.querySelector(\".db-tile-preview\").appendChild(tmpl.content.cloneNode(true));\n this.nodes.set(t.uid, node);\n return node;\n }\n\n updateNode(node, t) {\n node.querySelector(\".db-tile-name\").textContent = this.def(t.key).name;\n this.applySize(node, t);\n }\n\n // Pin a tile's node to its cell via custom properties the stylesheet reads\n // (grid lines are 1-based). x is clamped so the tile fits the current width.\n applySize(node, t) {\n const x = Math.min(Math.max(0, t.x ?? 0), this.cols - t.w);\n node.style.setProperty(\"--gx\", x + 1);\n node.style.setProperty(\"--gy\", (t.y ?? 0) + 1);\n node.style.setProperty(\"--gw\", t.w);\n node.style.setProperty(\"--gh\", t.h);\n }\n\n updateMeta() {\n const n = this.tiles.length;\n this.countTarget.textContent = `${n} ${n === 1 ? \"report\" : \"reports\"}`;\n const atCapacity = n >= this.maxTiles;\n\n this.paletteItemTargets.forEach((item) => {\n const added = this.tiles.some((t) => t.key === item.dataset.key);\n item.classList.toggle(\"is-added\", added);\n const badge = item.querySelector(\".db-added\");\n if (badge) badge.hidden = !added;\n const addButton = item.querySelector(\".db-add\");\n if (addButton) addButton.disabled = added || atCapacity;\n });\n }\n\n // ---------- drop highlight ----------\n // A green dashed ghost pinned to the cell the tile would land in.\n showPlaceholder(x, y, w, h) {\n if (!this.placeholder) {\n this.placeholder = document.createElement(\"div\");\n this.placeholder.className = \"db-drop-ph\";\n this.gridTarget.appendChild(this.placeholder);\n }\n this.placeholder.style.setProperty(\"--gx\", x + 1);\n this.placeholder.style.setProperty(\"--gy\", y + 1);\n this.placeholder.style.setProperty(\"--gw\", w);\n this.placeholder.style.setProperty(\"--gh\", h);\n this.placeholder.hidden = false;\n }\n\n hidePlaceholder() {\n if (this.placeholder) this.placeholder.hidden = true;\n }\n\n clearHighlight() {\n this.gridTarget.classList.remove(\"is-drop-target\");\n this.endZoneTarget.classList.remove(\"is-over\");\n if (this.hasEmptyTarget) this.emptyTarget.classList.remove(\"is-over\");\n this.hidePlaceholder();\n }\n\n // ---------- bootstrap ----------\n // Assign a cell to any tile missing valid coordinates (legacy configs), and\n // resolve overlaps, by first-fit packing in order \u2014 mirrors the server.\n seedPositions() {\n const occupied = new Set();\n const free = (x, y, w, h) => x != null && y != null && x >= 0 && y >= 0 && x + w <= this.maxCols &&\n this.rectFree(occupied, x, y, w, h);\n const mark = (x, y, w, h) => {\n for (let dy = 0; dy < h; dy++) for (let dx = 0; dx < w; dx++) occupied.add(`${x + dx},${y + dy}`);\n };\n this.tiles.forEach((t) => {\n if (!free(t.x, t.y, t.w, t.h)) {\n [t.x, t.y] = this.scanFreeCell(occupied, t.w, t.h, this.maxCols); // first-fit so far\n }\n mark(t.x, t.y, t.w, t.h);\n });\n }\n\n setDropEffect(event) {\n try {\n event.dataTransfer.dropEffect = this.dragging?.kind === \"palette\" ? \"copy\" : \"move\";\n } catch (_) {}\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"dashboard--bulletin\"\nexport default class extends Controller {\n static targets = [\n \"body\",\n \"form\",\n ];\n\n show() {\n this.formTarget.classList.remove(\"hidden\");\n this.bodyTarget.focus();\n }\n\n hide() {\n this.formTarget.classList.add(\"hidden\");\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\nexport default class extends Controller {\n static values = {\n prevMonth: Object,\n thisMonth: Object,\n };\n\n connect() {\n // Render into this controller's own element, not a hardcoded document-wide id.\n // The custom home dashboard can show this sparkline (my_sold_trend tile) on the\n // SAME page as the fixed sales-rep summary, which also uses this controller \u2014 a\n // shared getElementById id would collide and one chart would draw into the other.\n Highcharts.chart(this.element, {\n accessibility: { enabled: false },\n chart: {\n type: \"spline\",\n spacingTop: 0,\n spacingRight: 0,\n spacingBottom: 1,\n spacingLeft: 0,\n },\n credits: {\n enabled: false,\n },\n legend: {\n enabled: false,\n },\n xAxis: {\n gridLineWidth: 0,\n labels: {\n enabled: false,\n },\n minorTicks: false,\n plotLines: [{\n color: \"#50738a\",\n label: {\n align: \"right\",\n rotation: 0,\n style: {\n color: \"#50738a\",\n },\n text: \"Today\",\n textAlign: \"bottom\",\n },\n value: this.thisMonthValue.length - 1,\n width: 1,\n zIndex: 100,\n }],\n tickLength: 0,\n title: {\n enabled: false,\n },\n },\n yAxis: {\n gridLineWidth: 0,\n labels: {\n enabled: false,\n },\n minorTicks: false,\n plotBands: [{\n color: \"#f2f7fa\",\n from: 0,\n to: this.thisMonthValue.data.at(-1),\n }],\n plotLines: [{\n color: \"#c9dae5\",\n dashStyle: \"dash\",\n value: this.thisMonthValue.data.at(-1),\n width: 1,\n }],\n tickLength: 0,\n title: {\n enabled: false,\n },\n },\n plotOptions: {\n spline: {\n label: {\n enabled: false,\n },\n marker: {\n enabled: false,\n },\n },\n series: {\n pointStart: 1,\n },\n },\n series: [{\n color: \"#50738a\",\n data: this.prevMonthValue.data,\n name: this.prevMonthValue.month_name,\n }, {\n color: \"#13344a\",\n data: this.thisMonthValue.data,\n name: this.thisMonthValue.month_name,\n }],\n title: {\n text: null,\n },\n tooltip: {\n headerFormat: \"Sold
\",\n pointFormat: \"{series.name} {point.x}: {point.y}
\",\n shared: true,\n },\n });\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport { trackEvent } from \"@/utils/analytics\";\n\n// Connects to data-controller=\"dashboard--stats\"\nexport default class extends Controller {\n static targets = [\n \"expandedRow\",\n \"selectedRow\",\n ];\n\n click({ target }) {\n const button = target.closest(\"a\");\n\n this.expandedRowTargets.forEach(expandedRow => {\n expandedRow.remove();\n });\n\n this.selectedRowTargets.forEach(selectedRow => {\n selectedRow.classList.remove(\"row-open\");\n });\n\n const open = button.classList.toggle(\"open\");\n if (open) {\n button.closest(\"tr\").classList.add(\"row-open\");\n this.expand_row(button);\n } else {\n trackEvent({ category: \"Dashboard\", action: \"activity-drilldown\", label: target.textContent });\n }\n }\n\n expand_row(button) {\n const drilldown_url = button.getAttribute(\"data-drilldown-url\");\n const clicked_row = button.closest(\"tr\");\n\n $.getJSON(drilldown_url, (all_data) => {\n clicked_row.insertAdjacentHTML(\"afterend\", all_data.stat_rows);\n });\n }\n}\n", "// Shared Highcharts definitions for the Insights performance charts, used by\n// the Insights page (reports--insights) and by custom home dashboard cards\n// (dashboard--widget-chart). Each entry provides config() for the empty chart\n// and load(chart, response) to render a fetched JSON payload, and\n// fetchChartData() is the request both callers go through.\n\n// Ask for JSON explicitly. Without a dataType jQuery sends `Accept: */*`, and\n// access_denied (lib/authenticated_system.rb) answers that with its `want.html`\n// branch \u2014 a 302 to the login page that XHR follows to a 200. jQuery then\n// hands .done() the login HTML as a string and the load functions below throw\n// on an undefined payload key. Requesting JSON reaches the `want.json` branch\n// instead: 403 + require_login, which we turn into a re-login.\n//\n// The 403 is handled here rather than by the global ajaxError hook in app.js,\n// which matches on statusText (\"Forbidden\") \u2014 empty over HTTP/2 in Chrome.\nexport function fetchChartData(url) {\n return $.ajax({ url, dataType: \"json\" }).fail((jqXHR) => {\n if (jqXHR.status === 403 && jqXHR.responseJSON?.require_login) {\n window.location.href = \"/login\";\n }\n });\n}\n\nfunction attachBadLeadData(soldPoint, totalPoint, item) {\n if (item.bad_leads !== undefined) {\n const badLeadPct = item.bad_lead_pct != null ? Math.floor(item.bad_lead_pct) + \"%\" : \"N/A\";\n soldPoint.badLeads = item.bad_leads;\n soldPoint.badLeadPct = badLeadPct;\n totalPoint.badLeads = item.bad_leads;\n totalPoint.badLeadPct = badLeadPct;\n }\n}\n\n// Design-system chart surface (see ~/projects/work/design/AutoRaptor Design System,\n// \"Visual foundations\"): flat white card, navy ink, slate captions, hairline rules.\n// The two performance charts were the last dark holdouts on Insights \u2014 the\n// lead_temperature config below was already light, so this puts the page on one\n// theme (sc-16203).\nconst dsChart = {\n surface: \"#FFFFFF\",\n ink: \"#13344A\",\n muted: \"#50738A\",\n hairline: \"#DCE3E8\",\n\n // Weekend shading. This was #122634, then #132232 when the near-miss colours\n // were swept \u2014 both near-black, and at full opacity a weekend slab is the\n // loudest mark on a white chart, so the bars it sits behind read as the\n // background and it reads as the data. A band is context: it has to sit under\n // the series, not over them.\n weekendBand: \"#F2F7FA\",\n\n // The design system publishes no chart palette, so these are the steps from it\n // that survive validation as a categorical set: red-500, blue-500 and the link\n // green, in that order. Checked with the palette validator against both the\n // white card surface and the navy one used by the e-lead trend chart \u2014\n // lightness band, chroma floor, CVD separation, normal-vision floor and\n // contrast all pass. Do not extend this past three by generating a hue; a\n // fourth category folds into \"Other\".\n series: {\n badLeads: \"#F24C15\",\n created: \"#1976D2\",\n sold: \"#00A006\",\n },\n};\n\nconst performanceTooltip = {\n useHTML: true,\n backgroundColor: dsChart.surface,\n borderColor: dsChart.hairline,\n borderWidth: 1,\n style: {\n color: dsChart.ink,\n },\n formatter: function() {\n let tooltip = \"Closing Rate: \" + this.point.rate + \"
\" + this.series.name + \": \" + this.point.y;\n if (this.point.badLeads !== undefined) {\n tooltip += \"
Bad Leads: \" + this.point.badLeads + \" (\" + this.point.badLeadPct + \")\";\n }\n return tooltip;\n },\n};\n\nconst loadingStyle = {\n style: {\n position: \"absolute\",\n backgroundColor: dsChart.surface,\n color: dsChart.muted,\n opacity: 1,\n textAlign: \"center\",\n },\n};\n\nconst noDataStyle = {\n style: {\n color: dsChart.muted,\n },\n};\n\nfunction barChartConfig({ title, xAxisLabels, yAxisLabelsStyle }) {\n return {\n chart: {\n type: \"bar\",\n style: {\n fontFamily: \"Open Sans\",\n },\n backgroundColor: dsChart.surface,\n },\n loading: loadingStyle,\n noData: noDataStyle,\n plotOptions: {\n bar: {\n // Off on purpose. With colorByPoint the chart paints every bar its own\n // hue, which is what dragged in Highcharts' stock palette \u2014 the axis\n // already names each category, so the colour was carrying nothing.\n // Identity here belongs to the series, not the bar.\n colorByPoint: false,\n borderWidth: 0,\n },\n },\n title: {\n text: title,\n align: \"left\",\n style: {\n color: dsChart.ink,\n fontSize: \"19px\",\n fontWeight: \"bold\",\n },\n },\n xAxis: {\n lineColor: dsChart.hairline,\n tickColor: dsChart.hairline,\n labels: xAxisLabels,\n scrollbar: {\n enabled: true,\n showFull: false,\n },\n },\n yAxis: {\n title: {\n text: \"Up Sheets\",\n style: {\n color: dsChart.muted,\n },\n },\n allowDecimals: false,\n gridLineColor: dsChart.hairline,\n labels: {\n style: yAxisLabelsStyle,\n },\n },\n legend: {\n enabled: false,\n },\n tooltip: performanceTooltip,\n credits: { enabled: false },\n };\n}\n\nfunction dealershipPerformanceConfig() {\n return {\n chart: {\n type: \"column\",\n style: {\n fontFamily: \"Open Sans\",\n },\n backgroundColor: dsChart.surface,\n },\n loading: loadingStyle,\n noData: noDataStyle,\n plotOptions: {\n column: {\n // Off on purpose. With colorByPoint the chart paints every bar its own\n // hue, which is what dragged in Highcharts' stock palette \u2014 the axis\n // already names each category, so the colour was carrying nothing.\n // Identity here belongs to the series, not the bar.\n colorByPoint: false,\n borderWidth: 0,\n },\n },\n title: {\n text: \"Daily Dealership Trend\",\n align: \"left\",\n margin: 30,\n style: {\n color: dsChart.ink,\n fontSize: \"19px\",\n fontWeight: \"bold\",\n },\n },\n xAxis: {\n lineColor: dsChart.hairline,\n tickColor: dsChart.hairline,\n labels: {\n style: {\n color: dsChart.muted,\n fontSize: \"12px\",\n },\n },\n },\n yAxis: {\n title: {\n align: \"high\",\n text: \"Up Sheets\",\n offset: 0,\n rotation: 0,\n y: -20,\n x: 0,\n style: {\n color: dsChart.muted,\n // A horizontal y-axis title is capped at the axis length. On a short\n // dashboard card the plot is under 60px tall, so \"Up Sheets\" wrapped\n // and its second line ran off the card's left edge.\n whiteSpace: \"nowrap\",\n },\n },\n allowDecimals: false,\n gridLineColor: dsChart.hairline,\n labels: {\n style: {\n color: dsChart.muted,\n fontSize: \"12px\",\n },\n },\n },\n legend: {\n enabled: false,\n },\n tooltip: {\n useHTML: true,\n backgroundColor: dsChart.surface,\n borderColor: dsChart.hairline,\n borderWidth: 1,\n style: {\n color: dsChart.ink,\n },\n },\n credits: { enabled: false },\n };\n}\n\nfunction leadTemperatureConfig() {\n return {\n chart: {\n type: \"pie\",\n style: {\n fontFamily: \"Open Sans\",\n },\n // Transparent so the donut sits on the white DS card the custom dashboard\n // always renders (see views/_redesign_overrides.css). Slice colours stay\n // semantic (hot/warm/cold); title/labels/legend use the DS ink tokens.\n backgroundColor: \"transparent\",\n },\n loading: loadingStyle,\n // noDataStyle's white text is invisible on the white DS card -> DS ink.\n noData: { ...noDataStyle, style: { ...noDataStyle.style, color: \"#50738a\" } },\n title: {\n text: \"Open Leads by Temperature\",\n align: \"left\",\n style: {\n color: \"#13344a\",\n fontSize: \"19px\",\n fontWeight: \"bold\",\n },\n },\n plotOptions: {\n pie: {\n innerSize: \"60%\",\n borderWidth: 0,\n dataLabels: {\n enabled: true,\n format: \"{point.name}: {point.y}\",\n style: {\n color: \"#13344a\",\n },\n },\n },\n },\n legend: {\n enabled: true,\n itemStyle: {\n color: \"#50738a\",\n },\n },\n tooltip: {\n useHTML: true,\n backgroundColor: dsChart.surface,\n borderColor: dsChart.hairline,\n borderWidth: 1,\n style: {\n color: dsChart.ink,\n },\n pointFormat: \"{point.y} ({point.percentage:.0f}%)\",\n },\n credits: { enabled: false },\n };\n}\n\nfunction loadLeadTemperature(chart, response) {\n while (chart.series.length > 0) {\n chart.series[0].remove(true);\n }\n chart.hideLoading();\n\n chart.addSeries({\n name: \"Open Leads\",\n colorByPoint: false,\n data: response.data,\n });\n}\n\nfunction loadSourcePerformance(chart, response) {\n while (chart.series.length > 0) {\n chart.series[0].remove(true);\n }\n chart.hideLoading();\n\n const sources = response.sources;\n const data = response.data;\n\n const soldSeries = {\n name: \"Up Sheets Closed\",\n data: [],\n color: dsChart.series.sold,\n };\n\n const totalSeries = {\n name: \"Up Sheets Created\",\n data: [],\n color: dsChart.series.created,\n };\n\n const sourceNames = [];\n\n for (let i = 0; i < sources.length; i++) {\n const source = sources[i];\n const item = data[source];\n\n let rate;\n if (item.rate == null) {\n rate = \"N/A\";\n } else {\n rate = Math.floor(item.rate) + \"%\";\n }\n\n const soldPoint = { y: item.sold, rate };\n const totalPoint = { y: item.total, rate };\n attachBadLeadData(soldPoint, totalPoint, item);\n\n soldSeries.data.push(soldPoint);\n totalSeries.data.push(totalPoint);\n sourceNames.push(source + \"-
\" + rate + \" CP\");\n }\n\n const min = sources.length > 0 ? 0 : null;\n let max = null;\n if (sources.length > 0 && sources.length <= 12) {\n max = sources.length - 1;\n } else if (sources.length > 0 && sources.length > 12) {\n max = 12 - 1;\n }\n\n chart.xAxis[0].setExtremes(min, max);\n chart.xAxis[0].setCategories(sourceNames);\n chart.addSeries(soldSeries);\n chart.addSeries(totalSeries);\n}\n\nfunction loadSalesRepPerformance(chart, response) {\n chart.hideLoading();\n\n while (chart.series.length > 0) {\n chart.series[0].remove(true);\n }\n\n const reps = response.reps;\n const urls = response.urls;\n const data = response.data;\n\n const soldSeries = {\n name: \"Up Sheets Sold\",\n data: [],\n color: dsChart.series.sold,\n };\n\n const totalSeries = {\n name: \"Up Sheets Created\",\n data: [],\n color: dsChart.series.created,\n };\n\n const repNames = [];\n\n for (let i = 0; i < reps.length; i++) {\n const rep = reps[i];\n const url = urls[i];\n const repId = rep.id;\n const item = data[repId];\n\n let rate;\n if (item.rate == null) {\n rate = \"N/A\";\n } else {\n rate = Math.floor(item.rate) + \"%\";\n }\n\n const soldPoint = { y: item.sold, rate };\n const totalPoint = { y: item.total, rate };\n attachBadLeadData(soldPoint, totalPoint, item);\n\n soldSeries.data.push(soldPoint);\n totalSeries.data.push(totalPoint);\n repNames.push(\"
\" + rep.name + \"-
\" + rate + \" CP\" + \"
\");\n }\n\n const min = reps.length > 0 ? 0 : null;\n let max = null;\n if (reps.length > 0 && reps.length <= 12) {\n max = reps.length - 1;\n } else if (reps.length > 0 && reps.length > 12) {\n max = 12 - 1;\n }\n\n chart.xAxis[0].setExtremes(min, max);\n chart.xAxis[0].setCategories(repNames);\n chart.addSeries(soldSeries);\n chart.addSeries(totalSeries);\n}\n\nfunction loadDealershipPerformance(chart, response) {\n const SATURDAY = 6;\n const SUNDAY = 0;\n\n chart.hideLoading();\n\n while (chart.xAxis[0].plotLinesAndBands.length > 0) {\n chart.xAxis[0].removePlotBand(chart.xAxis[0].plotLinesAndBands[0].id);\n }\n\n while (chart.series.length > 0) {\n chart.series[0].remove(true);\n }\n\n const dayBuckets = response.day_buckets;\n const data = response.data;\n\n // Series colours are picked for the white card this chart now sits on\n // (sc-16203). The old pair was chosen against navy: #3C5671 for Created read\n // as a mid-tone there, but on white it becomes the darkest thing on the page\n // and swamps the Sold bars beside it.\n //\n // An earlier pass gave Created the DS slate (#50738A) for calm. The palette\n // validator rejects that: slate's chroma is 0.054, under the floor that keeps\n // a categorical hue from reading as gray, and it sits \u0394E 11.5 from the blue\n // beside it \u2014 under the 15 floor, so full-colour readers struggle to tell the\n // two series apart. Sold now takes the green, Created the blue and Bad Leads\n // the red, an order in which no two adjacent slots collide.\n const soldSeries = {\n name: \"Up Sheets Sold\",\n data: [],\n color: dsChart.series.sold,\n };\n\n const totalSeries = {\n name: \"Up Sheets Created\",\n data: [],\n color: dsChart.series.created,\n };\n\n const badLeadSeries = {\n name: \"Bad Leads\",\n data: [],\n color: dsChart.series.badLeads,\n };\n\n const dayBucketNames = [];\n\n for (let i = 0; i < dayBuckets.length; i++) {\n const dayBucket = dayBuckets[i];\n const item = data[dayBucket];\n\n soldSeries.data.push({ y: item.sold });\n totalSeries.data.push({ y: item.total });\n\n if (item.bad_leads !== undefined) {\n badLeadSeries.data.push({ y: item.bad_leads });\n }\n\n const currentDayOfWeek = moment(dayBucket).weekday();\n\n if (i === 0 && currentDayOfWeek === SUNDAY) {\n chart.xAxis[0].addPlotBand({ color: dsChart.weekendBand, id: \"plotBand-\" + i, from: i - 0.5, to: i + 0.5 });\n } else if ((i === dayBuckets.length - 1) && currentDayOfWeek === SATURDAY) {\n chart.xAxis[0].addPlotBand({ color: dsChart.weekendBand, id: \"plotBand-\" + i, from: i - 0.5, to: i + 0.5 });\n } else if (currentDayOfWeek === SATURDAY) {\n chart.xAxis[0].addPlotBand({ color: dsChart.weekendBand, id: \"plotBand-\" + i, from: i - 0.5, to: i + 1.5 });\n }\n\n const date = dayBucket.split(\"-\");\n const month = parseInt(date[1], 10);\n const day = parseInt(date[2], 10);\n dayBucketNames.push(month + \"/\" + day);\n }\n\n chart.xAxis[0].setCategories(dayBucketNames);\n chart.addSeries(soldSeries);\n chart.addSeries(totalSeries);\n\n if (badLeadSeries.data.length > 0) {\n chart.addSeries(badLeadSeries);\n }\n}\n\nexport const insightCharts = {\n source_performance_report: {\n config: () => barChartConfig({\n title: \"Monthly Source Performance\",\n xAxisLabels: {\n style: {\n color: dsChart.muted,\n fontSize: \"12px\",\n },\n },\n yAxisLabelsStyle: {\n color: dsChart.muted,\n fontSize: \"12px\",\n },\n }),\n load: loadSourcePerformance,\n },\n sales_rep_performance_report: {\n config: () => barChartConfig({\n title: \"Monthly Sales Rep Performance\",\n xAxisLabels: {\n style: {\n color: dsChart.muted,\n fontSize: \"12px\",\n lineHeight: 1,\n },\n useHTML: true,\n },\n yAxisLabelsStyle: {\n color: dsChart.muted,\n fontSize: \"12px\",\n },\n }),\n load: loadSalesRepPerformance,\n },\n dealership_performance_report: {\n config: dealershipPerformanceConfig,\n load: loadDealershipPerformance,\n },\n lead_temperature: {\n config: leadTemperatureConfig,\n load: loadLeadTemperature,\n },\n};\n", "import { Controller } from \"@hotwired/stimulus\";\nimport { insightCharts, fetchChartData } from \"../reports/insight_charts\";\n\n// Renders one Insights chart inside a custom home dashboard card\n// (see Dashboard::WidgetRegistry :chart widgets).\nexport default class extends Controller {\n static values = { report: String };\n\n connect() {\n const definition = insightCharts[this.reportValue];\n if (!definition) return;\n\n $(this.element).highcharts(definition.config());\n const chart = $(this.element).highcharts();\n chart.showLoading();\n fetchChartData(`/insights/${this.reportValue}`)\n .done((response) => definition.load(chart, response));\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"dealership--lead-assignment-settings\"\n// Governs the interactive behavior of the Schedule-Aware Round-Robin \"Settings\"\n// tab form:\n// * Lead distribution: hides availability, fallback and pace as a group when\n// the dealership assigns nothing, since all three describe how leads get\n// assigned.\n// * Fallback: reveals the nominated-user picker only when the \"Assign to a\n// specific person\" strategy is selected, and blocks submit (with an inline\n// error) when that strategy is chosen without a user.\n// * Auto-reply: reveals the sender-name / template fields only when the\n// \"Auto-reply via email\" checkbox is enabled.\nexport default class extends Controller {\n static targets = [\n \"autoAssign\",\n \"autoAssignDetails\",\n \"strategy\",\n \"nominatedUser\",\n \"error\",\n \"autoReply\",\n \"autoReplyDetails\",\n ];\n\n connect() {\n this.toggleAutoAssign();\n this.toggleFallback();\n this.toggleAutoReply();\n }\n\n toggleAutoAssign() {\n if (!this.hasAutoAssignDetailsTarget) return;\n this.autoAssignDetailsTarget.style.display = this.autoAssignSelected()\n ? \"\"\n : \"none\";\n }\n\n toggleFallback() {\n const nominated = this.nominatedSelected();\n this.nominatedUserTarget.style.display = nominated ? \"\" : \"none\";\n if (!nominated || this.selectedUserId()) {\n this.hideError();\n }\n }\n\n toggleAutoReply() {\n if (!this.hasAutoReplyDetailsTarget) return;\n this.autoReplyDetailsTarget.style.display = this.autoReplyTarget.checked\n ? \"\"\n : \"none\";\n }\n\n // The fallback only decides anything while leads are being assigned, so a\n // dealership that assigns nothing is not held to it \u2014 otherwise the block\n // would fire on an error message inside the hidden section, with nothing on\n // screen to explain it. Dealership#nominated_fallback_requires_user makes the\n // same exemption server-side.\n validate(event) {\n if (\n this.autoAssignSelected() &&\n this.nominatedSelected() &&\n !this.selectedUserId()\n ) {\n event.preventDefault();\n this.showError();\n }\n }\n\n autoAssignSelected() {\n // No radios on the page (or none checked yet) means the section was never\n // rendered \u2014 treat that as assigning, matching the column default.\n if (this.autoAssignTargets.length === 0) return true;\n\n return this.autoAssignTargets.some(\n (radio) => radio.checked && radio.value === \"true\",\n );\n }\n\n nominatedSelected() {\n return this.strategyTargets.some(\n (radio) => radio.checked && radio.value === \"nominated\",\n );\n }\n\n selectedUserId() {\n const select = this.nominatedUserTarget.querySelector(\"select\");\n return select ? select.value : \"\";\n }\n\n showError() {\n if (this.hasErrorTarget) {\n this.errorTarget.hidden = false;\n }\n }\n\n hideError() {\n if (this.hasErrorTarget) {\n this.errorTarget.hidden = true;\n }\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// How often to re-check whether the reader is still busy, once an update has\n// been deferred. Short enough that the frame catches up a moment after the\n// reader lets go, long enough that it costs nothing while they work.\nconst BUSY_RECHECK_INTERVAL = 3000;\n\n// Connects to data-controller=\"dealership--insights-poller\"\n//\n// Attached directly to the element on the eleads\n// page. Updates normally arrive as Turbo Stream broadcasts (the server\n// broadcasts a `turbo_stream.update` targeting this frame's id a few seconds\n// after an assignment, rotation toggle or schedule edit \u2014 see the job's\n// DEBOUNCE_WINDOW and COMMIT_HEADROOM), so this controller is not\n// the thing that keeps the tab fresh \u2014 it is the safety net and the traffic cop:\n//\n// * Fallback refresh. Every `interval` (5 min by default) it reloads the\n// frame from the Insights endpoint, so a dropped websocket or a missed\n// broadcast can never leave the tab stale indefinitely. The frame renders\n// its content eagerly (no src), so the first live refresh sets `src` to\n// kick off the fetch and every one after that calls `reload()`.\n// This request is also what tells the server someone is still reading, so\n// that it keeps broadcasting (LeadAssignment::InsightsBroadcastJob's\n// PRESENCE_WINDOW, which is sized against this interval). Lengthening the\n// interval past that window would quietly stop the pushes between reloads;\n// the interval is passed in from FALLBACK_REFRESH for that reason.\n// * Defer and apply. A refresh mid-interaction wipes an in-progress filter,\n// steals focus, or throws away half-entered hours \u2014 the roster the schedule\n// editors live on is inside this frame (sc-16605), so a swap replaces the\n// whole thing, open panel and all. So while the reader is busy, an incoming\n// broadcast is cancelled (`turbo:before-stream-render` +\n// `preventDefault()`) and the frame is marked dirty instead; the same goes\n// for a fallback tick. As soon as they stop being busy, one `reload()`\n// converges everything that was missed in a single GET.\n// * Catch-up on return. A hidden tab skips its ticks, and the server stops\n// pushing to it once its presence expires (the fallback refresh is what\n// renews presence \u2014 see LeadAssignment::InsightsBroadcastJob.mark_watched),\n// so what is on screen when the reader comes back can be minutes old. Coming\n// back into view refreshes it, if it is actually behind.\nexport default class extends Controller {\n static values = {\n url: String,\n interval: {\n type: Number,\n default: 300000,\n },\n };\n\n connect() {\n this.loaded = false;\n this.dirty = false;\n // What is on screen was just rendered by the server.\n this.lastRefreshAt = Date.now();\n\n this.startTimer();\n\n this.onBeforeStreamRender = (event) => this.interceptStreamRender(event);\n document.addEventListener(\"turbo:before-stream-render\", this.onBeforeStreamRender);\n\n this.onFrameRender = () => this.startTimer();\n this.element.addEventListener(\"turbo:frame-render\", this.onFrameRender);\n\n this.onVisibilityChange = () => this.visibilityChanged();\n document.addEventListener(\"visibilitychange\", this.onVisibilityChange);\n }\n\n disconnect() {\n this.stopTimer();\n this.stopBusyWatch();\n\n document.removeEventListener(\"turbo:before-stream-render\", this.onBeforeStreamRender);\n document.removeEventListener(\"visibilitychange\", this.onVisibilityChange);\n this.element.removeEventListener(\"turbo:frame-render\", this.onFrameRender);\n }\n\n // Ticks are skipped while hidden and broadcasts stop arriving once presence\n // lapses, so coming back into view is the moment to catch up. Only when there\n // is something to catch up on, though \u2014 flicking between tabs must not fire a\n // GET each time.\n visibilityChanged() {\n if (document.hidden) {\n return;\n }\n\n if (!this.dirty && Date.now() - this.lastRefreshAt < this.intervalValue) {\n return;\n }\n\n this.tick();\n }\n\n tick() {\n if (document.hidden) {\n this.startTimer();\n return;\n }\n\n if (this.isBusy()) {\n this.deferUpdate();\n return;\n }\n\n this.refresh();\n }\n\n // A broadcast that would swap the frame out from under someone mid-edit is\n // cancelled here and replayed as a single reload once they are done.\n interceptStreamRender(event) {\n const stream = event.target;\n\n if (!stream || typeof stream.getAttribute !== \"function\") {\n return;\n }\n\n if (stream.getAttribute(\"target\") !== this.element.id) {\n return;\n }\n\n if (!this.isBusy()) {\n this.contentIsCurrent();\n return;\n }\n\n event.preventDefault();\n this.deferUpdate();\n }\n\n contentIsCurrent() {\n this.lastRefreshAt = Date.now();\n this.startTimer();\n }\n\n deferUpdate() {\n this.dirty = true;\n this.startBusyWatch();\n }\n\n refresh() {\n this.dirty = false;\n this.lastRefreshAt = Date.now();\n this.stopBusyWatch();\n this.startTimer();\n\n if (this.loaded) {\n this.element.reload();\n } else {\n this.loaded = true;\n this.element.src = this.urlValue;\n }\n }\n\n // Only runs while there is something to apply, and stops as soon as it fires.\n startBusyWatch() {\n if (this.busyTimer) {\n return;\n }\n\n this.busyTimer = setInterval(() => {\n if (!this.dirty) {\n this.stopBusyWatch();\n return;\n }\n\n if (this.isBusy()) {\n return;\n }\n\n this.refresh();\n }, BUSY_RECHECK_INTERVAL);\n }\n\n stopBusyWatch() {\n if (this.busyTimer) {\n clearInterval(this.busyTimer);\n this.busyTimer = null;\n }\n }\n\n isBusy() {\n if (this.element.contains(document.activeElement)) {\n return true;\n }\n\n if (this.editorIsOpen()) {\n return true;\n }\n\n return this.filterInputs().some((input) => input.value.trim() !== \"\");\n }\n\n filterInputs() {\n return Array.from(\n this.element.querySelectorAll(\"input[data-filterable-table-target='search']\"),\n );\n }\n\n // The schedule-editor controller reflects its expanded state back onto the\n // element as a Stimulus value, so the open panels are readable from here\n // without reaching into another controller.\n editorIsOpen() {\n return (\n this.element.querySelector(\n \"[data-dealership--schedule-editor-open-value='true']\",\n ) !== null\n );\n }\n\n startTimer() {\n this.stopTimer();\n this.timer = setInterval(() => this.tick(), this.intervalValue);\n }\n\n stopTimer() {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"dealership--lead-provider\"\nexport default class extends Controller {\n connect() {\n $(this.element).find(\"img\").on(\"load\", function () {\n const o = $(this);\n const [h, w] = [o.height(), o.width()];\n // because it looked a little large for my taste\n if (o[0].src.match(/subaru/)) {\n o.css({ height: \"90px\" });\n o.css({ padding: \"5px 0\" });\n }\n if (w > 150) {\n const r = w / 150;\n const nh = Math.floor(h / r);\n o.css({ width: \"150px\" });\n o.css({ height: nh + \"px\" });\n const padding = (100 - nh) / 2;\n const top = Math.floor(padding);\n const bottom = 100 - nh - top;\n return o.css({ \"padding-top\": top, \"padding-bottom\": bottom });\n }\n });\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"dealership--lead-provider-form\"\nexport default class extends Controller {\n connect() {\n const $form = $(this.element);\n this.displayDetailFieldsForProvider = this.displayDetailFieldsForProvider.bind(this);\n this.shouldShowCredentialFields = this.shouldShowCredentialFields.bind(this);\n this.$form = $form;\n this.$externalIdContainer = this.$form.find(\"#dlp_external_id_container\");\n this.$credentialsContainer = this.$form.find(\"#dlp_credentials_container\");\n this.$leadProviderSelect = this.$form.find(\"#dealership_lead_provider_lead_provider_id\");\n\n this.providerName = this.$leadProviderSelect.find(\"option:selected\").html();\n this.isDealerSocket = this.$leadProviderSelect.find(\"option:selected\").data(\"credential-fields\");\n\n this.displayDetailFieldsForProvider();\n\n this.$form.on(\"submit\", e => {\n if (this.shouldShowCredentialFields()) {\n return this.$externalIdContainer.find(\"input\").remove();\n } else {\n return this.$credentialsContainer.find(\"input\").remove();\n }\n });\n\n this.$leadProviderSelect.on(\"change\", event => {\n this.providerName = event.target.options[event.target.selectedIndex].label;\n this.isDealerSocket = $(event.target.options[event.target.selectedIndex]).data(\"credential-fields\");\n return this.displayDetailFieldsForProvider(true);\n });\n }\n\n displayDetailFieldsForProvider (clear) {\n if (clear == null) { clear = false; }\n if (this.shouldShowCredentialFields()) { return this.showCredentialFields(clear); } else { return this.showExternalIDField(clear); }\n }\n\n showExternalIDField (clear) {\n if (clear == null) { clear = false; }\n if (clear === true) { this.$externalIdContainer.find(\"input\").val(\"\"); }\n this.$credentialsContainer.hide();\n return this.$externalIdContainer.show();\n }\n\n showCredentialFields (clear) {\n if (clear == null) { clear = false; }\n if (clear === true) { this.$credentialsContainer.find(\"input\").val(\"\"); }\n this.$externalIdContainer.hide();\n return this.$credentialsContainer.show();\n }\n\n shouldShowCredentialFields () {\n return this.isDealerSocket;\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"dealership--merge-timeframe\"\n// Guards the \"Lead Merge Timeframe\" box in dealership Configurations, which\n// says how stale an Up Sheet may be before inbound leads stop merging into it.\n//\n// Blank and 0 both mean \"no restriction\" \u2014 Dealership#lead_merge_timeframe?\n// reads them the same way, so the form has to accept both. Anything else must\n// be a whole number of days no larger than Dealership::MAX_DELAY_DAYS.\nexport default class extends Controller {\n static targets = [\"input\", \"message\"];\n static values = { max: Number };\n\n connect() {\n this.validate();\n }\n\n validate() {\n const message = this.errorFor(this.inputTarget.value);\n\n this.inputTarget.setCustomValidity(message || \"\");\n this.showMessage(message);\n }\n\n errorFor(rawValue) {\n const value = String(rawValue || \"\").trim();\n if (value === \"\") return null;\n\n if (!/^\\d+$/.test(value)) {\n return \"Enter a whole number of days (0 or more), or leave this blank for no restriction.\";\n }\n\n const max = this.maxDays();\n if (max !== null && Number(value) > max) {\n return `Enter ${max} days or fewer.`;\n }\n\n return null;\n }\n\n maxDays() {\n if (this.hasMaxValue && this.maxValue > 0) return this.maxValue;\n\n const attribute = Number(this.inputTarget.getAttribute(\"max\"));\n return Number.isFinite(attribute) && attribute > 0 ? attribute : null;\n }\n\n showMessage(message) {\n if (!this.hasMessageTarget) return;\n\n this.messageTarget.textContent = message || \"\";\n this.messageTarget.hidden = !message;\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"dealership--routing-composer\"\n//\n// Drives the \"Add routing rule\" composer on the Lead source routing tab. The\n// visible ar_select controls (`_composer[source_ids][]`, `_composer[user_ids][]`\n// and the two `_composer[fallback][...]` selects) are ignored server-side; this\n// controller reads them and materializes the real\n// SourceRoutingRulesController#batch_update wire format into the hiddenFields\n// container: for every chosen source it writes a\n// `source_routing_rules[][]` \"\" sentinel plus one input per chosen\n// rep, and a `rule_fallbacks[][...]` pair \u2014 so each source becomes its\n// own rule sharing the same rep pool and the same fallback.\n//\n// It syncs on every change and again on submit, and keeps the submit button\n// disabled until at least one source and one rep are selected.\nexport default class extends Controller {\n static targets = [\n \"sourceSelect\",\n \"repSelect\",\n \"fallbackSelect\",\n \"fallbackUserSelect\",\n \"hiddenFields\",\n \"submit\",\n ];\n\n connect() {\n this.sync();\n }\n\n sync() {\n const sourceIds = this.hasSourceSelectTarget\n ? this.#selectedValues(this.sourceSelectTarget)\n : [];\n const repIds = this.hasRepSelectTarget\n ? this.#selectedValues(this.repSelectTarget)\n : [];\n\n const strategy = this.hasFallbackSelectTarget\n ? this.fallbackSelectTarget.value\n : \"\";\n const fallbackUserId = this.hasFallbackUserSelectTarget\n ? this.fallbackUserSelectTarget.value\n : \"\";\n\n this.hiddenFieldsTarget.innerHTML = \"\";\n sourceIds.forEach((sourceId) => {\n const name = `source_routing_rules[${sourceId}][]`;\n this.#appendHidden(name, \"\");\n repIds.forEach((repId) => this.#appendHidden(name, repId));\n\n if (strategy) {\n this.#appendHidden(`rule_fallbacks[${sourceId}][strategy]`, strategy);\n this.#appendHidden(\n `rule_fallbacks[${sourceId}][user_id]`,\n strategy === \"nominated\" ? fallbackUserId : \"\",\n );\n }\n });\n\n if (this.hasSubmitTarget) {\n this.submitTarget.disabled = !(sourceIds.length > 0 && repIds.length > 0);\n }\n }\n\n #selectedValues(select) {\n return Array.from(select.selectedOptions)\n .map((option) => option.value)\n .filter((value) => value !== \"\");\n }\n\n #appendHidden(name, value) {\n const input = document.createElement(\"input\");\n input.type = \"hidden\";\n input.name = name;\n input.value = value;\n this.hiddenFieldsTarget.appendChild(input);\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"dealership--rule-fallback\"\n//\n// The per-rule \"if none of them are available\" controls on the Lead source\n// routing tab, on both an existing rule's card and the \"Add routing rule\"\n// composer. Reveals the person picker only while the \"Assign to a specific\n// person\" strategy is selected, and blocks submit with an inline error when\n// that strategy is chosen without a person \u2014 the server rejects the same\n// combination, but only as a flash message once the round trip is over.\nexport default class extends Controller {\n static targets = [\"strategy\", \"user\", \"nominatedUser\", \"error\"];\n\n connect() {\n this.toggle();\n }\n\n toggle() {\n const nominated = this.nominatedSelected();\n if (this.hasNominatedUserTarget) {\n this.nominatedUserTarget.style.display = nominated ? \"\" : \"none\";\n }\n if (!nominated || this.selectedUserId()) {\n this.hideError();\n }\n }\n\n validate(event) {\n if (this.nominatedSelected() && !this.selectedUserId()) {\n event.preventDefault();\n this.showError();\n }\n }\n\n nominatedSelected() {\n return this.hasStrategyTarget && this.strategyTarget.value === \"nominated\";\n }\n\n selectedUserId() {\n return this.hasUserTarget ? this.userTarget.value : \"\";\n }\n\n showError() {\n if (this.hasErrorTarget) this.errorTarget.hidden = false;\n }\n\n hideError() {\n if (this.hasErrorTarget) this.errorTarget.hidden = true;\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"dealership--schedule-editor\"\n//\n// Owns two jobs for a single rep card:\n// 1. Expand/collapse of the editor panel (the Edit/Done button + chevron).\n// 2. Mirroring the visible schedule editor (day chips, availability/hours\n// segments, time pickers) into the canonical hidden rep_schedule_hours[...]\n// inputs that actually submit.\n//\n// The controller lives INSIDE the rep row's turbo frame, so replacing the frame\n// after a save resets all of this state naturally.\nconst CHIP_ON = [\"bg-primary-900\", \"text-white\", \"border-primary-900\"];\nconst CHIP_OFF = [\"bg-white\", \"text-primary-400\"];\n\nconst FULL_DAY_START = \"12:00 AM\";\nconst FULL_DAY_FINISH = \"24:00\";\nconst DEFAULT_START = \"9:00 AM\";\nconst DEFAULT_FINISH = \"6:00 PM\";\n\nexport default class extends Controller {\n static targets = [\n \"panel\",\n \"expandButton\",\n \"chevron\",\n \"editLabel\",\n \"dayChip\",\n \"availabilityInput\",\n \"scopeInput\",\n \"hoursSection\",\n \"sharedInputs\",\n \"sharedStart\",\n \"sharedFinish\",\n \"customSection\",\n \"customRow\",\n \"customStart\",\n \"customFinish\",\n \"customEmptyHint\",\n \"availHint\",\n \"enableField\",\n \"startField\",\n \"finishField\",\n ];\n\n static values = {\n open: { type: Boolean, default: false },\n availability: String,\n scope: String,\n };\n\n connect() {\n this.#renderOpen();\n this.#refresh();\n }\n\n toggleExpand() {\n this.openValue = !this.openValue;\n this.#renderOpen();\n }\n\n toggleDay(event) {\n const chip = event.currentTarget;\n const on = chip.getAttribute(\"aria-pressed\") !== \"true\";\n this.#setChip(chip, on);\n this.#syncHidden();\n this.#refresh();\n }\n\n availabilityChanged() {\n this.#syncHidden();\n this.#refresh();\n }\n\n scopeChanged() {\n this.#syncHidden();\n this.#refresh();\n }\n\n syncFromInputs() {\n this.#syncHidden();\n }\n\n // ---- rendering ----\n\n #renderOpen() {\n if (this.hasPanelTarget) {\n this.panelTarget.hidden = !this.openValue;\n }\n // The chevron and the Edit/Done label say the state visually; aria-expanded\n // is the only thing that says it to a screen reader.\n if (this.hasExpandButtonTarget) {\n this.expandButtonTarget.setAttribute(\"aria-expanded\", String(this.openValue));\n }\n if (this.hasChevronTarget) {\n this.chevronTarget.classList.toggle(\"ri-arrow-up-s-line\", this.openValue);\n this.chevronTarget.classList.toggle(\"ri-arrow-down-s-line\", !this.openValue);\n }\n if (this.hasEditLabelTarget) {\n this.editLabelTarget.textContent = this.openValue ? \"Done\" : \"Edit\";\n }\n }\n\n #refresh() {\n const availability = this.#availability();\n const scope = this.#scope();\n const specific = availability === \"specific_hours\";\n\n if (this.hasHoursSectionTarget) {\n this.hoursSectionTarget.hidden = !specific;\n }\n if (this.hasSharedInputsTarget) {\n this.sharedInputsTarget.hidden = !(specific && scope === \"shared\");\n }\n if (this.hasCustomSectionTarget) {\n this.customSectionTarget.hidden = !(specific && scope === \"custom\");\n }\n\n let anyEnabled = false;\n this.customRowTargets.forEach((row) => {\n const on = this.#chipFor(row.dataset.weekday)?.getAttribute(\"aria-pressed\") === \"true\";\n row.hidden = !on;\n if (on) {\n anyEnabled = true;\n }\n });\n if (this.hasCustomEmptyHintTarget) {\n this.customEmptyHintTarget.hidden = anyEnabled;\n }\n\n if (this.hasAvailHintTarget) {\n this.availHintTarget.textContent = availability === \"full_days\"\n ? \"Receives leads any time on the selected days.\"\n : \"Only receives leads during the hours below.\";\n }\n }\n\n #setChip(chip, on) {\n chip.setAttribute(\"aria-pressed\", on ? \"true\" : \"false\");\n if (on) {\n chip.classList.remove(...CHIP_OFF);\n chip.classList.add(...CHIP_ON);\n } else {\n chip.classList.remove(...CHIP_ON);\n chip.classList.add(...CHIP_OFF);\n }\n }\n\n // ---- sync to canonical hidden fields ----\n\n #syncHidden() {\n const availability = this.#availability();\n const scope = this.#scope();\n\n this.dayChipTargets.forEach((chip) => {\n const weekday = chip.dataset.weekday;\n const enabled = chip.getAttribute(\"aria-pressed\") === \"true\";\n const enableField = this.#fieldFor(this.enableFieldTargets, weekday);\n const startField = this.#fieldFor(this.startFieldTargets, weekday);\n const finishField = this.#fieldFor(this.finishFieldTargets, weekday);\n if (!enableField || !startField || !finishField) {\n return;\n }\n\n enableField.value = enabled ? \"1\" : \"0\";\n\n let start;\n let finish;\n if (availability === \"full_days\") {\n start = FULL_DAY_START;\n finish = FULL_DAY_FINISH;\n } else if (scope === \"shared\") {\n start = this.#value(this.hasSharedStartTarget && this.sharedStartTarget, DEFAULT_START);\n finish = this.#value(this.hasSharedFinishTarget && this.sharedFinishTarget, DEFAULT_FINISH);\n } else {\n start = this.#value(this.#fieldFor(this.customStartTargets, weekday), DEFAULT_START);\n finish = this.#value(this.#fieldFor(this.customFinishTargets, weekday), DEFAULT_FINISH);\n }\n\n startField.value = start;\n finishField.value = finish;\n });\n }\n\n // ---- helpers ----\n\n #availability() {\n const checked = this.availabilityInputTargets.find((input) => input.checked);\n return checked ? checked.value : this.availabilityValue;\n }\n\n #scope() {\n const checked = this.scopeInputTargets.find((input) => input.checked);\n return checked ? checked.value : this.scopeValue;\n }\n\n #chipFor(weekday) {\n return this.dayChipTargets.find((chip) => chip.dataset.weekday === weekday);\n }\n\n #fieldFor(targets, weekday) {\n return targets.find((field) => field.dataset.weekday === weekday);\n }\n\n #value(input, fallback) {\n if (!input) {\n return fallback;\n }\n const value = input.value.trim();\n return value.length > 0 ? value : fallback;\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\nexport default class extends Controller {\n static targets = [\"select\", \"hiddenName\", \"taxGroupSelect\", \"hiddenTaxGroupName\", \"salespersonSelect\", \"hiddenSalespersonName\"];\n static values = { upsheetId: Number, quoteSheetId: Number };\n\n updateLenderName(event) {\n event.stopPropagation();\n\n if (!this.hasSelectTarget || !this.hasHiddenNameTarget) return;\n\n const selectedOption = this.selectTarget.options[this.selectTarget.selectedIndex];\n const lenderName = selectedOption.text;\n\n // Only set if a valid lender is selected (not the placeholder)\n if (this.selectTarget.value) {\n this.hiddenNameTarget.value = lenderName;\n } else {\n this.hiddenNameTarget.value = \"\";\n }\n }\n\n updateTaxGroupName(event) {\n event.stopPropagation();\n\n if (!this.hasTaxGroupSelectTarget || !this.hasHiddenTaxGroupNameTarget) return;\n\n const selectedOption = this.taxGroupSelectTarget.options[this.taxGroupSelectTarget.selectedIndex];\n const taxGroupName = selectedOption.text;\n\n // Only process if a valid tax group is selected (not the placeholder)\n if (this.taxGroupSelectTarget.value) {\n this.hiddenTaxGroupNameTarget.value = taxGroupName;\n this.updateQuoteSheetTaxRate(selectedOption);\n } else {\n this.hiddenTaxGroupNameTarget.value = \"\";\n // If clearing selection, no action needed - tax rate remains unchanged\n }\n }\n\n async updateQuoteSheetTaxRate(selectedOption) {\n // Skip if we don't have the required IDs for the AJAX call\n if (!this.hasUpsheetIdValue || !this.upsheetIdValue) {\n return;\n }\n if (!this.hasQuoteSheetIdValue || !this.quoteSheetIdValue) {\n return;\n }\n\n const taxRate = selectedOption.dataset.taxRate;\n if (!taxRate && taxRate !== 0) {\n return;\n }\n\n try {\n const csrfToken = document.querySelector(\"meta[name=\\\"csrf-token\\\"]\")?.content;\n const url = `/upsheets/${this.upsheetIdValue}/quote_sheets/${this.quoteSheetIdValue}/update_tax_rate`;\n\n // Gather current form values for recalculation\n const form = document.getElementById(\"quote_form\");\n const quoteParams = form ? this.getFormValues(form) : {};\n\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CSRF-Token\": csrfToken,\n Accept: \"application/json\",\n },\n body: JSON.stringify({\n sales_tax_rate: taxRate,\n quote: quoteParams,\n quote_id: quoteParams.id,\n }),\n });\n\n if (response.ok) {\n const data = await response.json();\n // Update DOM with recalculated values - no page reload needed\n this.updateCalculatedValues(data);\n } else {\n console.error(\"[DealertrackSelector] Failed to update tax rate:\", response.status);\n }\n } catch (error) {\n console.error(\"[DealertrackSelector] Error updating tax rate:\", error);\n }\n }\n\n getFormValues(form) {\n const formData = new FormData(form);\n const values = {};\n\n for (const [key, value] of formData.entries()) {\n // Convert quote[field_name] to field_name\n const match = key.match(/^quote\\[(.+)\\]$/);\n if (match) {\n values[match[1]] = value;\n }\n }\n\n return values;\n }\n\n updateCalculatedValues(data) {\n // Update tax rate display\n const taxRateEl = document.getElementById(\"quote_tax_rate\");\n if (taxRateEl && data.sales_tax_rate !== undefined) {\n taxRateEl.textContent = data.sales_tax_rate;\n }\n\n // Update total taxes\n const taxesEl = document.getElementById(\"quote_taxes\");\n if (taxesEl && data.total_taxes !== undefined) {\n taxesEl.textContent = this.formatCurrency(data.total_taxes);\n }\n\n // Update amount financed\n const financedEl = document.getElementById(\"quote_amount_financed\");\n if (financedEl && data.amount_financed !== undefined) {\n financedEl.textContent = this.formatCurrency(data.amount_financed);\n }\n\n // Update monthly payment input\n const monthlyPaymentInput = document.querySelector(\"input[name=\\\"quote[monthly_payment]\\\"]\");\n if (monthlyPaymentInput && data.monthly_payment !== undefined) {\n monthlyPaymentInput.value = this.formatCurrency(data.monthly_payment);\n }\n\n // Update COD\n const codEl = document.getElementById(\"quote_cod\");\n if (codEl && data.cod !== undefined) {\n codEl.textContent = this.formatCurrency(data.cod);\n }\n }\n\n formatCurrency(value) {\n if (value === null || value === undefined) return \"$0.00\";\n const num = typeof value === \"string\" ? parseFloat(value) : value;\n return new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n }).format(num);\n }\n\n updateSalespersonName(event) {\n event.stopPropagation();\n\n if (!this.hasSalespersonSelectTarget || !this.hasHiddenSalespersonNameTarget) return;\n\n const selectedOption = this.salespersonSelectTarget.options[this.salespersonSelectTarget.selectedIndex];\n const salespersonName = selectedOption.text;\n\n // Only set if a valid salesperson is selected (not the placeholder)\n if (this.salespersonSelectTarget.value) {\n this.hiddenSalespersonNameTarget.value = salespersonName;\n } else {\n this.hiddenSalespersonNameTarget.value = \"\";\n }\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\nexport default class extends Controller {\n static targets = [\"modal\", \"name\", \"form\", \"submitButton\", \"cancelButton\", \"buttonText\", \"buttonLoading\"];\n\n connect() {\n // Listen for successful Turbo stream response to close modal\n this.boundHandleTurboSubmitEnd = this.handleTurboSubmitEnd.bind(this);\n document.addEventListener(\"turbo:submit-end\", this.boundHandleTurboSubmitEnd);\n }\n\n disconnect() {\n document.removeEventListener(\"turbo:submit-end\", this.boundHandleTurboSubmitEnd);\n }\n\n open({ params: { deletePath, vehicleName } }) {\n this.nameTarget.textContent = vehicleName;\n this.formTarget.action = deletePath;\n\n // Reset button state\n this.submitButtonTarget.disabled = false;\n this.cancelButtonTarget.disabled = false;\n this.buttonTextTarget.classList.remove(\"hidden\");\n this.buttonLoadingTarget.classList.add(\"hidden\");\n\n this.modalTarget.showModal();\n }\n\n close() {\n this.modalTarget.close();\n }\n\n closeOnBackgroundClick(event) {\n if (event.target === this.modalTarget) {\n this.close();\n }\n }\n\n submit() {\n this.submitButtonTarget.disabled = true;\n this.cancelButtonTarget.disabled = true;\n this.buttonTextTarget.classList.add(\"hidden\");\n this.buttonLoadingTarget.classList.remove(\"hidden\");\n }\n\n handleTurboSubmitEnd(event) {\n // Only handle events from our form\n if (event.target !== this.formTarget) return;\n\n // A refused delete (a sold deal) answers with a turbo stream that puts the\n // reason in the page flash, so it closes like a success. Any other failure\n // keeps the modal open with its buttons back, so the rep sees it did not go.\n const contentType = event.detail.fetchResponse?.contentType || \"\";\n if (event.detail.success || contentType.startsWith(\"text/vnd.turbo-stream.html\")) {\n this.close();\n } else {\n this.submitButtonTarget.disabled = false;\n this.cancelButtonTarget.disabled = false;\n this.buttonTextTarget.classList.remove(\"hidden\");\n this.buttonLoadingTarget.classList.add(\"hidden\");\n }\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"dms-fee-filter\"\n// Client-side filtering and pagination for the synced DMS fee lists in settings\n// (Dealertrack fee tables, PBS fee setups). PBS has no recordType/taxable filters.\nexport default class extends Controller {\n static targets = [\n \"row\",\n \"count\",\n \"recordType\",\n \"taxable\",\n \"mapped\",\n \"search\",\n \"pagination\",\n \"prevBtn\",\n \"nextBtn\",\n \"pageInfo\",\n \"perPage\",\n ];\n\n static values = { perPage: { type: Number, default: 5 } };\n\n connect() {\n this.currentPage = 1;\n this.applyFilters();\n }\n\n filter() {\n this.currentPage = 1;\n this.applyFilters();\n }\n\n reset() {\n if (this.hasRecordTypeTarget) this.recordTypeTarget.value = \"\";\n if (this.hasTaxableTarget) this.taxableTarget.value = \"\";\n if (this.hasMappedTarget) this.mappedTarget.value = \"\";\n if (this.hasSearchTarget) this.searchTarget.value = \"\";\n this.currentPage = 1;\n this.applyFilters();\n }\n\n prevPage() {\n if (this.currentPage > 1) {\n this.currentPage--;\n this.applyFilters();\n }\n }\n\n nextPage() {\n if (this.currentPage < this.totalPages) {\n this.currentPage++;\n this.applyFilters();\n }\n }\n\n changePerPage() {\n const val = this.perPageTarget.value;\n this.perPageValue = val === \"all\" ? 0 : parseInt(val, 10);\n this.currentPage = 1;\n this.applyFilters();\n }\n\n applyFilters() {\n const recordType = this.hasRecordTypeTarget\n ? this.recordTypeTarget.value\n : \"\";\n const taxable = this.hasTaxableTarget ? this.taxableTarget.value : \"\";\n const mapped = this.hasMappedTarget ? this.mappedTarget.value : \"\";\n const search = this.hasSearchTarget\n ? this.searchTarget.value.toLowerCase().trim()\n : \"\";\n\n // First pass: determine which rows match the filters\n const matchingRows = [];\n let total = 0;\n\n this.rowTargets.forEach((row) => {\n total++;\n let show = true;\n\n if (recordType && row.dataset.recordType !== recordType) show = false;\n if (taxable === \"yes\" && row.dataset.taxable !== \"true\") show = false;\n if (taxable === \"no\" && row.dataset.taxable !== \"false\") show = false;\n if (mapped === \"yes\" && !row.dataset.mapped) show = false;\n if (mapped === \"no\" && row.dataset.mapped) show = false;\n\n if (search && show) {\n const text = (row.dataset.description || \"\").toLowerCase();\n if (!text.includes(search)) show = false;\n }\n\n if (show) {\n matchingRows.push(row);\n } else {\n row.style.display = \"none\";\n }\n });\n\n // Second pass: apply pagination to matching rows\n const perPage = this.perPageValue;\n const usePagination = perPage > 0;\n this.totalPages = usePagination\n ? Math.max(1, Math.ceil(matchingRows.length / perPage))\n : 1;\n\n if (this.currentPage > this.totalPages) {\n this.currentPage = this.totalPages;\n }\n\n const startIdx = usePagination ? (this.currentPage - 1) * perPage : 0;\n const endIdx = usePagination ? startIdx + perPage : matchingRows.length;\n\n matchingRows.forEach((row, idx) => {\n row.style.display = idx >= startIdx && idx < endIdx ? \"\" : \"none\";\n });\n\n // Update count\n if (this.hasCountTarget) {\n const visible = matchingRows.length;\n this.countTarget.textContent =\n visible === total ? `${total} fees` : `${visible} of ${total} fees`;\n }\n\n // Update pagination controls\n if (this.hasPaginationTarget) {\n this.paginationTarget.style.display =\n matchingRows.length > 0 ? \"\" : \"none\";\n }\n if (this.hasPrevBtnTarget) {\n this.prevBtnTarget.disabled = this.currentPage <= 1;\n }\n if (this.hasNextBtnTarget) {\n this.nextBtnTarget.disabled = this.currentPage >= this.totalPages;\n }\n if (this.hasPageInfoTarget) {\n if (usePagination) {\n this.pageInfoTarget.textContent = `Page ${this.currentPage} of ${this.totalPages}`;\n } else {\n this.pageInfoTarget.textContent = \"Showing all\";\n }\n }\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"dms-fee-sync\"\n// Triggers manual sync of DMS fees (Dealertrack fee tables, PBS fee setups) via a background job.\n// The job re-renders the fee section via Turbo Stream broadcast when it finishes, including on failure.\nexport default class extends Controller {\n static values = { url: String };\n\n async sync(event) {\n const button = event.currentTarget;\n const originalText = button.textContent;\n\n if (!this.urlValue) {\n alert(\"Sync failed: sync URL is missing\");\n return;\n }\n\n try {\n button.disabled = true;\n button.textContent = \"Syncing...\";\n\n const response = await fetch(this.urlValue, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CSRF-Token\": this.csrfToken,\n },\n });\n\n const data = await response.json();\n\n if (response.ok) {\n button.textContent = \"Sync queued \u2014 waiting for update...\";\n } else {\n alert(`Sync failed: ${data.error || \"Unknown error\"}`);\n button.textContent = originalText;\n button.disabled = false;\n }\n } catch (error) {\n alert(`Sync failed: ${error.message}`);\n button.textContent = originalText;\n button.disabled = false;\n }\n }\n\n get csrfToken() {\n return document.querySelector(\"meta[name=\\\"csrf-token\\\"]\")?.content || \"\";\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"dms-push\"\n// Pushes a loan quote to the dealership's DMS (Dealertrack or PBS) and polls the push status.\n// Every error and warning the server returns is shown to the dealer as is.\nexport default class extends Controller {\n static targets = [\"button\", \"status\"];\n\n static values = {\n url: String,\n statusUrl: String,\n vendor: String,\n // name of the select whose value is sent as salesperson_id; omitted when the DMS takes none\n salespersonField: String,\n };\n\n connect() {\n this.readyLabel = this.buttonTarget.innerHTML;\n this.loadStatus();\n }\n\n disconnect() {\n this.stopPolling();\n }\n\n // Shows the quote's latest push without toasts: on connect (also after every\n // quote_frame re-render) and after a push request whose response was lost.\n async loadStatus() {\n if (!this.hasStatusUrlValue) {\n console.warn(\"No status URL configured\");\n return;\n }\n\n this.quiet = true;\n try {\n this.updateUI(await this.fetchStatus());\n } catch (error) {\n console.error(\"Error checking status:\", error);\n this.showReady();\n } finally {\n this.quiet = false;\n }\n }\n\n async push(event) {\n event.preventDefault();\n\n if (!confirm(`Push this quote to ${this.vendorValue}?`)) {\n return;\n }\n\n if (!this.urlValue) {\n console.error(\"URL value is empty or undefined!\");\n this.showToast(\"Push URL not configured\", \"error\");\n return;\n }\n\n this.setLoadingState();\n\n try {\n const response = await fetch(this.urlValue, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CSRF-Token\": this.getCsrfToken(),\n },\n body: JSON.stringify(this.pushParams()),\n });\n\n const data = await response.json();\n\n if (data.already_pushed) {\n this.showAlreadyPushed(data);\n } else if (response.ok && data.success) {\n this.startPolling(data.push_id);\n this.showPending();\n } else {\n this.handleError(data);\n }\n } catch (error) {\n console.error(`Error pushing to ${this.vendorValue}:`, error);\n this.handleError({ message: \"Network error. Please try again.\" });\n // The push may have been created before the response was lost: show it\n // (and poll it) instead of offering a second push.\n this.loadStatus();\n }\n }\n\n pushParams() {\n if (!this.hasSalespersonFieldValue) return {};\n\n const select = document.querySelector(\n `select[name=\"${this.salespersonFieldValue}\"]`,\n );\n return { salesperson_id: select ? select.value : null };\n }\n\n async fetchStatus(pushId = null) {\n const url = pushId\n ? `${this.statusUrlValue}?push_id=${pushId}`\n : this.statusUrlValue;\n\n const response = await fetch(url, {\n headers: {\n Accept: \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n\n return await response.json();\n }\n\n // One request at a time; a response that arrives after polling stopped (or\n // restarted) is dropped, so it cannot repeat a toast or undo a final state.\n startPolling(pushId) {\n this.stopPolling();\n const run = (this.pollRun = {});\n\n const poll = async () => {\n try {\n const status = await this.fetchStatus(pushId);\n if (this.pollRun !== run) return;\n\n this.updateUIForStatus(status);\n if (status.status === \"success\" || status.status === \"failed\") {\n this.stopPolling();\n return;\n }\n } catch (error) {\n console.error(\"Polling error:\", error);\n }\n if (this.pollRun === run) this.pollTimer = setTimeout(poll, 2000);\n };\n\n this.pollTimer = setTimeout(poll, 2000);\n this.pollTimeout = setTimeout(() => {\n this.stopPolling();\n this.showToast(\"Push is taking longer than expected. Please refresh the page to check status.\", \"error\");\n }, 300000);\n }\n\n stopPolling() {\n this.pollRun = null;\n clearTimeout(this.pollTimer);\n clearTimeout(this.pollTimeout);\n }\n\n updateUI(status) {\n if (!status.has_been_pushed) {\n this.showReady();\n return;\n }\n\n this.updateUIForStatus(status);\n if (status.status === \"pending\" || status.status === \"processing\") {\n this.startPolling(status.push_id);\n }\n }\n\n updateUIForStatus(status) {\n switch (status.status) {\n case \"pending\":\n this.showPending();\n break;\n case \"processing\":\n this.showProcessing();\n break;\n case \"success\":\n this.showSuccess(status);\n break;\n case \"failed\":\n this.showFailure(status);\n break;\n }\n }\n\n showReady() {\n this.setNormalState();\n this.clearStatus();\n }\n\n showPending() {\n this.buttonTarget.disabled = true;\n this.buttonTarget.innerHTML = \" Queued\";\n\n this.setStatusHtml(`\n \n Waiting to process...\n \n `);\n }\n\n showProcessing() {\n this.setLoadingState();\n\n this.setStatusHtml(`\n \n Pushing to ${this.vendorValue}...\n \n `);\n }\n\n showSuccess(status) {\n const stockNumber = this.showPushed(status);\n\n if (!this.quiet) {\n this.showToast(this.withWarnings(`Successfully pushed to ${this.vendorValue}! Stock: ${stockNumber} (Deal ID: ${status.deal_key})`, status.warnings), \"success\");\n }\n }\n\n showAlreadyPushed(result) {\n const stockNumber = this.showPushed(result);\n this.showToast(`Already pushed to ${this.vendorValue}. Stock: ${stockNumber} (Deal ID: ${result.deal_key})`, \"info\");\n }\n\n // Button and status line for a pushed deal; returns the stock number for the toast.\n showPushed(result) {\n this.buttonTarget.disabled = true;\n this.buttonTarget.innerHTML = \" Already Pushed\";\n this.buttonTarget.classList.remove(\"btn-primary\", \"btn-secondary\");\n this.buttonTarget.classList.add(\"btn-success\");\n\n const stockNumber = result.stock_number || \"N/A\";\n\n this.setStatusHtml(`\n \n \n Stock: ${this.escapeHtml(stockNumber)} (Deal ID: ${this.escapeHtml(result.deal_key)})\n ${this.warningsHtml(result.warnings)}\n `);\n\n return stockNumber;\n }\n\n showFailure(status) {\n this.buttonTarget.disabled = false;\n this.buttonTarget.innerHTML = \" Retry Push\";\n this.buttonTarget.classList.remove(\"btn-primary\", \"btn-secondary\");\n this.buttonTarget.classList.add(\"btn-warning\");\n\n this.setStatusHtml(`\n \n \n Push failed: ${this.escapeHtml(status.message)}\n ${this.warningsHtml(status.warnings)}\n `);\n\n if (!this.quiet) {\n this.showToast(this.withWarnings(`Push failed: ${status.message}`, status.warnings), \"error\");\n }\n }\n\n warningsHtml(warnings) {\n if (!warnings || warnings.length === 0) return \"\";\n\n return ` ${this.escapeHtml(warnings.join(\"; \"))}`;\n }\n\n withWarnings(message, warnings) {\n if (!warnings || warnings.length === 0) return message;\n\n return `${message}\\n\\nWarnings:\\n${warnings.join(\"\\n\")}`;\n }\n\n handleError(data) {\n this.setNormalState();\n this.showToast(this.errorMessage(data), \"error\");\n }\n\n errorMessage(data) {\n const message = data.message || `Failed to push deal to ${this.vendorValue}`;\n const errors = data.errors || [];\n\n return errors.length > 0 ? `${message}\\n\\n${errors.join(\"\\n\")}` : message;\n }\n\n setLoadingState() {\n this.buttonTarget.disabled = true;\n this.buttonTarget.innerHTML = \" Pushing...\";\n }\n\n setNormalState() {\n this.buttonTarget.disabled = false;\n this.buttonTarget.innerHTML = this.readyLabel;\n }\n\n setStatusHtml(html) {\n if (this.hasStatusTarget) {\n this.statusTarget.innerHTML = html;\n }\n }\n\n clearStatus() {\n if (this.hasStatusTarget) {\n this.statusTarget.innerHTML = \"\";\n }\n }\n\n getCsrfToken() {\n const meta = document.querySelector(\"meta[name=\\\"csrf-token\\\"]\");\n return meta ? meta.getAttribute(\"content\") : \"\";\n }\n\n // Safe in element content and in quoted attribute values.\n escapeHtml(text) {\n if (!text) return \"\";\n const div = document.createElement(\"div\");\n div.textContent = text;\n return div.innerHTML.replace(/\"/g, \""\").replace(/'/g, \"'\");\n }\n\n showToast(message, type = \"success\") {\n if (window.Toastify) {\n try {\n const toast = window.Toastify({\n text: message,\n duration: type === \"error\" ? 6000 : 4000,\n gravity: \"top\",\n position: \"right\",\n className: type === \"error\" ? \"toast-error\" : \"toast-success\",\n stopOnFocus: true,\n offset: {\n y: 150,\n },\n style: {\n whiteSpace: \"pre-line\",\n },\n });\n toast.showToast();\n } catch (error) {\n console.error(\"Toast error:\", error);\n alert(`${type.toUpperCase()}: ${message}`);\n }\n } else {\n console.error(\"Toastify not available, using alert:\", message);\n alert(`${type.toUpperCase()}: ${message}`);\n }\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport { capturePosthogEvent } from \"../utils/posthog_capture\";\n\nexport default class extends Controller {\n static targets = [\"select\", \"submit\"];\n static values = { upsheetId: Number };\n\n connect() {\n this.dialog = this.element.closest(\"dialog\");\n if (!this.dialog) return;\n\n // The modal is opened externally via dialog.showModal(), which only toggles\n // the `open` attribute. Observe it so we capture one funnel event per open.\n this.observer = new MutationObserver(() => {\n if (this.dialog.open) {\n capturePosthogEvent(\"custom_document_generate_modal_opened\", {\n upsheet_id: this.hasUpsheetIdValue ? this.upsheetIdValue : undefined,\n });\n }\n });\n this.observer.observe(this.dialog, { attributes: true, attributeFilter: [\"open\"] });\n }\n\n disconnect() {\n this.observer?.disconnect();\n }\n\n enableSubmit() {\n this.submitTarget.disabled = !this.selectTarget.value;\n }\n\n submit() {\n this.submitTarget.disabled = true;\n this.submitTarget.value = \"Generating\\u2026\";\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"editor--popover\"\nexport default class extends Controller {\n static targets = [\n \"template\",\n ];\n\n insert({ params }) {\n const target = this.templateTargets.find(template => template.dataset.templateKey === params.templateKey.toString());\n const editor = CKEDITOR.instances.email_body;\n\n try {\n // Focus the editor first so CKEditor has a valid selection range.\n // Without this, opening the popover can leave the selection null and\n // insertHtml -> splitElement throws \"getParents, r is null\".\n editor.focus();\n editor.insertHtml(target.innerHTML);\n } catch (e) {\n // Fall back to appending at the end of the editor body.\n try {\n const range = editor.createRange();\n range.moveToElementEditEnd(editor.editable());\n editor.getSelection().selectRanges([range]);\n editor.insertHtml(target.innerHTML);\n } catch (_) {\n // Give up silently \u2014 user can re-click into the editor and retry.\n }\n }\n this.cancel();\n }\n\n cancel() {\n this.element.innerHTML = \"\";\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport fetch from \"@/utils/fetch\";\nimport confirm from \"@/utils/confirm\";\n\nexport default class extends Controller {\n static values = {\n url: String,\n };\n\n async delete() {\n if (!await confirm(\"Are you sure you want to delete this attachment?\")) {\n return;\n }\n\n fetch(this.urlValue, {\n method: \"DELETE\",\n })\n .then(() => {\n // remove the deleted attachment li from the list of attachments\n this.element.remove();\n }).catch(() => {\n alert(\"Sorry, the attachment could not be deleted.\");\n });\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"email--draft\"\nexport default class extends Controller {\n static values = {\n url: String,\n bodyId: String,\n };\n\n static targets = [\n \"modal\",\n \"goalSelect\",\n \"toneSelect\",\n \"userContext\",\n \"generateButton\",\n \"error\",\n \"spinner\",\n \"draftResult\",\n ];\n\n openModal() {\n this.errorTarget.classList.add(\"hidden\");\n this.errorTarget.textContent = \"\";\n this.modalTarget.classList.remove(\"hidden\");\n }\n\n closeModal() {\n this.modalTarget.classList.add(\"hidden\");\n this.#setLoading(false);\n }\n\n closeModalOnBackdrop(event) {\n if (event.target === this.modalTarget) {\n this.closeModal();\n }\n }\n\n async generate() {\n const goal = this.goalSelectTarget.value;\n const tone = this.toneSelectTarget.value;\n const userContext = this.userContextTarget.value.trim();\n\n this.#setLoading(true);\n this.errorTarget.classList.add(\"hidden\");\n\n const body = { goal, tone };\n if (userContext) body.user_context = userContext;\n\n try {\n const response = await fetch(this.urlValue, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"X-CSRF-Token\": document.querySelector(\"meta[name='csrf-token']\")?.content,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new Error(error.message || \"Failed to generate draft\");\n }\n\n // Cached draft still available\n if (response.status === 200) {\n const data = await response.json();\n this.draftResultTarget.dataset.draft = data.draft;\n this.closeModal();\n }\n // Job enqueued \u2014 keep loading state until Turbo Stream broadcast arrives\n } catch (error) {\n this.errorTarget.textContent = error.message;\n this.errorTarget.classList.remove(\"hidden\");\n this.#setLoading(false);\n }\n }\n\n draftResultTargetConnected(element) {\n const draft = element.dataset.draft;\n const suggestedSubject = element.dataset.suggestedSubject;\n const error = element.dataset.error;\n\n if (!draft && !error) return;\n\n if (error) {\n this.#setLoading(false);\n this.errorTarget.textContent = error;\n this.errorTarget.classList.remove(\"hidden\");\n return;\n }\n\n const editor = CKEDITOR.instances[this.bodyIdValue];\n if (editor) {\n editor.setData(draft);\n editor.focus();\n }\n\n if (suggestedSubject) {\n const subjectInput = this.element.querySelector(\"[data-email--editor-target='subject']\");\n if (subjectInput) {\n subjectInput.value = suggestedSubject;\n }\n }\n\n this.closeModal();\n }\n\n #setLoading(loading) {\n this.generateButtonTarget.disabled = loading;\n this.spinnerTarget.classList.toggle(\"hidden\", !loading);\n this.generateButtonTarget.querySelector(\"[data-label]\").textContent = loading\n ? \"Generating...\"\n : \"Generate\";\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport attachments from \"@/upsheets/attachments\";\nimport editorConfig from \"@/editor/config/toolbar\";\nimport { trackEvent } from \"@/utils/analytics\";\nimport { emailRegex } from \"@/utils/regex\";\n\nexport default class extends Controller {\n static targets = [\n \"body\",\n \"defaultEmailSubject\",\n \"spinner\",\n \"subject\",\n \"attachmentArea\",\n \"form\",\n \"autocomplete\",\n \"recipientCheckbox\",\n \"missingAddress\",\n \"missingAddressContainer\",\n ];\n\n connect () {\n const custom_config = {};\n custom_config.extraPlugins = CKEDITOR.config.extraPlugins + \",autosave,pastebase64\";\n custom_config.autosave = {\n delay: \"5\",\n saveOnDestroy: true,\n };\n\n CKEDITOR.replace(this.bodyTarget.id, { ...editorConfig, ...custom_config });\n this.#checkMissing();\n this.element.scrollIntoView(true);\n }\n\n /** @param {Event & { target: HTMLSelectElement, params: { path: String } }} */\n templateChanged ({ target: { value: id }, params: { path } }) {\n this.spinnerTarget.hidden = false;\n\n // Clean all fields when template is removed\n if (id === \"\") {\n this.#applyTemplate({\n message_template: {\n body: \"\",\n subject: \"\",\n },\n });\n\n return;\n }\n\n fetch(`${path}?message_template=${id}`)\n .then((response) => response.json())\n .then((data) => this.#applyTemplate(data));\n }\n\n // With the improved_tasks task picker, \"Send and Complete\" with nothing\n // ticked completes nothing, so it is tracked as a plain send.\n #trackedLabel () {\n if (!this.hasAutocompleteTarget) return \"Send\";\n if (this.autocompleteTarget.value !== \"true\") return \"Only Send\";\n\n const pickerBoxes = [...this.formTarget.querySelectorAll(\"input[name='complete_task_ids[]']\")];\n if (pickerBoxes.length > 0 && !pickerBoxes.some((box) => box.checked)) return \"Send\";\n\n return \"Send & Complete\";\n }\n\n #applyTemplate (data) {\n this.spinnerTarget.hidden = true;\n\n const { body } = data.message_template;\n this.subjectTarget.value = data.message_template.subject || this.defaultEmailSubjectTarget.value;\n\n const editor = this.#editorInstance;\n editor.setData(body);\n editor.focus();\n }\n\n show() {\n attachments.show();\n }\n\n cancel () {\n this.#destroyEditorInstance();\n // Previously the content was being removed with `this.element.remove()`\n // This made it so that there were whitespaces left inside the element which prevented made it so\n // that the CSS pseudo-class &:empty would not work, hence this workaround.\n this.element.parentElement.innerHTML = \"\";\n }\n\n submit (event) {\n if (!this.#formValid()) {\n event.preventDefault();\n return;\n }\n\n trackEvent({ category: \"Communication\", action: \"email\", label: this.#trackedLabel() });\n }\n\n submitLinkClick({ params: { autocomplete } }) {\n if (this.hasAutocompleteTarget) {\n this.autocompleteTarget.value = autocomplete;\n }\n\n this.formTarget.requestSubmit();\n }\n\n checkRecipient() {\n this.#checkMissing();\n }\n\n #destroyEditorInstance() {\n this.#editorInstance.destroy();\n }\n\n #formValid() {\n if (this.#editorInstance.getData() === \"\") {\n alert(\"You haven't entered any text for your email.\");\n this.#editorInstance.focus();\n return false;\n }\n\n if (!this.recipientCheckboxTargets.some((box) => box.checked)) {\n alert(\"You must select at least one recipient.\");\n return false;\n }\n\n if (this.recipientCheckboxTargets.some((box) => {\n if (!box.checked) return false;\n\n const email = this.missingAddressTargets.find((email) =>\n String(email.dataset.id) === String(box.value));\n if (!email) return false;\n\n if (email.value === \"\") {\n alert(`You must provide an email address for ${email.dataset.name}.`);\n email.focus();\n return true;\n }\n\n if (!email.value.match(emailRegex)) {\n alert(`You must provide a valid email address for ${email.dataset.name}.` +\n `\\n\\n${email.value} does not appear to be a valid address.`,\n );\n email.focus();\n return true;\n }\n\n return false;\n })) {\n return false;\n }\n\n // Remove all missing address targets that are hidden.\n // Each hidden target is implicitly not being sent an email\n // because its corresponding checkbox is not checked.\n this.missingAddressTargets.forEach((target) => {\n if (target.closest(\"div\").hidden) target.remove();\n });\n\n return true;\n }\n\n #checkMissing() {\n this.missingAddressContainerTarget.hidden = true;\n this.missingAddressTargets.forEach((address) => {\n address.closest(\"div\").hidden = true;\n });\n\n this.recipientCheckboxTargets.forEach((box) => {\n if (box.checked) {\n const addEmail = this.missingAddressTargets.find((address) =>\n String(address.dataset.id) === String(box.value));\n if (addEmail) {\n this.missingAddressContainerTarget.hidden = false;\n addEmail.closest(\"div\").hidden = !box.checked;\n }\n }\n });\n }\n\n get #editorInstance() {\n return CKEDITOR.instances[this.bodyTarget.id];\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\nexport default class extends Controller {\n static targets = [\"spammedLink\"];\n static values = { url: String, spammed: Boolean, emailId: Number };\n\n toggleSpam() {\n const spinner = `email_${this.emailIdValue}_spam`;\n UI.Spinners.show(spinner);\n const spammed = !this.spammedValue;\n this.spammedValue = spammed;\n return $.ajax({\n url: this.urlValue,\n type: \"PUT\",\n data: JSON.stringify({ marked_as_spam_at: spammed }),\n contentType: \"application/json\",\n }).then(() => {\n UI.Spinners.hide(spinner);\n this.element.classList.toggle(\"email-collapse\");\n if (spammed) {\n this.spammedLinkTarget.textContent = \"Unmark spam\";\n } else {\n this.spammedLinkTarget.textContent = \"Mark as spam\";\n }\n });\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport { trackEvent } from \"@/utils/analytics\";\nimport { Editor } from \"@/forms/editor\";\nimport fetch from \"@/utils/fetch\";\n\n// Connects to data-controller=\"email-campaign--compose\"\nexport default class extends Controller {\n #CK_EDITOR = \"ck_editor\";\n #BEE_PLUGIN = \"bee_plugin\";\n\n #ckeditor;\n #sourceEditor = this.#CK_EDITOR;\n\n static values = {\n total: Number,\n previewPath: String,\n };\n\n static targets = [\n \"bee\",\n \"ckeditor\",\n \"subject\",\n ];\n\n connect() {\n if (this.hasCkeditorTarget) {\n const textareaId = this.ckeditorTarget.querySelector(\"textarea\")?.id;\n\n if (textareaId && CKEDITOR.instances[textareaId]) {\n const existingInstance = CKEDITOR.instances[textareaId];\n this.#ckeditor = {\n instance: existingInstance,\n getContent: () => existingInstance.getData(),\n setContent: (content) => existingInstance.setData(content),\n };\n } else {\n this.#ckeditor = new Editor(this.ckeditorTarget);\n }\n }\n }\n\n disconnect() {\n if (this.hasCkeditorTarget) {\n const textareaId = this.ckeditorTarget.querySelector(\"textarea\")?.id;\n\n if (textareaId && CKEDITOR.instances[textareaId]) {\n CKEDITOR.instances[textareaId].destroy();\n }\n\n this.#ckeditor = null;\n }\n }\n\n selectTemplate({ target: { value } }) {\n // Template was set to nothing, clear all fields and reset to ckeditor\n if (value.trim().length === 0) {\n this.#loadTemplate({\n body: \"\",\n subject: \"\",\n marketing: false,\n });\n\n return;\n }\n\n fetch(this.previewPathValue.replace(\":id\", value))\n .then(response => {\n if (!response.ok) {\n throw new Error(`Template not found (${response.status})`);\n }\n return response.json();\n })\n .then(json => {\n this.#loadTemplate(json.data);\n })\n .catch(error => {\n console.error(\"Failed to load template:\", error);\n this.#loadTemplate({\n body: \"\",\n subject: \"\",\n marketing: false,\n });\n })\n ;\n }\n\n #loadTemplate({ body, marketing, subject }) {\n this.subjectTarget.value = subject;\n this.#sourceEditor = marketing ? this.#BEE_PLUGIN : this.#CK_EDITOR;\n\n if (marketing) {\n // bee\n this.beeTarget.srcdoc = body;\n } else {\n // ckeditor\n this.#ckeditor.setContent(body);\n }\n\n this.beeTarget.classList.toggle(\"hidden\", !marketing);\n this.ckeditorTarget.classList.toggle(\"hidden\", marketing);\n }\n\n submit({ detail: { fetchOptions: { body } } }) {\n const htmlBody = this.#sourceEditor === this.#CK_EDITOR ? this.#ckeditor.getContent() : this.beeTarget.srcdoc;\n\n body.set(\"email_campaign[body]\", htmlBody);\n body.set(\"email_campaign[source_editor]\", this.#sourceEditor);\n }\n\n afterSubmit({ detail: { fetchResponse: { response } } }) {\n if (response.ok) {\n trackEvent({\n category: \"Communication\",\n action: \"email\",\n label: \"marketing\",\n value: this.totalValue,\n });\n }\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"equity-report\"\n//\n// The two disclosures on the Equity Mining report.\n//\n// Comparable listings open one at a time: the panel is full-row width, so two\n// open at once pushes the row a reader is comparing against off the screen. The\n// legend is independent \u2014 it's page-level chrome, not per-row.\n//\n// This replaces a per-row
, which could not span the row: the toggle\n// sits in the Est. value column while the panel it opens is the full grid width.\nexport default class extends Controller {\n static targets = [\"legend\", \"panel\", \"toggle\", \"extraListing\", \"showAll\"];\n\n toggleLegend() {\n this.legendTarget.hidden = !this.legendTarget.hidden;\n }\n\n // `params: { row }` pairs a toggle with its panel \u2014 both carry the profile id.\n // Stimulus coerces a numeric param to a Number while dataset values stay\n // strings, so every comparison here goes through #rowId.\n toggleComparables({ params: { row } }) {\n const id = this.#rowId(row);\n const panel = this.#matching(this.panelTargets, id);\n const opening = panel.hidden;\n\n this.panelTargets.forEach((other) => {\n other.hidden = true;\n this.#setRowOpen(other, false);\n });\n this.toggleTargets.forEach((toggle) => this.#setToggleState(toggle, false));\n\n panel.hidden = !opening;\n this.#setRowOpen(panel, opening);\n this.#setToggleState(this.#matching(this.toggleTargets, id), opening);\n }\n\n // The panel lists a handful and keeps the rest back \u2014 a vehicle with forty\n // comparables would otherwise bury every row beneath it.\n showAllListings({ params: { row } }) {\n const id = this.#rowId(row);\n\n this.extraListingTargets\n .filter((listing) => listing.dataset.row === id)\n .forEach((listing) => { listing.hidden = false; });\n\n this.showAllTargets\n .filter((button) => button.dataset.row === id)\n .forEach((button) => { button.hidden = true; });\n }\n\n #rowId(row) {\n return String(row);\n }\n\n // The design tints the whole row while its listings are showing, so the panel\n // reads as belonging to the row above it rather than floating between two.\n // The tint matches :hover, which is what a row being worked already looks like.\n #setRowOpen(panel, open) {\n panel.closest(\".eq-row\")?.classList.toggle(\"eq-row--open\", open);\n }\n\n #matching(targets, id) {\n return targets.find((target) => target.dataset.row === id);\n }\n\n // Each toggle carries both labels \u2014 \"5 comparable listings\" and \"Hide 5\n // listings\" \u2014 and swaps which one is showing, so the count never has to be\n // rebuilt in JS and stays translatable in the template.\n #setToggleState(toggle, open) {\n if (!toggle) {\n return;\n }\n\n toggle.setAttribute(\"aria-expanded\", String(open));\n toggle.querySelector(\"[data-closed-label]\").hidden = open;\n toggle.querySelector(\"[data-open-label]\").hidden = !open;\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Sends the \"Send for Signature\" modal form via fetch so we can guarantee\n// the page reloads with the updated document state. Pure native
submit\n// inside an HTML5 proved unreliable in production \u2014 the dialog\n// modal teardown interacts oddly with the in-flight POST and the dealer is\n// left looking at the previous (pre-send) DOM even though the server already\n// updated `documents.esignature_status`.\nexport default class extends Controller {\n static targets = [\"form\", \"submit\"];\n\n async submit(event) {\n event.preventDefault();\n\n const form = this.formTarget;\n this.#disable();\n\n try {\n // Use JSON so the controller's format.json branch returns\n // {error: ...} for failures (which we surface to the dealer) instead\n // of doing a silent flash[:alert] redirect that the layout swallows.\n const response = await fetch(form.action, {\n method: form.method.toUpperCase() || \"POST\",\n body: new FormData(form),\n headers: { Accept: \"application/json\" },\n });\n\n if (response.ok) {\n // Success \u2014 but surface any soft-fail warning (e.g. SMS could not be\n // sent because the sender has no texting number) before reloading,\n // so the dealer doesn't think everything went through cleanly.\n const data = await response.json().catch(() => ({}));\n if (data.warning) window.alert(data.warning);\n window.location.reload();\n } else {\n const message = await this.#errorMessage(response);\n this.#enable();\n window.alert(message);\n }\n } catch (error) {\n this.#enable();\n window.alert(`Failed to send for signature: ${error.message}`);\n }\n }\n\n async #errorMessage(response) {\n try {\n const data = await response.json();\n return data.error || data.errors?.join?.(\" \") || `Server returned ${response.status}`;\n } catch (_e) {\n return `Server returned ${response.status}`;\n }\n }\n\n #disable() {\n if (this.hasSubmitTarget) {\n this.submitTarget.disabled = true;\n this.submitTarget.value = \"Sending\u2026\";\n }\n }\n\n #enable() {\n if (this.hasSubmitTarget) {\n this.submitTarget.disabled = false;\n this.submitTarget.value = \"Send for Signature\";\n }\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Generic show more / show less toggle between a collapsed and an expanded\n// block. A lazy-loading turbo frame inside the expanded block only fetches\n// once it first becomes visible, so collapsed entries cost nothing.\nexport default class extends Controller {\n static targets = [\"collapsed\", \"expanded\"];\n\n expand() {\n this.collapsedTarget.classList.add(\"hidden\");\n this.expandedTarget.classList.remove(\"hidden\");\n this.#loadLazyFrames();\n this.#moveFocus(this.expandedTarget);\n }\n\n collapse() {\n this.expandedTarget.classList.add(\"hidden\");\n this.collapsedTarget.classList.remove(\"hidden\");\n this.#moveFocus(this.collapsedTarget);\n }\n\n // Turbo's lazy loading rides on IntersectionObserver, which some embedded\n // webviews suppress; kick the frame explicitly so expansion never depends\n // on the observer firing. No-op once loaded \u2014 no refetch on re-expand.\n #loadLazyFrames() {\n this.expandedTarget\n .querySelectorAll(\"turbo-frame[loading=lazy]:not([complete])\")\n .forEach((frame) => frame.setAttribute(\"loading\", \"eager\"));\n }\n\n // Hiding the block that holds the activated button drops focus to ,\n // stranding keyboard users. preventScroll: a tall expanded body would\n // otherwise scroll the page to the control below it.\n #moveFocus(target) {\n target.querySelector(\"button, [href]\")?.focus({ preventScroll: true });\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Generic type-ahead row filter for tables/lists, with an optional group of rows\n// tucked behind a toggle.\n//\n// Markup:\n//
\n// \n// \n// \n// \u2026\n// \u2026\n// \n//
\n// \n//
\n//\n// Filter is case-insensitive substring match on `data-search-key`.\n//\n// Grouping is opt-in: mark the rows that belong to the group, give the group a\n// header row carrying the toggle, and render those rows `hidden` server-side so\n// the list doesn't paint expanded and then snap shut once this controller\n// connects.\n//\n//
\n// \u2026\n// \n// \n// \n// \n// \n// \u2026\n//
\n//\n// The storage key is optional: with one, the open/closed state survives a\n// turbo-frame reload via sessionStorage; without one the group starts in\n// whatever state the server rendered. A stored key the reader has never toggled\n// is not a preference, so it defers to the server too \u2014 which is how the eleads\n// roster manages to open its group for a dealership that has nobody in the\n// rotation yet, where a collapsed group would hide every row on the page.\n//\n// A query outranks the toggle \u2014 a matching group row shows whatever state the\n// group is in, `aria-expanded` reports what the reader can actually see rather\n// than the stored state, and the group header hides itself while a query matches\n// none of its rows. Collapsed rows still count as content, so a table whose rows\n// are *all* grouped doesn't read as \"no matches\" on an empty filter.\nexport default class extends Controller {\n static targets = [\"search\", \"row\", \"empty\", \"groupToggle\", \"groupHeader\"];\n static values = {\n groupExpanded: Boolean,\n groupStorageKey: String,\n };\n\n connect() {\n if (this.hasGroupStorageKeyValue) {\n this.groupExpandedValue = this.#storedExpansion();\n }\n this.filter();\n }\n\n toggleGroup() {\n this.groupExpandedValue = !this.groupExpandedValue;\n this.#storeExpansion(this.groupExpandedValue);\n this.filter();\n }\n\n filter() {\n const query = (this.hasSearchTarget ? this.searchTarget.value : \"\")\n .trim()\n .toLowerCase();\n\n let visible = 0;\n let groupMatches = 0;\n\n this.rowTargets.forEach((row) => {\n const key = (row.dataset.searchKey || \"\").toLowerCase();\n const match = query === \"\" || key.includes(query);\n const grouped = row.dataset.filterableTableGroup === \"true\";\n\n if (match && grouped) groupMatches += 1;\n\n const shown = match && (!grouped || this.groupExpandedValue || query !== \"\");\n row.hidden = !shown;\n if (shown) visible += 1;\n });\n\n this.#syncGroupChrome(query, groupMatches);\n\n if (this.hasEmptyTarget) {\n this.emptyTarget.hidden = visible !== 0 || groupMatches !== 0;\n }\n }\n\n #syncGroupChrome(query, groupMatches) {\n // A query reveals matching group rows whatever the toggle says, so report\n // the disclosure state the reader can actually see, not the stored one.\n const expanded = this.groupExpandedValue || (query !== \"\" && groupMatches > 0);\n\n this.groupToggleTargets.forEach((toggle) => {\n toggle.setAttribute(\"aria-expanded\", String(expanded));\n });\n\n this.groupHeaderTargets.forEach((header) => {\n header.hidden = query !== \"\" && groupMatches === 0;\n });\n }\n\n #storedExpansion() {\n try {\n const stored = window.sessionStorage.getItem(this.groupStorageKeyValue);\n\n return stored === null ? this.groupExpandedValue : stored === \"true\";\n } catch {\n // sessionStorage unavailable (private mode / disabled) \u2014 non-fatal.\n return this.groupExpandedValue;\n }\n }\n\n #storeExpansion(expanded) {\n if (!this.hasGroupStorageKeyValue) return;\n\n try {\n window.sessionStorage.setItem(this.groupStorageKeyValue, String(expanded));\n } catch {\n // See #storedExpansion.\n }\n }\n}\n", "/** Checks if value is string */\nfunction isString(str) {\n return typeof str === 'string' || str instanceof String;\n}\n\n/** Checks if value is object */\nfunction isObject(obj) {\n var _obj$constructor;\n return typeof obj === 'object' && obj != null && (obj == null || (_obj$constructor = obj.constructor) == null ? void 0 : _obj$constructor.name) === 'Object';\n}\nfunction pick(obj, keys) {\n if (Array.isArray(keys)) return pick(obj, (_, k) => keys.includes(k));\n return Object.entries(obj).reduce((acc, _ref) => {\n let [k, v] = _ref;\n if (keys(v, k)) acc[k] = v;\n return acc;\n }, {});\n}\n\n/** Direction */\nconst DIRECTION = {\n NONE: 'NONE',\n LEFT: 'LEFT',\n FORCE_LEFT: 'FORCE_LEFT',\n RIGHT: 'RIGHT',\n FORCE_RIGHT: 'FORCE_RIGHT'\n};\n\n/** Direction */\n\nfunction forceDirection(direction) {\n switch (direction) {\n case DIRECTION.LEFT:\n return DIRECTION.FORCE_LEFT;\n case DIRECTION.RIGHT:\n return DIRECTION.FORCE_RIGHT;\n default:\n return direction;\n }\n}\n\n/** Escapes regular expression control chars */\nfunction escapeRegExp(str) {\n return str.replace(/([.*+?^=!:${}()|[\\]/\\\\])/g, '\\\\$1');\n}\n\n// cloned from https://github.com/epoberezkin/fast-deep-equal with small changes\nfunction objectIncludes(b, a) {\n if (a === b) return true;\n const arrA = Array.isArray(a),\n arrB = Array.isArray(b);\n let i;\n if (arrA && arrB) {\n if (a.length != b.length) return false;\n for (i = 0; i < a.length; i++) if (!objectIncludes(a[i], b[i])) return false;\n return true;\n }\n if (arrA != arrB) return false;\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n const dateA = a instanceof Date,\n dateB = b instanceof Date;\n if (dateA && dateB) return a.getTime() == b.getTime();\n if (dateA != dateB) return false;\n const regexpA = a instanceof RegExp,\n regexpB = b instanceof RegExp;\n if (regexpA && regexpB) return a.toString() == b.toString();\n if (regexpA != regexpB) return false;\n const keys = Object.keys(a);\n // if (keys.length !== Object.keys(b).length) return false;\n\n for (i = 0; i < keys.length; i++) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n for (i = 0; i < keys.length; i++) if (!objectIncludes(b[keys[i]], a[keys[i]])) return false;\n return true;\n } else if (a && b && typeof a === 'function' && typeof b === 'function') {\n return a.toString() === b.toString();\n }\n return false;\n}\n\n/** Selection range */\n\nexport { DIRECTION, escapeRegExp, forceDirection, isObject, isString, objectIncludes, pick };\n", "import { DIRECTION } from './utils.js';\n\n/** Provides details of changing input */\nclass ActionDetails {\n /** Current input value */\n\n /** Current cursor position */\n\n /** Old input value */\n\n /** Old selection */\n\n constructor(opts) {\n Object.assign(this, opts);\n\n // double check if left part was changed (autofilling, other non-standard input triggers)\n while (this.value.slice(0, this.startChangePos) !== this.oldValue.slice(0, this.startChangePos)) {\n --this.oldSelection.start;\n }\n if (this.insertedCount) {\n // double check right part\n while (this.value.slice(this.cursorPos) !== this.oldValue.slice(this.oldSelection.end)) {\n if (this.value.length - this.cursorPos < this.oldValue.length - this.oldSelection.end) ++this.oldSelection.end;else ++this.cursorPos;\n }\n }\n }\n\n /** Start changing position */\n get startChangePos() {\n return Math.min(this.cursorPos, this.oldSelection.start);\n }\n\n /** Inserted symbols count */\n get insertedCount() {\n return this.cursorPos - this.startChangePos;\n }\n\n /** Inserted symbols */\n get inserted() {\n return this.value.substr(this.startChangePos, this.insertedCount);\n }\n\n /** Removed symbols count */\n get removedCount() {\n // Math.max for opposite operation\n return Math.max(this.oldSelection.end - this.startChangePos ||\n // for Delete\n this.oldValue.length - this.value.length, 0);\n }\n\n /** Removed symbols */\n get removed() {\n return this.oldValue.substr(this.startChangePos, this.removedCount);\n }\n\n /** Unchanged head symbols */\n get head() {\n return this.value.substring(0, this.startChangePos);\n }\n\n /** Unchanged tail symbols */\n get tail() {\n return this.value.substring(this.startChangePos + this.insertedCount);\n }\n\n /** Remove direction */\n get removeDirection() {\n if (!this.removedCount || this.insertedCount) return DIRECTION.NONE;\n\n // align right if delete at right\n return (this.oldSelection.end === this.cursorPos || this.oldSelection.start === this.cursorPos) &&\n // if not range removed (event with backspace)\n this.oldSelection.end === this.oldSelection.start ? DIRECTION.RIGHT : DIRECTION.LEFT;\n }\n}\n\nexport { ActionDetails as default };\n", "/** Applies mask on element */\nfunction IMask(el, opts) {\n // currently available only for input-like elements\n return new IMask.InputMask(el, opts);\n}\n\nexport { IMask as default };\n", "import { isString, isObject, pick } from '../core/utils.js';\nimport IMask from '../core/holder.js';\n\n// TODO can't use overloads here because of https://github.com/microsoft/TypeScript/issues/50754\n// export function maskedClass(mask: string): typeof MaskedPattern;\n// export function maskedClass(mask: DateConstructor): typeof MaskedDate;\n// export function maskedClass(mask: NumberConstructor): typeof MaskedNumber;\n// export function maskedClass(mask: Array | ArrayConstructor): typeof MaskedDynamic;\n// export function maskedClass(mask: MaskedDate): typeof MaskedDate;\n// export function maskedClass(mask: MaskedNumber): typeof MaskedNumber;\n// export function maskedClass(mask: MaskedEnum): typeof MaskedEnum;\n// export function maskedClass(mask: MaskedRange): typeof MaskedRange;\n// export function maskedClass(mask: MaskedRegExp): typeof MaskedRegExp;\n// export function maskedClass(mask: MaskedFunction): typeof MaskedFunction;\n// export function maskedClass(mask: MaskedPattern): typeof MaskedPattern;\n// export function maskedClass(mask: MaskedDynamic): typeof MaskedDynamic;\n// export function maskedClass(mask: Masked): typeof Masked;\n// export function maskedClass(mask: typeof Masked): typeof Masked;\n// export function maskedClass(mask: typeof MaskedDate): typeof MaskedDate;\n// export function maskedClass(mask: typeof MaskedNumber): typeof MaskedNumber;\n// export function maskedClass(mask: typeof MaskedEnum): typeof MaskedEnum;\n// export function maskedClass(mask: typeof MaskedRange): typeof MaskedRange;\n// export function maskedClass(mask: typeof MaskedRegExp): typeof MaskedRegExp;\n// export function maskedClass(mask: typeof MaskedFunction): typeof MaskedFunction;\n// export function maskedClass(mask: typeof MaskedPattern): typeof MaskedPattern;\n// export function maskedClass(mask: typeof MaskedDynamic): typeof MaskedDynamic;\n// export function maskedClass (mask: Mask): Mask;\n// export function maskedClass(mask: RegExp): typeof MaskedRegExp;\n// export function maskedClass(mask: (value: string, ...args: any[]) => boolean): typeof MaskedFunction;\n\n/** Get Masked class by mask type */\nfunction maskedClass(mask) /* TODO */{\n if (mask == null) throw new Error('mask property should be defined');\n if (mask instanceof RegExp) return IMask.MaskedRegExp;\n if (isString(mask)) return IMask.MaskedPattern;\n if (mask === Date) return IMask.MaskedDate;\n if (mask === Number) return IMask.MaskedNumber;\n if (Array.isArray(mask) || mask === Array) return IMask.MaskedDynamic;\n if (IMask.Masked && mask.prototype instanceof IMask.Masked) return mask;\n if (IMask.Masked && mask instanceof IMask.Masked) return mask.constructor;\n if (mask instanceof Function) return IMask.MaskedFunction;\n console.warn('Mask not found for mask', mask); // eslint-disable-line no-console\n return IMask.Masked;\n}\nfunction normalizeOpts(opts) {\n if (!opts) throw new Error('Options in not defined');\n if (IMask.Masked) {\n if (opts.prototype instanceof IMask.Masked) return {\n mask: opts\n };\n\n /*\n handle cases like:\n 1) opts = Masked\n 2) opts = { mask: Masked, ...instanceOpts }\n */\n const {\n mask = undefined,\n ...instanceOpts\n } = opts instanceof IMask.Masked ? {\n mask: opts\n } : isObject(opts) && opts.mask instanceof IMask.Masked ? opts : {};\n if (mask) {\n const _mask = mask.mask;\n return {\n ...pick(mask, (_, k) => !k.startsWith('_')),\n mask: mask.constructor,\n _mask,\n ...instanceOpts\n };\n }\n }\n if (!isObject(opts)) return {\n mask: opts\n };\n return {\n ...opts\n };\n}\n\n// TODO can't use overloads here because of https://github.com/microsoft/TypeScript/issues/50754\n\n// From masked\n// export default function createMask (opts: Opts): ReturnMasked;\n// // From masked class\n// export default function createMask, ReturnMasked extends Masked=InstanceType> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedDate=MaskedDate> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedNumber=MaskedNumber> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedEnum=MaskedEnum> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedRange=MaskedRange> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedRegExp=MaskedRegExp> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedFunction=MaskedFunction> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedPattern=MaskedPattern> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedDynamic=MaskedDynamic> (opts: Opts): ReturnMasked;\n// // From mask opts\n// export default function createMask, ReturnMasked=Opts extends MaskedOptions ? M : never> (opts: Opts): ReturnMasked;\n// export default function createMask> (opts: Opts): ReturnMasked;\n// export default function createMask> (opts: Opts): ReturnMasked;\n// export default function createMask> (opts: Opts): ReturnMasked;\n// export default function createMask> (opts: Opts): ReturnMasked;\n// export default function createMask> (opts: Opts): ReturnMasked;\n// export default function createMask> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedRegExp=MaskedRegExp> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedFunction=MaskedFunction> (opts: Opts): ReturnMasked;\n\n/** Creates new {@link Masked} depending on mask type */\nfunction createMask(opts) {\n if (IMask.Masked && opts instanceof IMask.Masked) return opts;\n const nOpts = normalizeOpts(opts);\n const MaskedClass = maskedClass(nOpts.mask);\n if (!MaskedClass) throw new Error(\"Masked class is not found for provided mask \" + nOpts.mask + \", appropriate module needs to be imported manually before creating mask.\");\n if (nOpts.mask === MaskedClass) delete nOpts.mask;\n if (nOpts._mask) {\n nOpts.mask = nOpts._mask;\n delete nOpts._mask;\n }\n return new MaskedClass(nOpts);\n}\nIMask.createMask = createMask;\n\nexport { createMask as default, maskedClass, normalizeOpts };\n", "import IMask from '../core/holder.js';\n\n/** Generic element API to use with mask */\nclass MaskElement {\n /** */\n\n /** */\n\n /** */\n\n /** Safely returns selection start */\n get selectionStart() {\n let start;\n try {\n start = this._unsafeSelectionStart;\n } catch {}\n return start != null ? start : this.value.length;\n }\n\n /** Safely returns selection end */\n get selectionEnd() {\n let end;\n try {\n end = this._unsafeSelectionEnd;\n } catch {}\n return end != null ? end : this.value.length;\n }\n\n /** Safely sets element selection */\n select(start, end) {\n if (start == null || end == null || start === this.selectionStart && end === this.selectionEnd) return;\n try {\n this._unsafeSelect(start, end);\n } catch {}\n }\n\n /** */\n get isActive() {\n return false;\n }\n /** */\n\n /** */\n\n /** */\n}\nIMask.MaskElement = MaskElement;\n\nexport { MaskElement as default };\n", "import MaskElement from './mask-element.js';\nimport IMask from '../core/holder.js';\n\nconst KEY_Z = 90;\nconst KEY_Y = 89;\n\n/** Bridge between HTMLElement and {@link Masked} */\nclass HTMLMaskElement extends MaskElement {\n /** HTMLElement to use mask on */\n\n constructor(input) {\n super();\n this.input = input;\n this._onKeydown = this._onKeydown.bind(this);\n this._onInput = this._onInput.bind(this);\n this._onBeforeinput = this._onBeforeinput.bind(this);\n this._onCompositionEnd = this._onCompositionEnd.bind(this);\n }\n get rootElement() {\n var _this$input$getRootNo, _this$input$getRootNo2, _this$input;\n return (_this$input$getRootNo = (_this$input$getRootNo2 = (_this$input = this.input).getRootNode) == null ? void 0 : _this$input$getRootNo2.call(_this$input)) != null ? _this$input$getRootNo : document;\n }\n\n /** Is element in focus */\n get isActive() {\n return this.input === this.rootElement.activeElement;\n }\n\n /** Binds HTMLElement events to mask internal events */\n bindEvents(handlers) {\n this.input.addEventListener('keydown', this._onKeydown);\n this.input.addEventListener('input', this._onInput);\n this.input.addEventListener('beforeinput', this._onBeforeinput);\n this.input.addEventListener('compositionend', this._onCompositionEnd);\n this.input.addEventListener('drop', handlers.drop);\n this.input.addEventListener('click', handlers.click);\n this.input.addEventListener('focus', handlers.focus);\n this.input.addEventListener('blur', handlers.commit);\n this._handlers = handlers;\n }\n _onKeydown(e) {\n if (this._handlers.redo && (e.keyCode === KEY_Z && e.shiftKey && (e.metaKey || e.ctrlKey) || e.keyCode === KEY_Y && e.ctrlKey)) {\n e.preventDefault();\n return this._handlers.redo(e);\n }\n if (this._handlers.undo && e.keyCode === KEY_Z && (e.metaKey || e.ctrlKey)) {\n e.preventDefault();\n return this._handlers.undo(e);\n }\n if (!e.isComposing) this._handlers.selectionChange(e);\n }\n _onBeforeinput(e) {\n if (e.inputType === 'historyUndo' && this._handlers.undo) {\n e.preventDefault();\n return this._handlers.undo(e);\n }\n if (e.inputType === 'historyRedo' && this._handlers.redo) {\n e.preventDefault();\n return this._handlers.redo(e);\n }\n }\n _onCompositionEnd(e) {\n this._handlers.input(e);\n }\n _onInput(e) {\n if (!e.isComposing) this._handlers.input(e);\n }\n\n /** Unbinds HTMLElement events to mask internal events */\n unbindEvents() {\n this.input.removeEventListener('keydown', this._onKeydown);\n this.input.removeEventListener('input', this._onInput);\n this.input.removeEventListener('beforeinput', this._onBeforeinput);\n this.input.removeEventListener('compositionend', this._onCompositionEnd);\n this.input.removeEventListener('drop', this._handlers.drop);\n this.input.removeEventListener('click', this._handlers.click);\n this.input.removeEventListener('focus', this._handlers.focus);\n this.input.removeEventListener('blur', this._handlers.commit);\n this._handlers = {};\n }\n}\nIMask.HTMLMaskElement = HTMLMaskElement;\n\nexport { HTMLMaskElement as default };\n", "import HTMLMaskElement from './html-mask-element.js';\nimport IMask from '../core/holder.js';\nimport './mask-element.js';\n\n/** Bridge between InputElement and {@link Masked} */\nclass HTMLInputMaskElement extends HTMLMaskElement {\n /** InputElement to use mask on */\n\n constructor(input) {\n super(input);\n this.input = input;\n }\n\n /** Returns InputElement selection start */\n get _unsafeSelectionStart() {\n return this.input.selectionStart != null ? this.input.selectionStart : this.value.length;\n }\n\n /** Returns InputElement selection end */\n get _unsafeSelectionEnd() {\n return this.input.selectionEnd;\n }\n\n /** Sets InputElement selection */\n _unsafeSelect(start, end) {\n this.input.setSelectionRange(start, end);\n }\n get value() {\n return this.input.value;\n }\n set value(value) {\n this.input.value = value;\n }\n}\nIMask.HTMLMaskElement = HTMLMaskElement;\n\nexport { HTMLInputMaskElement as default };\n", "import HTMLMaskElement from './html-mask-element.js';\nimport IMask from '../core/holder.js';\nimport './mask-element.js';\n\nclass HTMLContenteditableMaskElement extends HTMLMaskElement {\n /** Returns HTMLElement selection start */\n get _unsafeSelectionStart() {\n const root = this.rootElement;\n const selection = root.getSelection && root.getSelection();\n const anchorOffset = selection && selection.anchorOffset;\n const focusOffset = selection && selection.focusOffset;\n if (focusOffset == null || anchorOffset == null || anchorOffset < focusOffset) {\n return anchorOffset;\n }\n return focusOffset;\n }\n\n /** Returns HTMLElement selection end */\n get _unsafeSelectionEnd() {\n const root = this.rootElement;\n const selection = root.getSelection && root.getSelection();\n const anchorOffset = selection && selection.anchorOffset;\n const focusOffset = selection && selection.focusOffset;\n if (focusOffset == null || anchorOffset == null || anchorOffset > focusOffset) {\n return anchorOffset;\n }\n return focusOffset;\n }\n\n /** Sets HTMLElement selection */\n _unsafeSelect(start, end) {\n if (!this.rootElement.createRange) return;\n const range = this.rootElement.createRange();\n range.setStart(this.input.firstChild || this.input, start);\n range.setEnd(this.input.lastChild || this.input, end);\n const root = this.rootElement;\n const selection = root.getSelection && root.getSelection();\n if (selection) {\n selection.removeAllRanges();\n selection.addRange(range);\n }\n }\n\n /** HTMLElement value */\n get value() {\n return this.input.textContent || '';\n }\n set value(value) {\n this.input.textContent = value;\n }\n}\nIMask.HTMLContenteditableMaskElement = HTMLContenteditableMaskElement;\n\nexport { HTMLContenteditableMaskElement as default };\n", "class InputHistory {\n constructor() {\n this.states = [];\n this.currentIndex = 0;\n }\n get currentState() {\n return this.states[this.currentIndex];\n }\n get isEmpty() {\n return this.states.length === 0;\n }\n push(state) {\n // if current index points before the last element then remove the future\n if (this.currentIndex < this.states.length - 1) this.states.length = this.currentIndex + 1;\n this.states.push(state);\n if (this.states.length > InputHistory.MAX_LENGTH) this.states.shift();\n this.currentIndex = this.states.length - 1;\n }\n go(steps) {\n this.currentIndex = Math.min(Math.max(this.currentIndex + steps, 0), this.states.length - 1);\n return this.currentState;\n }\n undo() {\n return this.go(-1);\n }\n redo() {\n return this.go(+1);\n }\n clear() {\n this.states.length = 0;\n this.currentIndex = 0;\n }\n}\nInputHistory.MAX_LENGTH = 100;\n\nexport { InputHistory as default };\n", "import { DIRECTION } from '../core/utils.js';\nimport ActionDetails from '../core/action-details.js';\nimport createMask, { maskedClass } from '../masked/factory.js';\nimport MaskElement from './mask-element.js';\nimport HTMLInputMaskElement from './html-input-mask-element.js';\nimport HTMLContenteditableMaskElement from './html-contenteditable-mask-element.js';\nimport IMask from '../core/holder.js';\nimport InputHistory from './input-history.js';\nimport './html-mask-element.js';\n\n/** Listens to element events and controls changes between element and {@link Masked} */\nclass InputMask {\n /**\n View element\n */\n\n /** Internal {@link Masked} model */\n\n constructor(el, opts) {\n this.el = el instanceof MaskElement ? el : el.isContentEditable && el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA' ? new HTMLContenteditableMaskElement(el) : new HTMLInputMaskElement(el);\n this.masked = createMask(opts);\n this._listeners = {};\n this._value = '';\n this._unmaskedValue = '';\n this._rawInputValue = '';\n this.history = new InputHistory();\n this._saveSelection = this._saveSelection.bind(this);\n this._onInput = this._onInput.bind(this);\n this._onChange = this._onChange.bind(this);\n this._onDrop = this._onDrop.bind(this);\n this._onFocus = this._onFocus.bind(this);\n this._onClick = this._onClick.bind(this);\n this._onUndo = this._onUndo.bind(this);\n this._onRedo = this._onRedo.bind(this);\n this.alignCursor = this.alignCursor.bind(this);\n this.alignCursorFriendly = this.alignCursorFriendly.bind(this);\n this._bindEvents();\n\n // refresh\n this.updateValue();\n this._onChange();\n }\n maskEquals(mask) {\n var _this$masked;\n return mask == null || ((_this$masked = this.masked) == null ? void 0 : _this$masked.maskEquals(mask));\n }\n\n /** Masked */\n get mask() {\n return this.masked.mask;\n }\n set mask(mask) {\n if (this.maskEquals(mask)) return;\n if (!(mask instanceof IMask.Masked) && this.masked.constructor === maskedClass(mask)) {\n // TODO \"any\" no idea\n this.masked.updateOptions({\n mask\n });\n return;\n }\n const masked = mask instanceof IMask.Masked ? mask : createMask({\n mask\n });\n masked.unmaskedValue = this.masked.unmaskedValue;\n this.masked = masked;\n }\n\n /** Raw value */\n get value() {\n return this._value;\n }\n set value(str) {\n if (this.value === str) return;\n this.masked.value = str;\n this.updateControl('auto');\n }\n\n /** Unmasked value */\n get unmaskedValue() {\n return this._unmaskedValue;\n }\n set unmaskedValue(str) {\n if (this.unmaskedValue === str) return;\n this.masked.unmaskedValue = str;\n this.updateControl('auto');\n }\n\n /** Raw input value */\n get rawInputValue() {\n return this._rawInputValue;\n }\n set rawInputValue(str) {\n if (this.rawInputValue === str) return;\n this.masked.rawInputValue = str;\n this.updateControl();\n this.alignCursor();\n }\n\n /** Typed unmasked value */\n get typedValue() {\n return this.masked.typedValue;\n }\n set typedValue(val) {\n if (this.masked.typedValueEquals(val)) return;\n this.masked.typedValue = val;\n this.updateControl('auto');\n }\n\n /** Display value */\n get displayValue() {\n return this.masked.displayValue;\n }\n\n /** Starts listening to element events */\n _bindEvents() {\n this.el.bindEvents({\n selectionChange: this._saveSelection,\n input: this._onInput,\n drop: this._onDrop,\n click: this._onClick,\n focus: this._onFocus,\n commit: this._onChange,\n undo: this._onUndo,\n redo: this._onRedo\n });\n }\n\n /** Stops listening to element events */\n _unbindEvents() {\n if (this.el) this.el.unbindEvents();\n }\n\n /** Fires custom event */\n _fireEvent(ev, e) {\n const listeners = this._listeners[ev];\n if (!listeners) return;\n listeners.forEach(l => l(e));\n }\n\n /** Current selection start */\n get selectionStart() {\n return this._cursorChanging ? this._changingCursorPos : this.el.selectionStart;\n }\n\n /** Current cursor position */\n get cursorPos() {\n return this._cursorChanging ? this._changingCursorPos : this.el.selectionEnd;\n }\n set cursorPos(pos) {\n if (!this.el || !this.el.isActive) return;\n this.el.select(pos, pos);\n this._saveSelection();\n }\n\n /** Stores current selection */\n _saveSelection( /* ev */\n ) {\n if (this.displayValue !== this.el.value) {\n console.warn('Element value was changed outside of mask. Syncronize mask using `mask.updateValue()` to work properly.'); // eslint-disable-line no-console\n }\n this._selection = {\n start: this.selectionStart,\n end: this.cursorPos\n };\n }\n\n /** Syncronizes model value from view */\n updateValue() {\n this.masked.value = this.el.value;\n this._value = this.masked.value;\n this._unmaskedValue = this.masked.unmaskedValue;\n this._rawInputValue = this.masked.rawInputValue;\n }\n\n /** Syncronizes view from model value, fires change events */\n updateControl(cursorPos) {\n const newUnmaskedValue = this.masked.unmaskedValue;\n const newValue = this.masked.value;\n const newRawInputValue = this.masked.rawInputValue;\n const newDisplayValue = this.displayValue;\n const isChanged = this.unmaskedValue !== newUnmaskedValue || this.value !== newValue || this._rawInputValue !== newRawInputValue;\n this._unmaskedValue = newUnmaskedValue;\n this._value = newValue;\n this._rawInputValue = newRawInputValue;\n if (this.el.value !== newDisplayValue) this.el.value = newDisplayValue;\n if (cursorPos === 'auto') this.alignCursor();else if (cursorPos != null) this.cursorPos = cursorPos;\n if (isChanged) this._fireChangeEvents();\n if (!this._historyChanging && (isChanged || this.history.isEmpty)) this.history.push({\n unmaskedValue: newUnmaskedValue,\n selection: {\n start: this.selectionStart,\n end: this.cursorPos\n }\n });\n }\n\n /** Updates options with deep equal check, recreates {@link Masked} model if mask type changes */\n updateOptions(opts) {\n const {\n mask,\n ...restOpts\n } = opts; // TODO types, yes, mask is optional\n\n const updateMask = !this.maskEquals(mask);\n const updateOpts = this.masked.optionsIsChanged(restOpts);\n if (updateMask) this.mask = mask;\n if (updateOpts) this.masked.updateOptions(restOpts); // TODO\n\n if (updateMask || updateOpts) this.updateControl();\n }\n\n /** Updates cursor */\n updateCursor(cursorPos) {\n if (cursorPos == null) return;\n this.cursorPos = cursorPos;\n\n // also queue change cursor for mobile browsers\n this._delayUpdateCursor(cursorPos);\n }\n\n /** Delays cursor update to support mobile browsers */\n _delayUpdateCursor(cursorPos) {\n this._abortUpdateCursor();\n this._changingCursorPos = cursorPos;\n this._cursorChanging = setTimeout(() => {\n if (!this.el) return; // if was destroyed\n this.cursorPos = this._changingCursorPos;\n this._abortUpdateCursor();\n }, 10);\n }\n\n /** Fires custom events */\n _fireChangeEvents() {\n this._fireEvent('accept', this._inputEvent);\n if (this.masked.isComplete) this._fireEvent('complete', this._inputEvent);\n }\n\n /** Aborts delayed cursor update */\n _abortUpdateCursor() {\n if (this._cursorChanging) {\n clearTimeout(this._cursorChanging);\n delete this._cursorChanging;\n }\n }\n\n /** Aligns cursor to nearest available position */\n alignCursor() {\n this.cursorPos = this.masked.nearestInputPos(this.masked.nearestInputPos(this.cursorPos, DIRECTION.LEFT));\n }\n\n /** Aligns cursor only if selection is empty */\n alignCursorFriendly() {\n if (this.selectionStart !== this.cursorPos) return; // skip if range is selected\n this.alignCursor();\n }\n\n /** Adds listener on custom event */\n on(ev, handler) {\n if (!this._listeners[ev]) this._listeners[ev] = [];\n this._listeners[ev].push(handler);\n return this;\n }\n\n /** Removes custom event listener */\n off(ev, handler) {\n if (!this._listeners[ev]) return this;\n if (!handler) {\n delete this._listeners[ev];\n return this;\n }\n const hIndex = this._listeners[ev].indexOf(handler);\n if (hIndex >= 0) this._listeners[ev].splice(hIndex, 1);\n return this;\n }\n\n /** Handles view input event */\n _onInput(e) {\n this._inputEvent = e;\n this._abortUpdateCursor();\n const details = new ActionDetails({\n // new state\n value: this.el.value,\n cursorPos: this.cursorPos,\n // old state\n oldValue: this.displayValue,\n oldSelection: this._selection\n });\n const oldRawValue = this.masked.rawInputValue;\n const offset = this.masked.splice(details.startChangePos, details.removed.length, details.inserted, details.removeDirection, {\n input: true,\n raw: true\n }).offset;\n\n // force align in remove direction only if no input chars were removed\n // otherwise we still need to align with NONE (to get out from fixed symbols for instance)\n const removeDirection = oldRawValue === this.masked.rawInputValue ? details.removeDirection : DIRECTION.NONE;\n let cursorPos = this.masked.nearestInputPos(details.startChangePos + offset, removeDirection);\n if (removeDirection !== DIRECTION.NONE) cursorPos = this.masked.nearestInputPos(cursorPos, DIRECTION.NONE);\n this.updateControl(cursorPos);\n delete this._inputEvent;\n }\n\n /** Handles view change event and commits model value */\n _onChange() {\n if (this.displayValue !== this.el.value) this.updateValue();\n this.masked.doCommit();\n this.updateControl();\n this._saveSelection();\n }\n\n /** Handles view drop event, prevents by default */\n _onDrop(ev) {\n ev.preventDefault();\n ev.stopPropagation();\n }\n\n /** Restore last selection on focus */\n _onFocus(ev) {\n this.alignCursorFriendly();\n }\n\n /** Restore last selection on focus */\n _onClick(ev) {\n this.alignCursorFriendly();\n }\n _onUndo() {\n this._applyHistoryState(this.history.undo());\n }\n _onRedo() {\n this._applyHistoryState(this.history.redo());\n }\n _applyHistoryState(state) {\n if (!state) return;\n this._historyChanging = true;\n this.unmaskedValue = state.unmaskedValue;\n this.el.select(state.selection.start, state.selection.end);\n this._saveSelection();\n this._historyChanging = false;\n }\n\n /** Unbind view events and removes element reference */\n destroy() {\n this._unbindEvents();\n this._listeners.length = 0;\n delete this.el;\n }\n}\nIMask.InputMask = InputMask;\n\nexport { InputMask as default };\n", "import IMask from './holder.js';\n\n/** Provides details of changing model value */\nclass ChangeDetails {\n /** Inserted symbols */\n\n /** Additional offset if any changes occurred before tail */\n\n /** Raw inserted is used by dynamic mask */\n\n /** Can skip chars */\n\n static normalize(prep) {\n return Array.isArray(prep) ? prep : [prep, new ChangeDetails()];\n }\n constructor(details) {\n Object.assign(this, {\n inserted: '',\n rawInserted: '',\n tailShift: 0,\n skip: false\n }, details);\n }\n\n /** Aggregate changes */\n aggregate(details) {\n this.inserted += details.inserted;\n this.rawInserted += details.rawInserted;\n this.tailShift += details.tailShift;\n this.skip = this.skip || details.skip;\n return this;\n }\n\n /** Total offset considering all changes */\n get offset() {\n return this.tailShift + this.inserted.length;\n }\n get consumed() {\n return Boolean(this.rawInserted) || this.skip;\n }\n equals(details) {\n return this.inserted === details.inserted && this.tailShift === details.tailShift && this.rawInserted === details.rawInserted && this.skip === details.skip;\n }\n}\nIMask.ChangeDetails = ChangeDetails;\n\nexport { ChangeDetails as default };\n", "/** Provides details of continuous extracted tail */\nclass ContinuousTailDetails {\n /** Tail value as string */\n\n /** Tail start position */\n\n /** Start position */\n\n constructor(value, from, stop) {\n if (value === void 0) {\n value = '';\n }\n if (from === void 0) {\n from = 0;\n }\n this.value = value;\n this.from = from;\n this.stop = stop;\n }\n toString() {\n return this.value;\n }\n extend(tail) {\n this.value += String(tail);\n }\n appendTo(masked) {\n return masked.append(this.toString(), {\n tail: true\n }).aggregate(masked._appendPlaceholder());\n }\n get state() {\n return {\n value: this.value,\n from: this.from,\n stop: this.stop\n };\n }\n set state(state) {\n Object.assign(this, state);\n }\n unshift(beforePos) {\n if (!this.value.length || beforePos != null && this.from >= beforePos) return '';\n const shiftChar = this.value[0];\n this.value = this.value.slice(1);\n return shiftChar;\n }\n shift() {\n if (!this.value.length) return '';\n const shiftChar = this.value[this.value.length - 1];\n this.value = this.value.slice(0, -1);\n return shiftChar;\n }\n}\n\nexport { ContinuousTailDetails as default };\n", "import ChangeDetails from '../core/change-details.js';\nimport ContinuousTailDetails from '../core/continuous-tail-details.js';\nimport { isString, DIRECTION, objectIncludes, forceDirection } from '../core/utils.js';\nimport IMask from '../core/holder.js';\n\n/** Append flags */\n\n/** Extract flags */\n\n// see https://github.com/microsoft/TypeScript/issues/6223\n\n/** Provides common masking stuff */\nclass Masked {\n /** */\n\n /** */\n\n /** Transforms value before mask processing */\n\n /** Transforms each char before mask processing */\n\n /** Validates if value is acceptable */\n\n /** Does additional processing at the end of editing */\n\n /** Format typed value to string */\n\n /** Parse string to get typed value */\n\n /** Enable characters overwriting */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n constructor(opts) {\n this._value = '';\n this._update({\n ...Masked.DEFAULTS,\n ...opts\n });\n this._initialized = true;\n }\n\n /** Sets and applies new options */\n updateOptions(opts) {\n if (!this.optionsIsChanged(opts)) return;\n this.withValueRefresh(this._update.bind(this, opts));\n }\n\n /** Sets new options */\n _update(opts) {\n Object.assign(this, opts);\n }\n\n /** Mask state */\n get state() {\n return {\n _value: this.value,\n _rawInputValue: this.rawInputValue\n };\n }\n set state(state) {\n this._value = state._value;\n }\n\n /** Resets value */\n reset() {\n this._value = '';\n }\n get value() {\n return this._value;\n }\n set value(value) {\n this.resolve(value, {\n input: true\n });\n }\n\n /** Resolve new value */\n resolve(value, flags) {\n if (flags === void 0) {\n flags = {\n input: true\n };\n }\n this.reset();\n this.append(value, flags, '');\n this.doCommit();\n }\n get unmaskedValue() {\n return this.value;\n }\n set unmaskedValue(value) {\n this.resolve(value, {});\n }\n get typedValue() {\n return this.parse ? this.parse(this.value, this) : this.unmaskedValue;\n }\n set typedValue(value) {\n if (this.format) {\n this.value = this.format(value, this);\n } else {\n this.unmaskedValue = String(value);\n }\n }\n\n /** Value that includes raw user input */\n get rawInputValue() {\n return this.extractInput(0, this.displayValue.length, {\n raw: true\n });\n }\n set rawInputValue(value) {\n this.resolve(value, {\n raw: true\n });\n }\n get displayValue() {\n return this.value;\n }\n get isComplete() {\n return true;\n }\n get isFilled() {\n return this.isComplete;\n }\n\n /** Finds nearest input position in direction */\n nearestInputPos(cursorPos, direction) {\n return cursorPos;\n }\n totalInputPositions(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n return Math.min(this.displayValue.length, toPos - fromPos);\n }\n\n /** Extracts value in range considering flags */\n extractInput(fromPos, toPos, flags) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n return this.displayValue.slice(fromPos, toPos);\n }\n\n /** Extracts tail in range */\n extractTail(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n return new ContinuousTailDetails(this.extractInput(fromPos, toPos), fromPos);\n }\n\n /** Appends tail */\n appendTail(tail) {\n if (isString(tail)) tail = new ContinuousTailDetails(String(tail));\n return tail.appendTo(this);\n }\n\n /** Appends char */\n _appendCharRaw(ch, flags) {\n if (!ch) return new ChangeDetails();\n this._value += ch;\n return new ChangeDetails({\n inserted: ch,\n rawInserted: ch\n });\n }\n\n /** Appends char */\n _appendChar(ch, flags, checkTail) {\n if (flags === void 0) {\n flags = {};\n }\n const consistentState = this.state;\n let details;\n [ch, details] = this.doPrepareChar(ch, flags);\n if (ch) {\n details = details.aggregate(this._appendCharRaw(ch, flags));\n\n // TODO handle `skip`?\n\n // try `autofix` lookahead\n if (!details.rawInserted && this.autofix === 'pad') {\n const noFixState = this.state;\n this.state = consistentState;\n let fixDetails = this.pad(flags);\n const chDetails = this._appendCharRaw(ch, flags);\n fixDetails = fixDetails.aggregate(chDetails);\n\n // if fix was applied or\n // if details are equal use skip restoring state optimization\n if (chDetails.rawInserted || fixDetails.equals(details)) {\n details = fixDetails;\n } else {\n this.state = noFixState;\n }\n }\n }\n if (details.inserted) {\n let consistentTail;\n let appended = this.doValidate(flags) !== false;\n if (appended && checkTail != null) {\n // validation ok, check tail\n const beforeTailState = this.state;\n if (this.overwrite === true) {\n consistentTail = checkTail.state;\n for (let i = 0; i < details.rawInserted.length; ++i) {\n checkTail.unshift(this.displayValue.length - details.tailShift);\n }\n }\n let tailDetails = this.appendTail(checkTail);\n appended = tailDetails.rawInserted.length === checkTail.toString().length;\n\n // not ok, try shift\n if (!(appended && tailDetails.inserted) && this.overwrite === 'shift') {\n this.state = beforeTailState;\n consistentTail = checkTail.state;\n for (let i = 0; i < details.rawInserted.length; ++i) {\n checkTail.shift();\n }\n tailDetails = this.appendTail(checkTail);\n appended = tailDetails.rawInserted.length === checkTail.toString().length;\n }\n\n // if ok, rollback state after tail\n if (appended && tailDetails.inserted) this.state = beforeTailState;\n }\n\n // revert all if something went wrong\n if (!appended) {\n details = new ChangeDetails();\n this.state = consistentState;\n if (checkTail && consistentTail) checkTail.state = consistentTail;\n }\n }\n return details;\n }\n\n /** Appends optional placeholder at the end */\n _appendPlaceholder() {\n return new ChangeDetails();\n }\n\n /** Appends optional eager placeholder at the end */\n _appendEager() {\n return new ChangeDetails();\n }\n\n /** Appends symbols considering flags */\n append(str, flags, tail) {\n if (!isString(str)) throw new Error('value should be string');\n const checkTail = isString(tail) ? new ContinuousTailDetails(String(tail)) : tail;\n if (flags != null && flags.tail) flags._beforeTailState = this.state;\n let details;\n [str, details] = this.doPrepare(str, flags);\n for (let ci = 0; ci < str.length; ++ci) {\n const d = this._appendChar(str[ci], flags, checkTail);\n if (!d.rawInserted && !this.doSkipInvalid(str[ci], flags, checkTail)) break;\n details.aggregate(d);\n }\n if ((this.eager === true || this.eager === 'append') && flags != null && flags.input && str) {\n details.aggregate(this._appendEager());\n }\n\n // append tail but aggregate only tailShift\n if (checkTail != null) {\n details.tailShift += this.appendTail(checkTail).tailShift;\n // TODO it's a good idea to clear state after appending ends\n // but it causes bugs when one append calls another (when dynamic dispatch set rawInputValue)\n // this._resetBeforeTailState();\n }\n return details;\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n this._value = this.displayValue.slice(0, fromPos) + this.displayValue.slice(toPos);\n return new ChangeDetails();\n }\n\n /** Calls function and reapplies current value */\n withValueRefresh(fn) {\n if (this._refreshing || !this._initialized) return fn();\n this._refreshing = true;\n const rawInput = this.rawInputValue;\n const value = this.value;\n const ret = fn();\n this.rawInputValue = rawInput;\n // append lost trailing chars at the end\n if (this.value && this.value !== value && value.indexOf(this.value) === 0) {\n this.append(value.slice(this.displayValue.length), {}, '');\n this.doCommit();\n }\n delete this._refreshing;\n return ret;\n }\n runIsolated(fn) {\n if (this._isolated || !this._initialized) return fn(this);\n this._isolated = true;\n const state = this.state;\n const ret = fn(this);\n this.state = state;\n delete this._isolated;\n return ret;\n }\n doSkipInvalid(ch, flags, checkTail) {\n return Boolean(this.skipInvalid);\n }\n\n /** Prepares string before mask processing */\n doPrepare(str, flags) {\n if (flags === void 0) {\n flags = {};\n }\n return ChangeDetails.normalize(this.prepare ? this.prepare(str, this, flags) : str);\n }\n\n /** Prepares each char before mask processing */\n doPrepareChar(str, flags) {\n if (flags === void 0) {\n flags = {};\n }\n return ChangeDetails.normalize(this.prepareChar ? this.prepareChar(str, this, flags) : str);\n }\n\n /** Validates if value is acceptable */\n doValidate(flags) {\n return (!this.validate || this.validate(this.value, this, flags)) && (!this.parent || this.parent.doValidate(flags));\n }\n\n /** Does additional processing at the end of editing */\n doCommit() {\n if (this.commit) this.commit(this.value, this);\n }\n splice(start, deleteCount, inserted, removeDirection, flags) {\n if (inserted === void 0) {\n inserted = '';\n }\n if (removeDirection === void 0) {\n removeDirection = DIRECTION.NONE;\n }\n if (flags === void 0) {\n flags = {\n input: true\n };\n }\n const tailPos = start + deleteCount;\n const tail = this.extractTail(tailPos);\n const eagerRemove = this.eager === true || this.eager === 'remove';\n let oldRawValue;\n if (eagerRemove) {\n removeDirection = forceDirection(removeDirection);\n oldRawValue = this.extractInput(0, tailPos, {\n raw: true\n });\n }\n let startChangePos = start;\n const details = new ChangeDetails();\n\n // if it is just deletion without insertion\n if (removeDirection !== DIRECTION.NONE) {\n startChangePos = this.nearestInputPos(start, deleteCount > 1 && start !== 0 && !eagerRemove ? DIRECTION.NONE : removeDirection);\n\n // adjust tailShift if start was aligned\n details.tailShift = startChangePos - start;\n }\n details.aggregate(this.remove(startChangePos));\n if (eagerRemove && removeDirection !== DIRECTION.NONE && oldRawValue === this.rawInputValue) {\n if (removeDirection === DIRECTION.FORCE_LEFT) {\n let valLength;\n while (oldRawValue === this.rawInputValue && (valLength = this.displayValue.length)) {\n details.aggregate(new ChangeDetails({\n tailShift: -1\n })).aggregate(this.remove(valLength - 1));\n }\n } else if (removeDirection === DIRECTION.FORCE_RIGHT) {\n tail.unshift();\n }\n }\n return details.aggregate(this.append(inserted, flags, tail));\n }\n maskEquals(mask) {\n return this.mask === mask;\n }\n optionsIsChanged(opts) {\n return !objectIncludes(this, opts);\n }\n typedValueEquals(value) {\n const tval = this.typedValue;\n return value === tval || Masked.EMPTY_VALUES.includes(value) && Masked.EMPTY_VALUES.includes(tval) || (this.format ? this.format(value, this) === this.format(this.typedValue, this) : false);\n }\n pad(flags) {\n return new ChangeDetails();\n }\n}\nMasked.DEFAULTS = {\n skipInvalid: true\n};\nMasked.EMPTY_VALUES = [undefined, null, ''];\nIMask.Masked = Masked;\n\nexport { Masked as default };\n", "import ChangeDetails from '../../core/change-details.js';\nimport { isString } from '../../core/utils.js';\nimport ContinuousTailDetails from '../../core/continuous-tail-details.js';\nimport IMask from '../../core/holder.js';\n\nclass ChunksTailDetails {\n /** */\n\n constructor(chunks, from) {\n if (chunks === void 0) {\n chunks = [];\n }\n if (from === void 0) {\n from = 0;\n }\n this.chunks = chunks;\n this.from = from;\n }\n toString() {\n return this.chunks.map(String).join('');\n }\n extend(tailChunk) {\n if (!String(tailChunk)) return;\n tailChunk = isString(tailChunk) ? new ContinuousTailDetails(String(tailChunk)) : tailChunk;\n const lastChunk = this.chunks[this.chunks.length - 1];\n const extendLast = lastChunk && (\n // if stops are same or tail has no stop\n lastChunk.stop === tailChunk.stop || tailChunk.stop == null) &&\n // if tail chunk goes just after last chunk\n tailChunk.from === lastChunk.from + lastChunk.toString().length;\n if (tailChunk instanceof ContinuousTailDetails) {\n // check the ability to extend previous chunk\n if (extendLast) {\n // extend previous chunk\n lastChunk.extend(tailChunk.toString());\n } else {\n // append new chunk\n this.chunks.push(tailChunk);\n }\n } else if (tailChunk instanceof ChunksTailDetails) {\n if (tailChunk.stop == null) {\n // unwrap floating chunks to parent, keeping `from` pos\n let firstTailChunk;\n while (tailChunk.chunks.length && tailChunk.chunks[0].stop == null) {\n firstTailChunk = tailChunk.chunks.shift(); // not possible to be `undefined` because length was checked above\n firstTailChunk.from += tailChunk.from;\n this.extend(firstTailChunk);\n }\n }\n\n // if tail chunk still has value\n if (tailChunk.toString()) {\n // if chunks contains stops, then popup stop to container\n tailChunk.stop = tailChunk.blockIndex;\n this.chunks.push(tailChunk);\n }\n }\n }\n appendTo(masked) {\n if (!(masked instanceof IMask.MaskedPattern)) {\n const tail = new ContinuousTailDetails(this.toString());\n return tail.appendTo(masked);\n }\n const details = new ChangeDetails();\n for (let ci = 0; ci < this.chunks.length; ++ci) {\n const chunk = this.chunks[ci];\n const lastBlockIter = masked._mapPosToBlock(masked.displayValue.length);\n const stop = chunk.stop;\n let chunkBlock;\n if (stop != null && (\n // if block not found or stop is behind lastBlock\n !lastBlockIter || lastBlockIter.index <= stop)) {\n if (chunk instanceof ChunksTailDetails ||\n // for continuous block also check if stop is exist\n masked._stops.indexOf(stop) >= 0) {\n details.aggregate(masked._appendPlaceholder(stop));\n }\n chunkBlock = chunk instanceof ChunksTailDetails && masked._blocks[stop];\n }\n if (chunkBlock) {\n const tailDetails = chunkBlock.appendTail(chunk);\n details.aggregate(tailDetails);\n\n // get not inserted chars\n const remainChars = chunk.toString().slice(tailDetails.rawInserted.length);\n if (remainChars) details.aggregate(masked.append(remainChars, {\n tail: true\n }));\n } else {\n details.aggregate(masked.append(chunk.toString(), {\n tail: true\n }));\n }\n }\n return details;\n }\n get state() {\n return {\n chunks: this.chunks.map(c => c.state),\n from: this.from,\n stop: this.stop,\n blockIndex: this.blockIndex\n };\n }\n set state(state) {\n const {\n chunks,\n ...props\n } = state;\n Object.assign(this, props);\n this.chunks = chunks.map(cstate => {\n const chunk = \"chunks\" in cstate ? new ChunksTailDetails() : new ContinuousTailDetails();\n chunk.state = cstate;\n return chunk;\n });\n }\n unshift(beforePos) {\n if (!this.chunks.length || beforePos != null && this.from >= beforePos) return '';\n const chunkShiftPos = beforePos != null ? beforePos - this.from : beforePos;\n let ci = 0;\n while (ci < this.chunks.length) {\n const chunk = this.chunks[ci];\n const shiftChar = chunk.unshift(chunkShiftPos);\n if (chunk.toString()) {\n // chunk still contains value\n // but not shifted - means no more available chars to shift\n if (!shiftChar) break;\n ++ci;\n } else {\n // clean if chunk has no value\n this.chunks.splice(ci, 1);\n }\n if (shiftChar) return shiftChar;\n }\n return '';\n }\n shift() {\n if (!this.chunks.length) return '';\n let ci = this.chunks.length - 1;\n while (0 <= ci) {\n const chunk = this.chunks[ci];\n const shiftChar = chunk.shift();\n if (chunk.toString()) {\n // chunk still contains value\n // but not shifted - means no more available chars to shift\n if (!shiftChar) break;\n --ci;\n } else {\n // clean if chunk has no value\n this.chunks.splice(ci, 1);\n }\n if (shiftChar) return shiftChar;\n }\n return '';\n }\n}\n\nexport { ChunksTailDetails as default };\n", "import { DIRECTION } from '../../core/utils.js';\n\nclass PatternCursor {\n constructor(masked, pos) {\n this.masked = masked;\n this._log = [];\n const {\n offset,\n index\n } = masked._mapPosToBlock(pos) || (pos < 0 ?\n // first\n {\n index: 0,\n offset: 0\n } :\n // last\n {\n index: this.masked._blocks.length,\n offset: 0\n });\n this.offset = offset;\n this.index = index;\n this.ok = false;\n }\n get block() {\n return this.masked._blocks[this.index];\n }\n get pos() {\n return this.masked._blockStartPos(this.index) + this.offset;\n }\n get state() {\n return {\n index: this.index,\n offset: this.offset,\n ok: this.ok\n };\n }\n set state(s) {\n Object.assign(this, s);\n }\n pushState() {\n this._log.push(this.state);\n }\n popState() {\n const s = this._log.pop();\n if (s) this.state = s;\n return s;\n }\n bindBlock() {\n if (this.block) return;\n if (this.index < 0) {\n this.index = 0;\n this.offset = 0;\n }\n if (this.index >= this.masked._blocks.length) {\n this.index = this.masked._blocks.length - 1;\n this.offset = this.block.displayValue.length; // TODO this is stupid type error, `block` depends on index that was changed above\n }\n }\n _pushLeft(fn) {\n this.pushState();\n for (this.bindBlock(); 0 <= this.index; --this.index, this.offset = ((_this$block = this.block) == null ? void 0 : _this$block.displayValue.length) || 0) {\n var _this$block;\n if (fn()) return this.ok = true;\n }\n return this.ok = false;\n }\n _pushRight(fn) {\n this.pushState();\n for (this.bindBlock(); this.index < this.masked._blocks.length; ++this.index, this.offset = 0) {\n if (fn()) return this.ok = true;\n }\n return this.ok = false;\n }\n pushLeftBeforeFilled() {\n return this._pushLeft(() => {\n if (this.block.isFixed || !this.block.value) return;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.FORCE_LEFT);\n if (this.offset !== 0) return true;\n });\n }\n pushLeftBeforeInput() {\n // cases:\n // filled input: 00|\n // optional empty input: 00[]|\n // nested block: XX<[]>|\n return this._pushLeft(() => {\n if (this.block.isFixed) return;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.LEFT);\n return true;\n });\n }\n pushLeftBeforeRequired() {\n return this._pushLeft(() => {\n if (this.block.isFixed || this.block.isOptional && !this.block.value) return;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.LEFT);\n return true;\n });\n }\n pushRightBeforeFilled() {\n return this._pushRight(() => {\n if (this.block.isFixed || !this.block.value) return;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.FORCE_RIGHT);\n if (this.offset !== this.block.value.length) return true;\n });\n }\n pushRightBeforeInput() {\n return this._pushRight(() => {\n if (this.block.isFixed) return;\n\n // const o = this.offset;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.NONE);\n // HACK cases like (STILL DOES NOT WORK FOR NESTED)\n // aa|X\n // aaX_ - this will not work\n // if (o && o === this.offset && this.block instanceof PatternInputDefinition) continue;\n return true;\n });\n }\n pushRightBeforeRequired() {\n return this._pushRight(() => {\n if (this.block.isFixed || this.block.isOptional && !this.block.value) return;\n\n // TODO check |[*]XX_\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.NONE);\n return true;\n });\n }\n}\n\nexport { PatternCursor as default };\n", "import ChangeDetails from '../../core/change-details.js';\nimport { DIRECTION, isString } from '../../core/utils.js';\nimport ContinuousTailDetails from '../../core/continuous-tail-details.js';\nimport '../../core/holder.js';\n\nclass PatternFixedDefinition {\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n constructor(opts) {\n Object.assign(this, opts);\n this._value = '';\n this.isFixed = true;\n }\n get value() {\n return this._value;\n }\n get unmaskedValue() {\n return this.isUnmasking ? this.value : '';\n }\n get rawInputValue() {\n return this._isRawInput ? this.value : '';\n }\n get displayValue() {\n return this.value;\n }\n reset() {\n this._isRawInput = false;\n this._value = '';\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this._value.length;\n }\n this._value = this._value.slice(0, fromPos) + this._value.slice(toPos);\n if (!this._value) this._isRawInput = false;\n return new ChangeDetails();\n }\n nearestInputPos(cursorPos, direction) {\n if (direction === void 0) {\n direction = DIRECTION.NONE;\n }\n const minPos = 0;\n const maxPos = this._value.length;\n switch (direction) {\n case DIRECTION.LEFT:\n case DIRECTION.FORCE_LEFT:\n return minPos;\n case DIRECTION.NONE:\n case DIRECTION.RIGHT:\n case DIRECTION.FORCE_RIGHT:\n default:\n return maxPos;\n }\n }\n totalInputPositions(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this._value.length;\n }\n return this._isRawInput ? toPos - fromPos : 0;\n }\n extractInput(fromPos, toPos, flags) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this._value.length;\n }\n if (flags === void 0) {\n flags = {};\n }\n return flags.raw && this._isRawInput && this._value.slice(fromPos, toPos) || '';\n }\n get isComplete() {\n return true;\n }\n get isFilled() {\n return Boolean(this._value);\n }\n _appendChar(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n if (this.isFilled) return new ChangeDetails();\n const appendEager = this.eager === true || this.eager === 'append';\n const appended = this.char === ch;\n const isResolved = appended && (this.isUnmasking || flags.input || flags.raw) && (!flags.raw || !appendEager) && !flags.tail;\n const details = new ChangeDetails({\n inserted: this.char,\n rawInserted: isResolved ? this.char : ''\n });\n this._value = this.char;\n this._isRawInput = isResolved && (flags.raw || flags.input);\n return details;\n }\n _appendEager() {\n return this._appendChar(this.char, {\n tail: true\n });\n }\n _appendPlaceholder() {\n const details = new ChangeDetails();\n if (this.isFilled) return details;\n this._value = details.inserted = this.char;\n return details;\n }\n extractTail() {\n return new ContinuousTailDetails('');\n }\n appendTail(tail) {\n if (isString(tail)) tail = new ContinuousTailDetails(String(tail));\n return tail.appendTo(this);\n }\n append(str, flags, tail) {\n const details = this._appendChar(str[0], flags);\n if (tail != null) {\n details.tailShift += this.appendTail(tail).tailShift;\n }\n return details;\n }\n doCommit() {}\n get state() {\n return {\n _value: this._value,\n _rawInputValue: this.rawInputValue\n };\n }\n set state(state) {\n this._value = state._value;\n this._isRawInput = Boolean(state._rawInputValue);\n }\n pad(flags) {\n return this._appendPlaceholder();\n }\n}\n\nexport { PatternFixedDefinition as default };\n", "import createMask from '../factory.js';\nimport ChangeDetails from '../../core/change-details.js';\nimport { DIRECTION } from '../../core/utils.js';\nimport '../../core/holder.js';\n\nclass PatternInputDefinition {\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n constructor(opts) {\n const {\n parent,\n isOptional,\n placeholderChar,\n displayChar,\n lazy,\n eager,\n ...maskOpts\n } = opts;\n this.masked = createMask(maskOpts);\n Object.assign(this, {\n parent,\n isOptional,\n placeholderChar,\n displayChar,\n lazy,\n eager\n });\n }\n reset() {\n this.isFilled = false;\n this.masked.reset();\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.value.length;\n }\n if (fromPos === 0 && toPos >= 1) {\n this.isFilled = false;\n return this.masked.remove(fromPos, toPos);\n }\n return new ChangeDetails();\n }\n get value() {\n return this.masked.value || (this.isFilled && !this.isOptional ? this.placeholderChar : '');\n }\n get unmaskedValue() {\n return this.masked.unmaskedValue;\n }\n get rawInputValue() {\n return this.masked.rawInputValue;\n }\n get displayValue() {\n return this.masked.value && this.displayChar || this.value;\n }\n get isComplete() {\n return Boolean(this.masked.value) || this.isOptional;\n }\n _appendChar(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n if (this.isFilled) return new ChangeDetails();\n const state = this.masked.state;\n // simulate input\n let details = this.masked._appendChar(ch, this.currentMaskFlags(flags));\n if (details.inserted && this.doValidate(flags) === false) {\n details = new ChangeDetails();\n this.masked.state = state;\n }\n if (!details.inserted && !this.isOptional && !this.lazy && !flags.input) {\n details.inserted = this.placeholderChar;\n }\n details.skip = !details.inserted && !this.isOptional;\n this.isFilled = Boolean(details.inserted);\n return details;\n }\n append(str, flags, tail) {\n // TODO probably should be done via _appendChar\n return this.masked.append(str, this.currentMaskFlags(flags), tail);\n }\n _appendPlaceholder() {\n if (this.isFilled || this.isOptional) return new ChangeDetails();\n this.isFilled = true;\n return new ChangeDetails({\n inserted: this.placeholderChar\n });\n }\n _appendEager() {\n return new ChangeDetails();\n }\n extractTail(fromPos, toPos) {\n return this.masked.extractTail(fromPos, toPos);\n }\n appendTail(tail) {\n return this.masked.appendTail(tail);\n }\n extractInput(fromPos, toPos, flags) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.value.length;\n }\n return this.masked.extractInput(fromPos, toPos, flags);\n }\n nearestInputPos(cursorPos, direction) {\n if (direction === void 0) {\n direction = DIRECTION.NONE;\n }\n const minPos = 0;\n const maxPos = this.value.length;\n const boundPos = Math.min(Math.max(cursorPos, minPos), maxPos);\n switch (direction) {\n case DIRECTION.LEFT:\n case DIRECTION.FORCE_LEFT:\n return this.isComplete ? boundPos : minPos;\n case DIRECTION.RIGHT:\n case DIRECTION.FORCE_RIGHT:\n return this.isComplete ? boundPos : maxPos;\n case DIRECTION.NONE:\n default:\n return boundPos;\n }\n }\n totalInputPositions(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.value.length;\n }\n return this.value.slice(fromPos, toPos).length;\n }\n doValidate(flags) {\n return this.masked.doValidate(this.currentMaskFlags(flags)) && (!this.parent || this.parent.doValidate(this.currentMaskFlags(flags)));\n }\n doCommit() {\n this.masked.doCommit();\n }\n get state() {\n return {\n _value: this.value,\n _rawInputValue: this.rawInputValue,\n masked: this.masked.state,\n isFilled: this.isFilled\n };\n }\n set state(state) {\n this.masked.state = state.masked;\n this.isFilled = state.isFilled;\n }\n currentMaskFlags(flags) {\n var _flags$_beforeTailSta;\n return {\n ...flags,\n _beforeTailState: (flags == null || (_flags$_beforeTailSta = flags._beforeTailState) == null ? void 0 : _flags$_beforeTailSta.masked) || (flags == null ? void 0 : flags._beforeTailState)\n };\n }\n pad(flags) {\n return new ChangeDetails();\n }\n}\nPatternInputDefinition.DEFAULT_DEFINITIONS = {\n '0': /\\d/,\n 'a': /[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]/,\n // http://stackoverflow.com/a/22075070\n '*': /./\n};\n\nexport { PatternInputDefinition as default };\n", "import Masked from './base.js';\nimport IMask from '../core/holder.js';\nimport '../core/change-details.js';\nimport '../core/continuous-tail-details.js';\nimport '../core/utils.js';\n\n/** Masking by RegExp */\nclass MaskedRegExp extends Masked {\n /** */\n\n /** Enable characters overwriting */\n\n /** */\n\n /** */\n\n /** */\n\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n const mask = opts.mask;\n if (mask) opts.validate = value => value.search(mask) >= 0;\n super._update(opts);\n }\n}\nIMask.MaskedRegExp = MaskedRegExp;\n\nexport { MaskedRegExp as default };\n", "import ChangeDetails from '../core/change-details.js';\nimport IMask from '../core/holder.js';\nimport { DIRECTION } from '../core/utils.js';\nimport Masked from './base.js';\nimport createMask, { normalizeOpts } from './factory.js';\nimport ChunksTailDetails from './pattern/chunk-tail-details.js';\nimport PatternCursor from './pattern/cursor.js';\nimport PatternFixedDefinition from './pattern/fixed-definition.js';\nimport PatternInputDefinition from './pattern/input-definition.js';\nimport './regexp.js';\nimport '../core/continuous-tail-details.js';\n\n/** Pattern mask */\nclass MaskedPattern extends Masked {\n /** */\n\n /** */\n\n /** Single char for empty input */\n\n /** Single char for filled input */\n\n /** Show placeholder only when needed */\n\n /** Enable characters overwriting */\n\n /** */\n\n /** */\n\n /** */\n\n constructor(opts) {\n super({\n ...MaskedPattern.DEFAULTS,\n ...opts,\n definitions: Object.assign({}, PatternInputDefinition.DEFAULT_DEFINITIONS, opts == null ? void 0 : opts.definitions)\n });\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n opts.definitions = Object.assign({}, this.definitions, opts.definitions);\n super._update(opts);\n this._rebuildMask();\n }\n _rebuildMask() {\n const defs = this.definitions;\n this._blocks = [];\n this.exposeBlock = undefined;\n this._stops = [];\n this._maskedBlocks = {};\n const pattern = this.mask;\n if (!pattern || !defs) return;\n let unmaskingBlock = false;\n let optionalBlock = false;\n for (let i = 0; i < pattern.length; ++i) {\n if (this.blocks) {\n const p = pattern.slice(i);\n const bNames = Object.keys(this.blocks).filter(bName => p.indexOf(bName) === 0);\n // order by key length\n bNames.sort((a, b) => b.length - a.length);\n // use block name with max length\n const bName = bNames[0];\n if (bName) {\n const {\n expose,\n repeat,\n ...bOpts\n } = normalizeOpts(this.blocks[bName]); // TODO type Opts\n const blockOpts = {\n lazy: this.lazy,\n eager: this.eager,\n placeholderChar: this.placeholderChar,\n displayChar: this.displayChar,\n overwrite: this.overwrite,\n autofix: this.autofix,\n ...bOpts,\n repeat,\n parent: this\n };\n const maskedBlock = repeat != null ? new IMask.RepeatBlock(blockOpts /* TODO */) : createMask(blockOpts);\n if (maskedBlock) {\n this._blocks.push(maskedBlock);\n if (expose) this.exposeBlock = maskedBlock;\n\n // store block index\n if (!this._maskedBlocks[bName]) this._maskedBlocks[bName] = [];\n this._maskedBlocks[bName].push(this._blocks.length - 1);\n }\n i += bName.length - 1;\n continue;\n }\n }\n let char = pattern[i];\n let isInput = (char in defs);\n if (char === MaskedPattern.STOP_CHAR) {\n this._stops.push(this._blocks.length);\n continue;\n }\n if (char === '{' || char === '}') {\n unmaskingBlock = !unmaskingBlock;\n continue;\n }\n if (char === '[' || char === ']') {\n optionalBlock = !optionalBlock;\n continue;\n }\n if (char === MaskedPattern.ESCAPE_CHAR) {\n ++i;\n char = pattern[i];\n if (!char) break;\n isInput = false;\n }\n const def = isInput ? new PatternInputDefinition({\n isOptional: optionalBlock,\n lazy: this.lazy,\n eager: this.eager,\n placeholderChar: this.placeholderChar,\n displayChar: this.displayChar,\n ...normalizeOpts(defs[char]),\n parent: this\n }) : new PatternFixedDefinition({\n char,\n eager: this.eager,\n isUnmasking: unmaskingBlock\n });\n this._blocks.push(def);\n }\n }\n get state() {\n return {\n ...super.state,\n _blocks: this._blocks.map(b => b.state)\n };\n }\n set state(state) {\n if (!state) {\n this.reset();\n return;\n }\n const {\n _blocks,\n ...maskedState\n } = state;\n this._blocks.forEach((b, bi) => b.state = _blocks[bi]);\n super.state = maskedState;\n }\n reset() {\n super.reset();\n this._blocks.forEach(b => b.reset());\n }\n get isComplete() {\n return this.exposeBlock ? this.exposeBlock.isComplete : this._blocks.every(b => b.isComplete);\n }\n get isFilled() {\n return this._blocks.every(b => b.isFilled);\n }\n get isFixed() {\n return this._blocks.every(b => b.isFixed);\n }\n get isOptional() {\n return this._blocks.every(b => b.isOptional);\n }\n doCommit() {\n this._blocks.forEach(b => b.doCommit());\n super.doCommit();\n }\n get unmaskedValue() {\n return this.exposeBlock ? this.exposeBlock.unmaskedValue : this._blocks.reduce((str, b) => str += b.unmaskedValue, '');\n }\n set unmaskedValue(unmaskedValue) {\n if (this.exposeBlock) {\n const tail = this.extractTail(this._blockStartPos(this._blocks.indexOf(this.exposeBlock)) + this.exposeBlock.displayValue.length);\n this.exposeBlock.unmaskedValue = unmaskedValue;\n this.appendTail(tail);\n this.doCommit();\n } else super.unmaskedValue = unmaskedValue;\n }\n get value() {\n return this.exposeBlock ? this.exposeBlock.value :\n // TODO return _value when not in change?\n this._blocks.reduce((str, b) => str += b.value, '');\n }\n set value(value) {\n if (this.exposeBlock) {\n const tail = this.extractTail(this._blockStartPos(this._blocks.indexOf(this.exposeBlock)) + this.exposeBlock.displayValue.length);\n this.exposeBlock.value = value;\n this.appendTail(tail);\n this.doCommit();\n } else super.value = value;\n }\n get typedValue() {\n return this.exposeBlock ? this.exposeBlock.typedValue : super.typedValue;\n }\n set typedValue(value) {\n if (this.exposeBlock) {\n const tail = this.extractTail(this._blockStartPos(this._blocks.indexOf(this.exposeBlock)) + this.exposeBlock.displayValue.length);\n this.exposeBlock.typedValue = value;\n this.appendTail(tail);\n this.doCommit();\n } else super.typedValue = value;\n }\n get displayValue() {\n return this._blocks.reduce((str, b) => str += b.displayValue, '');\n }\n appendTail(tail) {\n return super.appendTail(tail).aggregate(this._appendPlaceholder());\n }\n _appendEager() {\n var _this$_mapPosToBlock;\n const details = new ChangeDetails();\n let startBlockIndex = (_this$_mapPosToBlock = this._mapPosToBlock(this.displayValue.length)) == null ? void 0 : _this$_mapPosToBlock.index;\n if (startBlockIndex == null) return details;\n\n // TODO test if it works for nested pattern masks\n if (this._blocks[startBlockIndex].isFilled) ++startBlockIndex;\n for (let bi = startBlockIndex; bi < this._blocks.length; ++bi) {\n const d = this._blocks[bi]._appendEager();\n if (!d.inserted) break;\n details.aggregate(d);\n }\n return details;\n }\n _appendCharRaw(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n const blockIter = this._mapPosToBlock(this.displayValue.length);\n const details = new ChangeDetails();\n if (!blockIter) return details;\n for (let bi = blockIter.index, block; block = this._blocks[bi]; ++bi) {\n var _flags$_beforeTailSta;\n const blockDetails = block._appendChar(ch, {\n ...flags,\n _beforeTailState: (_flags$_beforeTailSta = flags._beforeTailState) == null || (_flags$_beforeTailSta = _flags$_beforeTailSta._blocks) == null ? void 0 : _flags$_beforeTailSta[bi]\n });\n details.aggregate(blockDetails);\n if (blockDetails.consumed) break; // go next char\n }\n return details;\n }\n extractTail(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n const chunkTail = new ChunksTailDetails();\n if (fromPos === toPos) return chunkTail;\n this._forEachBlocksInRange(fromPos, toPos, (b, bi, bFromPos, bToPos) => {\n const blockChunk = b.extractTail(bFromPos, bToPos);\n blockChunk.stop = this._findStopBefore(bi);\n blockChunk.from = this._blockStartPos(bi);\n if (blockChunk instanceof ChunksTailDetails) blockChunk.blockIndex = bi;\n chunkTail.extend(blockChunk);\n });\n return chunkTail;\n }\n extractInput(fromPos, toPos, flags) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n if (flags === void 0) {\n flags = {};\n }\n if (fromPos === toPos) return '';\n let input = '';\n this._forEachBlocksInRange(fromPos, toPos, (b, _, fromPos, toPos) => {\n input += b.extractInput(fromPos, toPos, flags);\n });\n return input;\n }\n _findStopBefore(blockIndex) {\n let stopBefore;\n for (let si = 0; si < this._stops.length; ++si) {\n const stop = this._stops[si];\n if (stop <= blockIndex) stopBefore = stop;else break;\n }\n return stopBefore;\n }\n\n /** Appends placeholder depending on laziness */\n _appendPlaceholder(toBlockIndex) {\n const details = new ChangeDetails();\n if (this.lazy && toBlockIndex == null) return details;\n const startBlockIter = this._mapPosToBlock(this.displayValue.length);\n if (!startBlockIter) return details;\n const startBlockIndex = startBlockIter.index;\n const endBlockIndex = toBlockIndex != null ? toBlockIndex : this._blocks.length;\n this._blocks.slice(startBlockIndex, endBlockIndex).forEach(b => {\n if (!b.lazy || toBlockIndex != null) {\n var _blocks2;\n details.aggregate(b._appendPlaceholder((_blocks2 = b._blocks) == null ? void 0 : _blocks2.length));\n }\n });\n return details;\n }\n\n /** Finds block in pos */\n _mapPosToBlock(pos) {\n let accVal = '';\n for (let bi = 0; bi < this._blocks.length; ++bi) {\n const block = this._blocks[bi];\n const blockStartPos = accVal.length;\n accVal += block.displayValue;\n if (pos <= accVal.length) {\n return {\n index: bi,\n offset: pos - blockStartPos\n };\n }\n }\n }\n _blockStartPos(blockIndex) {\n return this._blocks.slice(0, blockIndex).reduce((pos, b) => pos += b.displayValue.length, 0);\n }\n _forEachBlocksInRange(fromPos, toPos, fn) {\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n const fromBlockIter = this._mapPosToBlock(fromPos);\n if (fromBlockIter) {\n const toBlockIter = this._mapPosToBlock(toPos);\n // process first block\n const isSameBlock = toBlockIter && fromBlockIter.index === toBlockIter.index;\n const fromBlockStartPos = fromBlockIter.offset;\n const fromBlockEndPos = toBlockIter && isSameBlock ? toBlockIter.offset : this._blocks[fromBlockIter.index].displayValue.length;\n fn(this._blocks[fromBlockIter.index], fromBlockIter.index, fromBlockStartPos, fromBlockEndPos);\n if (toBlockIter && !isSameBlock) {\n // process intermediate blocks\n for (let bi = fromBlockIter.index + 1; bi < toBlockIter.index; ++bi) {\n fn(this._blocks[bi], bi, 0, this._blocks[bi].displayValue.length);\n }\n\n // process last block\n fn(this._blocks[toBlockIter.index], toBlockIter.index, 0, toBlockIter.offset);\n }\n }\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n const removeDetails = super.remove(fromPos, toPos);\n this._forEachBlocksInRange(fromPos, toPos, (b, _, bFromPos, bToPos) => {\n removeDetails.aggregate(b.remove(bFromPos, bToPos));\n });\n return removeDetails;\n }\n nearestInputPos(cursorPos, direction) {\n if (direction === void 0) {\n direction = DIRECTION.NONE;\n }\n if (!this._blocks.length) return 0;\n const cursor = new PatternCursor(this, cursorPos);\n if (direction === DIRECTION.NONE) {\n // -------------------------------------------------\n // NONE should only go out from fixed to the right!\n // -------------------------------------------------\n if (cursor.pushRightBeforeInput()) return cursor.pos;\n cursor.popState();\n if (cursor.pushLeftBeforeInput()) return cursor.pos;\n return this.displayValue.length;\n }\n\n // FORCE is only about a|* otherwise is 0\n if (direction === DIRECTION.LEFT || direction === DIRECTION.FORCE_LEFT) {\n // try to break fast when *|a\n if (direction === DIRECTION.LEFT) {\n cursor.pushRightBeforeFilled();\n if (cursor.ok && cursor.pos === cursorPos) return cursorPos;\n cursor.popState();\n }\n\n // forward flow\n cursor.pushLeftBeforeInput();\n cursor.pushLeftBeforeRequired();\n cursor.pushLeftBeforeFilled();\n\n // backward flow\n if (direction === DIRECTION.LEFT) {\n cursor.pushRightBeforeInput();\n cursor.pushRightBeforeRequired();\n if (cursor.ok && cursor.pos <= cursorPos) return cursor.pos;\n cursor.popState();\n if (cursor.ok && cursor.pos <= cursorPos) return cursor.pos;\n cursor.popState();\n }\n if (cursor.ok) return cursor.pos;\n if (direction === DIRECTION.FORCE_LEFT) return 0;\n cursor.popState();\n if (cursor.ok) return cursor.pos;\n cursor.popState();\n if (cursor.ok) return cursor.pos;\n return 0;\n }\n if (direction === DIRECTION.RIGHT || direction === DIRECTION.FORCE_RIGHT) {\n // forward flow\n cursor.pushRightBeforeInput();\n cursor.pushRightBeforeRequired();\n if (cursor.pushRightBeforeFilled()) return cursor.pos;\n if (direction === DIRECTION.FORCE_RIGHT) return this.displayValue.length;\n\n // backward flow\n cursor.popState();\n if (cursor.ok) return cursor.pos;\n cursor.popState();\n if (cursor.ok) return cursor.pos;\n return this.nearestInputPos(cursorPos, DIRECTION.LEFT);\n }\n return cursorPos;\n }\n totalInputPositions(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n let total = 0;\n this._forEachBlocksInRange(fromPos, toPos, (b, _, bFromPos, bToPos) => {\n total += b.totalInputPositions(bFromPos, bToPos);\n });\n return total;\n }\n\n /** Get block by name */\n maskedBlock(name) {\n return this.maskedBlocks(name)[0];\n }\n\n /** Get all blocks by name */\n maskedBlocks(name) {\n const indices = this._maskedBlocks[name];\n if (!indices) return [];\n return indices.map(gi => this._blocks[gi]);\n }\n pad(flags) {\n const details = new ChangeDetails();\n this._forEachBlocksInRange(0, this.displayValue.length, b => details.aggregate(b.pad(flags)));\n return details;\n }\n}\nMaskedPattern.DEFAULTS = {\n ...Masked.DEFAULTS,\n lazy: true,\n placeholderChar: '_'\n};\nMaskedPattern.STOP_CHAR = '`';\nMaskedPattern.ESCAPE_CHAR = '\\\\';\nMaskedPattern.InputDefinition = PatternInputDefinition;\nMaskedPattern.FixedDefinition = PatternFixedDefinition;\nIMask.MaskedPattern = MaskedPattern;\n\nexport { MaskedPattern as default };\n", "import ChangeDetails from '../core/change-details.js';\nimport IMask from '../core/holder.js';\nimport MaskedPattern from './pattern.js';\nimport '../core/utils.js';\nimport './base.js';\nimport '../core/continuous-tail-details.js';\nimport './factory.js';\nimport './pattern/chunk-tail-details.js';\nimport './pattern/cursor.js';\nimport './pattern/fixed-definition.js';\nimport './pattern/input-definition.js';\nimport './regexp.js';\n\n/** Pattern which accepts ranges */\nclass MaskedRange extends MaskedPattern {\n /**\n Optionally sets max length of pattern.\n Used when pattern length is longer then `to` param length. Pads zeros at start in this case.\n */\n\n /** Min bound */\n\n /** Max bound */\n\n get _matchFrom() {\n return this.maxLength - String(this.from).length;\n }\n constructor(opts) {\n super(opts); // mask will be created in _update\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n const {\n to = this.to || 0,\n from = this.from || 0,\n maxLength = this.maxLength || 0,\n autofix = this.autofix,\n ...patternOpts\n } = opts;\n this.to = to;\n this.from = from;\n this.maxLength = Math.max(String(to).length, maxLength);\n this.autofix = autofix;\n const fromStr = String(this.from).padStart(this.maxLength, '0');\n const toStr = String(this.to).padStart(this.maxLength, '0');\n let sameCharsCount = 0;\n while (sameCharsCount < toStr.length && toStr[sameCharsCount] === fromStr[sameCharsCount]) ++sameCharsCount;\n patternOpts.mask = toStr.slice(0, sameCharsCount).replace(/0/g, '\\\\0') + '0'.repeat(this.maxLength - sameCharsCount);\n super._update(patternOpts);\n }\n get isComplete() {\n return super.isComplete && Boolean(this.value);\n }\n boundaries(str) {\n let minstr = '';\n let maxstr = '';\n const [, placeholder, num] = str.match(/^(\\D*)(\\d*)(\\D*)/) || [];\n if (num) {\n minstr = '0'.repeat(placeholder.length) + num;\n maxstr = '9'.repeat(placeholder.length) + num;\n }\n minstr = minstr.padEnd(this.maxLength, '0');\n maxstr = maxstr.padEnd(this.maxLength, '9');\n return [minstr, maxstr];\n }\n doPrepareChar(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n let details;\n [ch, details] = super.doPrepareChar(ch.replace(/\\D/g, ''), flags);\n if (!ch) details.skip = !this.isComplete;\n return [ch, details];\n }\n _appendCharRaw(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n if (!this.autofix || this.value.length + 1 > this.maxLength) return super._appendCharRaw(ch, flags);\n const fromStr = String(this.from).padStart(this.maxLength, '0');\n const toStr = String(this.to).padStart(this.maxLength, '0');\n const [minstr, maxstr] = this.boundaries(this.value + ch);\n if (Number(maxstr) < this.from) return super._appendCharRaw(fromStr[this.value.length], flags);\n if (Number(minstr) > this.to) {\n if (!flags.tail && this.autofix === 'pad' && this.value.length + 1 < this.maxLength) {\n return super._appendCharRaw(fromStr[this.value.length], flags).aggregate(this._appendCharRaw(ch, flags));\n }\n return super._appendCharRaw(toStr[this.value.length], flags);\n }\n return super._appendCharRaw(ch, flags);\n }\n doValidate(flags) {\n const str = this.value;\n const firstNonZero = str.search(/[^0]/);\n if (firstNonZero === -1 && str.length <= this._matchFrom) return true;\n const [minstr, maxstr] = this.boundaries(str);\n return this.from <= Number(maxstr) && Number(minstr) <= this.to && super.doValidate(flags);\n }\n pad(flags) {\n const details = new ChangeDetails();\n if (this.value.length === this.maxLength) return details;\n const value = this.value;\n const padLength = this.maxLength - this.value.length;\n if (padLength) {\n this.reset();\n for (let i = 0; i < padLength; ++i) {\n details.aggregate(super._appendCharRaw('0', flags));\n }\n\n // append tail\n value.split('').forEach(ch => this._appendCharRaw(ch));\n }\n return details;\n }\n}\nIMask.MaskedRange = MaskedRange;\n\nexport { MaskedRange as default };\n", "import MaskedPattern from './pattern.js';\nimport MaskedRange from './range.js';\nimport IMask from '../core/holder.js';\nimport { isString } from '../core/utils.js';\nimport '../core/change-details.js';\nimport './base.js';\nimport '../core/continuous-tail-details.js';\nimport './factory.js';\nimport './pattern/chunk-tail-details.js';\nimport './pattern/cursor.js';\nimport './pattern/fixed-definition.js';\nimport './pattern/input-definition.js';\nimport './regexp.js';\n\nconst DefaultPattern = 'd{.}`m{.}`Y';\n\n// Make format and parse required when pattern is provided\n\n/** Date mask */\nclass MaskedDate extends MaskedPattern {\n static extractPatternOptions(opts) {\n const {\n mask,\n pattern,\n ...patternOpts\n } = opts;\n return {\n ...patternOpts,\n mask: isString(mask) ? mask : pattern\n };\n }\n\n /** Pattern mask for date according to {@link MaskedDate#format} */\n\n /** Start date */\n\n /** End date */\n\n /** Format typed value to string */\n\n /** Parse string to get typed value */\n\n constructor(opts) {\n super(MaskedDate.extractPatternOptions({\n ...MaskedDate.DEFAULTS,\n ...opts\n }));\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n const {\n mask,\n pattern,\n blocks,\n ...patternOpts\n } = {\n ...MaskedDate.DEFAULTS,\n ...opts\n };\n const patternBlocks = Object.assign({}, MaskedDate.GET_DEFAULT_BLOCKS());\n // adjust year block\n if (opts.min) patternBlocks.Y.from = opts.min.getFullYear();\n if (opts.max) patternBlocks.Y.to = opts.max.getFullYear();\n if (opts.min && opts.max && patternBlocks.Y.from === patternBlocks.Y.to) {\n patternBlocks.m.from = opts.min.getMonth() + 1;\n patternBlocks.m.to = opts.max.getMonth() + 1;\n if (patternBlocks.m.from === patternBlocks.m.to) {\n patternBlocks.d.from = opts.min.getDate();\n patternBlocks.d.to = opts.max.getDate();\n }\n }\n Object.assign(patternBlocks, this.blocks, blocks);\n super._update({\n ...patternOpts,\n mask: isString(mask) ? mask : pattern,\n blocks: patternBlocks\n });\n }\n doValidate(flags) {\n const date = this.date;\n return super.doValidate(flags) && (!this.isComplete || this.isDateExist(this.value) && date != null && (this.min == null || this.min <= date) && (this.max == null || date <= this.max));\n }\n\n /** Checks if date is exists */\n isDateExist(str) {\n return this.format(this.parse(str, this), this).indexOf(str) >= 0;\n }\n\n /** Parsed Date */\n get date() {\n return this.typedValue;\n }\n set date(date) {\n this.typedValue = date;\n }\n get typedValue() {\n return this.isComplete ? super.typedValue : null;\n }\n set typedValue(value) {\n super.typedValue = value;\n }\n maskEquals(mask) {\n return mask === Date || super.maskEquals(mask);\n }\n optionsIsChanged(opts) {\n return super.optionsIsChanged(MaskedDate.extractPatternOptions(opts));\n }\n}\nMaskedDate.GET_DEFAULT_BLOCKS = () => ({\n d: {\n mask: MaskedRange,\n from: 1,\n to: 31,\n maxLength: 2\n },\n m: {\n mask: MaskedRange,\n from: 1,\n to: 12,\n maxLength: 2\n },\n Y: {\n mask: MaskedRange,\n from: 1900,\n to: 9999\n }\n});\nMaskedDate.DEFAULTS = {\n ...MaskedPattern.DEFAULTS,\n mask: Date,\n pattern: DefaultPattern,\n format: (date, masked) => {\n if (!date) return '';\n const day = String(date.getDate()).padStart(2, '0');\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const year = date.getFullYear();\n return [day, month, year].join('.');\n },\n parse: (str, masked) => {\n const [day, month, year] = str.split('.').map(Number);\n return new Date(year, month - 1, day);\n }\n};\nIMask.MaskedDate = MaskedDate;\n\nexport { MaskedDate as default };\n", "import { DIRECTION, objectIncludes } from '../core/utils.js';\nimport ChangeDetails from '../core/change-details.js';\nimport createMask, { normalizeOpts } from './factory.js';\nimport Masked from './base.js';\nimport IMask from '../core/holder.js';\nimport '../core/continuous-tail-details.js';\n\n/** Dynamic mask for choosing appropriate mask in run-time */\nclass MaskedDynamic extends Masked {\n constructor(opts) {\n super({\n ...MaskedDynamic.DEFAULTS,\n ...opts\n });\n this.currentMask = undefined;\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n super._update(opts);\n if ('mask' in opts) {\n this.exposeMask = undefined;\n // mask could be totally dynamic with only `dispatch` option\n this.compiledMasks = Array.isArray(opts.mask) ? opts.mask.map(m => {\n const {\n expose,\n ...maskOpts\n } = normalizeOpts(m);\n const masked = createMask({\n overwrite: this._overwrite,\n eager: this._eager,\n skipInvalid: this._skipInvalid,\n ...maskOpts\n });\n if (expose) this.exposeMask = masked;\n return masked;\n }) : [];\n\n // this.currentMask = this.doDispatch(''); // probably not needed but lets see\n }\n }\n _appendCharRaw(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n const details = this._applyDispatch(ch, flags);\n if (this.currentMask) {\n details.aggregate(this.currentMask._appendChar(ch, this.currentMaskFlags(flags)));\n }\n return details;\n }\n _applyDispatch(appended, flags, tail) {\n if (appended === void 0) {\n appended = '';\n }\n if (flags === void 0) {\n flags = {};\n }\n if (tail === void 0) {\n tail = '';\n }\n const prevValueBeforeTail = flags.tail && flags._beforeTailState != null ? flags._beforeTailState._value : this.value;\n const inputValue = this.rawInputValue;\n const insertValue = flags.tail && flags._beforeTailState != null ? flags._beforeTailState._rawInputValue : inputValue;\n const tailValue = inputValue.slice(insertValue.length);\n const prevMask = this.currentMask;\n const details = new ChangeDetails();\n const prevMaskState = prevMask == null ? void 0 : prevMask.state;\n\n // clone flags to prevent overwriting `_beforeTailState`\n this.currentMask = this.doDispatch(appended, {\n ...flags\n }, tail);\n\n // restore state after dispatch\n if (this.currentMask) {\n if (this.currentMask !== prevMask) {\n // if mask changed reapply input\n this.currentMask.reset();\n if (insertValue) {\n this.currentMask.append(insertValue, {\n raw: true\n });\n details.tailShift = this.currentMask.value.length - prevValueBeforeTail.length;\n }\n if (tailValue) {\n details.tailShift += this.currentMask.append(tailValue, {\n raw: true,\n tail: true\n }).tailShift;\n }\n } else if (prevMaskState) {\n // Dispatch can do something bad with state, so\n // restore prev mask state\n this.currentMask.state = prevMaskState;\n }\n }\n return details;\n }\n _appendPlaceholder() {\n const details = this._applyDispatch();\n if (this.currentMask) {\n details.aggregate(this.currentMask._appendPlaceholder());\n }\n return details;\n }\n _appendEager() {\n const details = this._applyDispatch();\n if (this.currentMask) {\n details.aggregate(this.currentMask._appendEager());\n }\n return details;\n }\n appendTail(tail) {\n const details = new ChangeDetails();\n if (tail) details.aggregate(this._applyDispatch('', {}, tail));\n return details.aggregate(this.currentMask ? this.currentMask.appendTail(tail) : super.appendTail(tail));\n }\n currentMaskFlags(flags) {\n var _flags$_beforeTailSta, _flags$_beforeTailSta2;\n return {\n ...flags,\n _beforeTailState: ((_flags$_beforeTailSta = flags._beforeTailState) == null ? void 0 : _flags$_beforeTailSta.currentMaskRef) === this.currentMask && ((_flags$_beforeTailSta2 = flags._beforeTailState) == null ? void 0 : _flags$_beforeTailSta2.currentMask) || flags._beforeTailState\n };\n }\n doDispatch(appended, flags, tail) {\n if (flags === void 0) {\n flags = {};\n }\n if (tail === void 0) {\n tail = '';\n }\n return this.dispatch(appended, this, flags, tail);\n }\n doValidate(flags) {\n return super.doValidate(flags) && (!this.currentMask || this.currentMask.doValidate(this.currentMaskFlags(flags)));\n }\n doPrepare(str, flags) {\n if (flags === void 0) {\n flags = {};\n }\n let [s, details] = super.doPrepare(str, flags);\n if (this.currentMask) {\n let currentDetails;\n [s, currentDetails] = super.doPrepare(s, this.currentMaskFlags(flags));\n details = details.aggregate(currentDetails);\n }\n return [s, details];\n }\n doPrepareChar(str, flags) {\n if (flags === void 0) {\n flags = {};\n }\n let [s, details] = super.doPrepareChar(str, flags);\n if (this.currentMask) {\n let currentDetails;\n [s, currentDetails] = super.doPrepareChar(s, this.currentMaskFlags(flags));\n details = details.aggregate(currentDetails);\n }\n return [s, details];\n }\n reset() {\n var _this$currentMask;\n (_this$currentMask = this.currentMask) == null || _this$currentMask.reset();\n this.compiledMasks.forEach(m => m.reset());\n }\n get value() {\n return this.exposeMask ? this.exposeMask.value : this.currentMask ? this.currentMask.value : '';\n }\n set value(value) {\n if (this.exposeMask) {\n this.exposeMask.value = value;\n this.currentMask = this.exposeMask;\n this._applyDispatch();\n } else super.value = value;\n }\n get unmaskedValue() {\n return this.exposeMask ? this.exposeMask.unmaskedValue : this.currentMask ? this.currentMask.unmaskedValue : '';\n }\n set unmaskedValue(unmaskedValue) {\n if (this.exposeMask) {\n this.exposeMask.unmaskedValue = unmaskedValue;\n this.currentMask = this.exposeMask;\n this._applyDispatch();\n } else super.unmaskedValue = unmaskedValue;\n }\n get typedValue() {\n return this.exposeMask ? this.exposeMask.typedValue : this.currentMask ? this.currentMask.typedValue : '';\n }\n set typedValue(typedValue) {\n if (this.exposeMask) {\n this.exposeMask.typedValue = typedValue;\n this.currentMask = this.exposeMask;\n this._applyDispatch();\n return;\n }\n let unmaskedValue = String(typedValue);\n\n // double check it\n if (this.currentMask) {\n this.currentMask.typedValue = typedValue;\n unmaskedValue = this.currentMask.unmaskedValue;\n }\n this.unmaskedValue = unmaskedValue;\n }\n get displayValue() {\n return this.currentMask ? this.currentMask.displayValue : '';\n }\n get isComplete() {\n var _this$currentMask2;\n return Boolean((_this$currentMask2 = this.currentMask) == null ? void 0 : _this$currentMask2.isComplete);\n }\n get isFilled() {\n var _this$currentMask3;\n return Boolean((_this$currentMask3 = this.currentMask) == null ? void 0 : _this$currentMask3.isFilled);\n }\n remove(fromPos, toPos) {\n const details = new ChangeDetails();\n if (this.currentMask) {\n details.aggregate(this.currentMask.remove(fromPos, toPos))\n // update with dispatch\n .aggregate(this._applyDispatch());\n }\n return details;\n }\n get state() {\n var _this$currentMask4;\n return {\n ...super.state,\n _rawInputValue: this.rawInputValue,\n compiledMasks: this.compiledMasks.map(m => m.state),\n currentMaskRef: this.currentMask,\n currentMask: (_this$currentMask4 = this.currentMask) == null ? void 0 : _this$currentMask4.state\n };\n }\n set state(state) {\n const {\n compiledMasks,\n currentMaskRef,\n currentMask,\n ...maskedState\n } = state;\n if (compiledMasks) this.compiledMasks.forEach((m, mi) => m.state = compiledMasks[mi]);\n if (currentMaskRef != null) {\n this.currentMask = currentMaskRef;\n this.currentMask.state = currentMask;\n }\n super.state = maskedState;\n }\n extractInput(fromPos, toPos, flags) {\n return this.currentMask ? this.currentMask.extractInput(fromPos, toPos, flags) : '';\n }\n extractTail(fromPos, toPos) {\n return this.currentMask ? this.currentMask.extractTail(fromPos, toPos) : super.extractTail(fromPos, toPos);\n }\n doCommit() {\n if (this.currentMask) this.currentMask.doCommit();\n super.doCommit();\n }\n nearestInputPos(cursorPos, direction) {\n return this.currentMask ? this.currentMask.nearestInputPos(cursorPos, direction) : super.nearestInputPos(cursorPos, direction);\n }\n get overwrite() {\n return this.currentMask ? this.currentMask.overwrite : this._overwrite;\n }\n set overwrite(overwrite) {\n this._overwrite = overwrite;\n }\n get eager() {\n return this.currentMask ? this.currentMask.eager : this._eager;\n }\n set eager(eager) {\n this._eager = eager;\n }\n get skipInvalid() {\n return this.currentMask ? this.currentMask.skipInvalid : this._skipInvalid;\n }\n set skipInvalid(skipInvalid) {\n this._skipInvalid = skipInvalid;\n }\n get autofix() {\n return this.currentMask ? this.currentMask.autofix : this._autofix;\n }\n set autofix(autofix) {\n this._autofix = autofix;\n }\n maskEquals(mask) {\n return Array.isArray(mask) ? this.compiledMasks.every((m, mi) => {\n if (!mask[mi]) return;\n const {\n mask: oldMask,\n ...restOpts\n } = mask[mi];\n return objectIncludes(m, restOpts) && m.maskEquals(oldMask);\n }) : super.maskEquals(mask);\n }\n typedValueEquals(value) {\n var _this$currentMask5;\n return Boolean((_this$currentMask5 = this.currentMask) == null ? void 0 : _this$currentMask5.typedValueEquals(value));\n }\n}\n/** Currently chosen mask */\n/** Currently chosen mask */\n/** Compliled {@link Masked} options */\n/** Chooses {@link Masked} depending on input value */\nMaskedDynamic.DEFAULTS = {\n ...Masked.DEFAULTS,\n dispatch: (appended, masked, flags, tail) => {\n if (!masked.compiledMasks.length) return;\n const inputValue = masked.rawInputValue;\n\n // simulate input\n const inputs = masked.compiledMasks.map((m, index) => {\n const isCurrent = masked.currentMask === m;\n const startInputPos = isCurrent ? m.displayValue.length : m.nearestInputPos(m.displayValue.length, DIRECTION.FORCE_LEFT);\n if (m.rawInputValue !== inputValue) {\n m.reset();\n m.append(inputValue, {\n raw: true\n });\n } else if (!isCurrent) {\n m.remove(startInputPos);\n }\n m.append(appended, masked.currentMaskFlags(flags));\n m.appendTail(tail);\n return {\n index,\n weight: m.rawInputValue.length,\n totalInputPositions: m.totalInputPositions(0, Math.max(startInputPos, m.nearestInputPos(m.displayValue.length, DIRECTION.FORCE_LEFT)))\n };\n });\n\n // pop masks with longer values first\n inputs.sort((i1, i2) => i2.weight - i1.weight || i2.totalInputPositions - i1.totalInputPositions);\n return masked.compiledMasks[inputs[0].index];\n }\n};\nIMask.MaskedDynamic = MaskedDynamic;\n\nexport { MaskedDynamic as default };\n", "import MaskedPattern from './pattern.js';\nimport IMask from '../core/holder.js';\nimport ChangeDetails from '../core/change-details.js';\nimport { DIRECTION } from '../core/utils.js';\nimport ContinuousTailDetails from '../core/continuous-tail-details.js';\nimport './base.js';\nimport './factory.js';\nimport './pattern/chunk-tail-details.js';\nimport './pattern/cursor.js';\nimport './pattern/fixed-definition.js';\nimport './pattern/input-definition.js';\nimport './regexp.js';\n\n/** Pattern which validates enum values */\nclass MaskedEnum extends MaskedPattern {\n constructor(opts) {\n super({\n ...MaskedEnum.DEFAULTS,\n ...opts\n }); // mask will be created in _update\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n const {\n enum: enum_,\n ...eopts\n } = opts;\n if (enum_) {\n const lengths = enum_.map(e => e.length);\n const requiredLength = Math.min(...lengths);\n const optionalLength = Math.max(...lengths) - requiredLength;\n eopts.mask = '*'.repeat(requiredLength);\n if (optionalLength) eopts.mask += '[' + '*'.repeat(optionalLength) + ']';\n this.enum = enum_;\n }\n super._update(eopts);\n }\n _appendCharRaw(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n const matchFrom = Math.min(this.nearestInputPos(0, DIRECTION.FORCE_RIGHT), this.value.length);\n const matches = this.enum.filter(e => this.matchValue(e, this.unmaskedValue + ch, matchFrom));\n if (matches.length) {\n if (matches.length === 1) {\n this._forEachBlocksInRange(0, this.value.length, (b, bi) => {\n const mch = matches[0][bi];\n if (bi >= this.value.length || mch === b.value) return;\n b.reset();\n b._appendChar(mch, flags);\n });\n }\n const d = super._appendCharRaw(matches[0][this.value.length], flags);\n if (matches.length === 1) {\n matches[0].slice(this.unmaskedValue.length).split('').forEach(mch => d.aggregate(super._appendCharRaw(mch)));\n }\n return d;\n }\n return new ChangeDetails({\n skip: !this.isComplete\n });\n }\n extractTail(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n // just drop tail\n return new ContinuousTailDetails('', fromPos);\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n if (fromPos === toPos) return new ChangeDetails();\n const matchFrom = Math.min(super.nearestInputPos(0, DIRECTION.FORCE_RIGHT), this.value.length);\n let pos;\n for (pos = fromPos; pos >= 0; --pos) {\n const matches = this.enum.filter(e => this.matchValue(e, this.value.slice(matchFrom, pos), matchFrom));\n if (matches.length > 1) break;\n }\n const details = super.remove(pos, toPos);\n details.tailShift += pos - fromPos;\n return details;\n }\n get isComplete() {\n return this.enum.indexOf(this.value) >= 0;\n }\n}\n/** Match enum value */\nMaskedEnum.DEFAULTS = {\n ...MaskedPattern.DEFAULTS,\n matchValue: (estr, istr, matchFrom) => estr.indexOf(istr, matchFrom) === matchFrom\n};\nIMask.MaskedEnum = MaskedEnum;\n\nexport { MaskedEnum as default };\n", "import Masked from './base.js';\nimport IMask from '../core/holder.js';\nimport '../core/change-details.js';\nimport '../core/continuous-tail-details.js';\nimport '../core/utils.js';\n\n/** Masking by custom Function */\nclass MaskedFunction extends Masked {\n /** */\n\n /** Enable characters overwriting */\n\n /** */\n\n /** */\n\n /** */\n\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n super._update({\n ...opts,\n validate: opts.mask\n });\n }\n}\nIMask.MaskedFunction = MaskedFunction;\n\nexport { MaskedFunction as default };\n", "import { escapeRegExp, DIRECTION } from '../core/utils.js';\nimport ChangeDetails from '../core/change-details.js';\nimport Masked from './base.js';\nimport IMask from '../core/holder.js';\nimport '../core/continuous-tail-details.js';\n\nvar _MaskedNumber;\n/** Number mask */\nclass MaskedNumber extends Masked {\n /** Single char */\n\n /** Single char */\n\n /** Array of single chars */\n\n /** */\n\n /** */\n\n /** Digits after point */\n\n /** Flag to remove leading and trailing zeros in the end of editing */\n\n /** Flag to pad trailing zeros after point in the end of editing */\n\n /** Enable characters overwriting */\n\n /** */\n\n /** */\n\n /** */\n\n /** Format typed value to string */\n\n /** Parse string to get typed value */\n\n constructor(opts) {\n super({\n ...MaskedNumber.DEFAULTS,\n ...opts\n });\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n super._update(opts);\n this._updateRegExps();\n }\n _updateRegExps() {\n const start = '^' + (this.allowNegative ? '[+|\\\\-]?' : '');\n const mid = '\\\\d*';\n const end = (this.scale ? \"(\" + escapeRegExp(this.radix) + \"\\\\d{0,\" + this.scale + \"})?\" : '') + '$';\n this._numberRegExp = new RegExp(start + mid + end);\n this._mapToRadixRegExp = new RegExp(\"[\" + this.mapToRadix.map(escapeRegExp).join('') + \"]\", 'g');\n this._thousandsSeparatorRegExp = new RegExp(escapeRegExp(this.thousandsSeparator), 'g');\n }\n _removeThousandsSeparators(value) {\n return value.replace(this._thousandsSeparatorRegExp, '');\n }\n _insertThousandsSeparators(value) {\n // https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript\n const parts = value.split(this.radix);\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, this.thousandsSeparator);\n return parts.join(this.radix);\n }\n doPrepareChar(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n const [prepCh, details] = super.doPrepareChar(this._removeThousandsSeparators(this.scale && this.mapToRadix.length && (\n /*\n radix should be mapped when\n 1) input is done from keyboard = flags.input && flags.raw\n 2) unmasked value is set = !flags.input && !flags.raw\n and should not be mapped when\n 1) value is set = flags.input && !flags.raw\n 2) raw value is set = !flags.input && flags.raw\n */\n flags.input && flags.raw || !flags.input && !flags.raw) ? ch.replace(this._mapToRadixRegExp, this.radix) : ch), flags);\n if (ch && !prepCh) details.skip = true;\n if (prepCh && !this.allowPositive && !this.value && prepCh !== '-') details.aggregate(this._appendChar('-'));\n return [prepCh, details];\n }\n _separatorsCount(to, extendOnSeparators) {\n if (extendOnSeparators === void 0) {\n extendOnSeparators = false;\n }\n let count = 0;\n for (let pos = 0; pos < to; ++pos) {\n if (this._value.indexOf(this.thousandsSeparator, pos) === pos) {\n ++count;\n if (extendOnSeparators) to += this.thousandsSeparator.length;\n }\n }\n return count;\n }\n _separatorsCountFromSlice(slice) {\n if (slice === void 0) {\n slice = this._value;\n }\n return this._separatorsCount(this._removeThousandsSeparators(slice).length, true);\n }\n extractInput(fromPos, toPos, flags) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n [fromPos, toPos] = this._adjustRangeWithSeparators(fromPos, toPos);\n return this._removeThousandsSeparators(super.extractInput(fromPos, toPos, flags));\n }\n _appendCharRaw(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n const prevBeforeTailValue = flags.tail && flags._beforeTailState ? flags._beforeTailState._value : this._value;\n const prevBeforeTailSeparatorsCount = this._separatorsCountFromSlice(prevBeforeTailValue);\n this._value = this._removeThousandsSeparators(this.value);\n const oldValue = this._value;\n this._value += ch;\n const num = this.number;\n let accepted = !isNaN(num);\n let skip = false;\n if (accepted) {\n let fixedNum;\n if (this.min != null && this.min < 0 && this.number < this.min) fixedNum = this.min;\n if (this.max != null && this.max > 0 && this.number > this.max) fixedNum = this.max;\n if (fixedNum != null) {\n if (this.autofix) {\n this._value = this.format(fixedNum, this).replace(MaskedNumber.UNMASKED_RADIX, this.radix);\n skip || (skip = oldValue === this._value && !flags.tail); // if not changed on tail it's still ok to proceed\n } else {\n accepted = false;\n }\n }\n accepted && (accepted = Boolean(this._value.match(this._numberRegExp)));\n }\n let appendDetails;\n if (!accepted) {\n this._value = oldValue;\n appendDetails = new ChangeDetails();\n } else {\n appendDetails = new ChangeDetails({\n inserted: this._value.slice(oldValue.length),\n rawInserted: skip ? '' : ch,\n skip\n });\n }\n this._value = this._insertThousandsSeparators(this._value);\n const beforeTailValue = flags.tail && flags._beforeTailState ? flags._beforeTailState._value : this._value;\n const beforeTailSeparatorsCount = this._separatorsCountFromSlice(beforeTailValue);\n appendDetails.tailShift += (beforeTailSeparatorsCount - prevBeforeTailSeparatorsCount) * this.thousandsSeparator.length;\n return appendDetails;\n }\n _findSeparatorAround(pos) {\n if (this.thousandsSeparator) {\n const searchFrom = pos - this.thousandsSeparator.length + 1;\n const separatorPos = this.value.indexOf(this.thousandsSeparator, searchFrom);\n if (separatorPos <= pos) return separatorPos;\n }\n return -1;\n }\n _adjustRangeWithSeparators(from, to) {\n const separatorAroundFromPos = this._findSeparatorAround(from);\n if (separatorAroundFromPos >= 0) from = separatorAroundFromPos;\n const separatorAroundToPos = this._findSeparatorAround(to);\n if (separatorAroundToPos >= 0) to = separatorAroundToPos + this.thousandsSeparator.length;\n return [from, to];\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n [fromPos, toPos] = this._adjustRangeWithSeparators(fromPos, toPos);\n const valueBeforePos = this.value.slice(0, fromPos);\n const valueAfterPos = this.value.slice(toPos);\n const prevBeforeTailSeparatorsCount = this._separatorsCount(valueBeforePos.length);\n this._value = this._insertThousandsSeparators(this._removeThousandsSeparators(valueBeforePos + valueAfterPos));\n const beforeTailSeparatorsCount = this._separatorsCountFromSlice(valueBeforePos);\n return new ChangeDetails({\n tailShift: (beforeTailSeparatorsCount - prevBeforeTailSeparatorsCount) * this.thousandsSeparator.length\n });\n }\n nearestInputPos(cursorPos, direction) {\n if (!this.thousandsSeparator) return cursorPos;\n switch (direction) {\n case DIRECTION.NONE:\n case DIRECTION.LEFT:\n case DIRECTION.FORCE_LEFT:\n {\n const separatorAtLeftPos = this._findSeparatorAround(cursorPos - 1);\n if (separatorAtLeftPos >= 0) {\n const separatorAtLeftEndPos = separatorAtLeftPos + this.thousandsSeparator.length;\n if (cursorPos < separatorAtLeftEndPos || this.value.length <= separatorAtLeftEndPos || direction === DIRECTION.FORCE_LEFT) {\n return separatorAtLeftPos;\n }\n }\n break;\n }\n case DIRECTION.RIGHT:\n case DIRECTION.FORCE_RIGHT:\n {\n const separatorAtRightPos = this._findSeparatorAround(cursorPos);\n if (separatorAtRightPos >= 0) {\n return separatorAtRightPos + this.thousandsSeparator.length;\n }\n }\n }\n return cursorPos;\n }\n doCommit() {\n if (this.value) {\n const number = this.number;\n let validnum = number;\n\n // check bounds\n if (this.min != null) validnum = Math.max(validnum, this.min);\n if (this.max != null) validnum = Math.min(validnum, this.max);\n if (validnum !== number) this.unmaskedValue = this.format(validnum, this);\n let formatted = this.value;\n if (this.normalizeZeros) formatted = this._normalizeZeros(formatted);\n if (this.padFractionalZeros && this.scale > 0) formatted = this._padFractionalZeros(formatted);\n this._value = formatted;\n }\n super.doCommit();\n }\n _normalizeZeros(value) {\n const parts = this._removeThousandsSeparators(value).split(this.radix);\n\n // remove leading zeros\n parts[0] = parts[0].replace(/^(\\D*)(0*)(\\d*)/, (match, sign, zeros, num) => sign + num);\n // add leading zero\n if (value.length && !/\\d$/.test(parts[0])) parts[0] = parts[0] + '0';\n if (parts.length > 1) {\n parts[1] = parts[1].replace(/0*$/, ''); // remove trailing zeros\n if (!parts[1].length) parts.length = 1; // remove fractional\n }\n return this._insertThousandsSeparators(parts.join(this.radix));\n }\n _padFractionalZeros(value) {\n if (!value) return value;\n const parts = value.split(this.radix);\n if (parts.length < 2) parts.push('');\n parts[1] = parts[1].padEnd(this.scale, '0');\n return parts.join(this.radix);\n }\n doSkipInvalid(ch, flags, checkTail) {\n if (flags === void 0) {\n flags = {};\n }\n const dropFractional = this.scale === 0 && ch !== this.thousandsSeparator && (ch === this.radix || ch === MaskedNumber.UNMASKED_RADIX || this.mapToRadix.includes(ch));\n return super.doSkipInvalid(ch, flags, checkTail) && !dropFractional;\n }\n get unmaskedValue() {\n return this._removeThousandsSeparators(this._normalizeZeros(this.value)).replace(this.radix, MaskedNumber.UNMASKED_RADIX);\n }\n set unmaskedValue(unmaskedValue) {\n super.unmaskedValue = unmaskedValue;\n }\n get typedValue() {\n return this.parse(this.unmaskedValue, this);\n }\n set typedValue(n) {\n this.rawInputValue = this.format(n, this).replace(MaskedNumber.UNMASKED_RADIX, this.radix);\n }\n\n /** Parsed Number */\n get number() {\n return this.typedValue;\n }\n set number(number) {\n this.typedValue = number;\n }\n get allowNegative() {\n return this.min != null && this.min < 0 || this.max != null && this.max < 0;\n }\n get allowPositive() {\n return this.min != null && this.min > 0 || this.max != null && this.max > 0;\n }\n typedValueEquals(value) {\n // handle 0 -> '' case (typed = 0 even if value = '')\n // for details see https://github.com/uNmAnNeR/imaskjs/issues/134\n return (super.typedValueEquals(value) || MaskedNumber.EMPTY_VALUES.includes(value) && MaskedNumber.EMPTY_VALUES.includes(this.typedValue)) && !(value === 0 && this.value === '');\n }\n}\n_MaskedNumber = MaskedNumber;\nMaskedNumber.UNMASKED_RADIX = '.';\nMaskedNumber.EMPTY_VALUES = [...Masked.EMPTY_VALUES, 0];\nMaskedNumber.DEFAULTS = {\n ...Masked.DEFAULTS,\n mask: Number,\n radix: ',',\n thousandsSeparator: '',\n mapToRadix: [_MaskedNumber.UNMASKED_RADIX],\n min: Number.MIN_SAFE_INTEGER,\n max: Number.MAX_SAFE_INTEGER,\n scale: 2,\n normalizeZeros: true,\n padFractionalZeros: false,\n parse: Number,\n format: n => n.toLocaleString('en-US', {\n useGrouping: false,\n maximumFractionDigits: 20\n })\n};\nIMask.MaskedNumber = MaskedNumber;\n\nexport { MaskedNumber as default };\n", "import createMask from './factory.js';\nimport IMask from '../core/holder.js';\nimport '../core/utils.js';\n\n/** Mask pipe source and destination types */\nconst PIPE_TYPE = {\n MASKED: 'value',\n UNMASKED: 'unmaskedValue',\n TYPED: 'typedValue'\n};\n/** Creates new pipe function depending on mask type, source and destination options */\nfunction createPipe(arg, from, to) {\n if (from === void 0) {\n from = PIPE_TYPE.MASKED;\n }\n if (to === void 0) {\n to = PIPE_TYPE.MASKED;\n }\n const masked = createMask(arg);\n return value => masked.runIsolated(m => {\n m[from] = value;\n return m[to];\n });\n}\n\n/** Pipes value through mask depending on mask type, source and destination options */\nfunction pipe(value, mask, from, to) {\n return createPipe(mask, from, to)(value);\n}\nIMask.PIPE_TYPE = PIPE_TYPE;\nIMask.createPipe = createPipe;\nIMask.pipe = pipe;\n\nexport { PIPE_TYPE, createPipe, pipe };\n", "import ChangeDetails from '../core/change-details.js';\nimport IMask from '../core/holder.js';\nimport createMask, { normalizeOpts } from './factory.js';\nimport MaskedPattern from './pattern.js';\nimport '../core/utils.js';\nimport './base.js';\nimport '../core/continuous-tail-details.js';\nimport './pattern/chunk-tail-details.js';\nimport './pattern/cursor.js';\nimport './pattern/fixed-definition.js';\nimport './pattern/input-definition.js';\nimport './regexp.js';\n\n/** Pattern mask */\nclass RepeatBlock extends MaskedPattern {\n get repeatFrom() {\n var _ref;\n return (_ref = Array.isArray(this.repeat) ? this.repeat[0] : this.repeat === Infinity ? 0 : this.repeat) != null ? _ref : 0;\n }\n get repeatTo() {\n var _ref2;\n return (_ref2 = Array.isArray(this.repeat) ? this.repeat[1] : this.repeat) != null ? _ref2 : Infinity;\n }\n constructor(opts) {\n super(opts);\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n var _ref3, _ref4, _this$_blocks;\n const {\n repeat,\n ...blockOpts\n } = normalizeOpts(opts); // TODO type\n this._blockOpts = Object.assign({}, this._blockOpts, blockOpts);\n const block = createMask(this._blockOpts);\n this.repeat = (_ref3 = (_ref4 = repeat != null ? repeat : block.repeat) != null ? _ref4 : this.repeat) != null ? _ref3 : Infinity; // TODO type\n\n super._update({\n mask: 'm'.repeat(Math.max(this.repeatTo === Infinity && ((_this$_blocks = this._blocks) == null ? void 0 : _this$_blocks.length) || 0, this.repeatFrom)),\n blocks: {\n m: block\n },\n eager: block.eager,\n overwrite: block.overwrite,\n skipInvalid: block.skipInvalid,\n lazy: block.lazy,\n placeholderChar: block.placeholderChar,\n displayChar: block.displayChar\n });\n }\n _allocateBlock(bi) {\n if (bi < this._blocks.length) return this._blocks[bi];\n if (this.repeatTo === Infinity || this._blocks.length < this.repeatTo) {\n this._blocks.push(createMask(this._blockOpts));\n this.mask += 'm';\n return this._blocks[this._blocks.length - 1];\n }\n }\n _appendCharRaw(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n const details = new ChangeDetails();\n for (let bi = (_this$_mapPosToBlock$ = (_this$_mapPosToBlock = this._mapPosToBlock(this.displayValue.length)) == null ? void 0 : _this$_mapPosToBlock.index) != null ? _this$_mapPosToBlock$ : Math.max(this._blocks.length - 1, 0), block, allocated;\n // try to get a block or\n // try to allocate a new block if not allocated already\n block = (_this$_blocks$bi = this._blocks[bi]) != null ? _this$_blocks$bi : allocated = !allocated && this._allocateBlock(bi); ++bi) {\n var _this$_mapPosToBlock$, _this$_mapPosToBlock, _this$_blocks$bi, _flags$_beforeTailSta;\n const blockDetails = block._appendChar(ch, {\n ...flags,\n _beforeTailState: (_flags$_beforeTailSta = flags._beforeTailState) == null || (_flags$_beforeTailSta = _flags$_beforeTailSta._blocks) == null ? void 0 : _flags$_beforeTailSta[bi]\n });\n if (blockDetails.skip && allocated) {\n // remove the last allocated block and break\n this._blocks.pop();\n this.mask = this.mask.slice(1);\n break;\n }\n details.aggregate(blockDetails);\n if (blockDetails.consumed) break; // go next char\n }\n return details;\n }\n _trimEmptyTail(fromPos, toPos) {\n var _this$_mapPosToBlock2, _this$_mapPosToBlock3;\n if (fromPos === void 0) {\n fromPos = 0;\n }\n const firstBlockIndex = Math.max(((_this$_mapPosToBlock2 = this._mapPosToBlock(fromPos)) == null ? void 0 : _this$_mapPosToBlock2.index) || 0, this.repeatFrom, 0);\n let lastBlockIndex;\n if (toPos != null) lastBlockIndex = (_this$_mapPosToBlock3 = this._mapPosToBlock(toPos)) == null ? void 0 : _this$_mapPosToBlock3.index;\n if (lastBlockIndex == null) lastBlockIndex = this._blocks.length - 1;\n let removeCount = 0;\n for (let blockIndex = lastBlockIndex; firstBlockIndex <= blockIndex; --blockIndex, ++removeCount) {\n if (this._blocks[blockIndex].unmaskedValue) break;\n }\n if (removeCount) {\n this._blocks.splice(lastBlockIndex - removeCount + 1, removeCount);\n this.mask = this.mask.slice(removeCount);\n }\n }\n reset() {\n super.reset();\n this._trimEmptyTail();\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n const removeDetails = super.remove(fromPos, toPos);\n this._trimEmptyTail(fromPos, toPos);\n return removeDetails;\n }\n totalInputPositions(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos == null && this.repeatTo === Infinity) return Infinity;\n return super.totalInputPositions(fromPos, toPos);\n }\n get state() {\n return super.state;\n }\n set state(state) {\n this._blocks.length = state._blocks.length;\n this.mask = this.mask.slice(0, this._blocks.length);\n super.state = state;\n }\n}\nIMask.RepeatBlock = RepeatBlock;\n\nexport { RepeatBlock as default };\n", "export { default as InputMask } from './controls/input.js';\nimport IMask from './core/holder.js';\nexport { default as HTMLContenteditableMaskElement } from './controls/html-contenteditable-mask-element.js';\nexport { default as HTMLInputMaskElement } from './controls/html-input-mask-element.js';\nexport { default as HTMLMaskElement } from './controls/html-mask-element.js';\nexport { default as MaskElement } from './controls/mask-element.js';\nexport { default as ChangeDetails } from './core/change-details.js';\nexport { DIRECTION, forceDirection } from './core/utils.js';\nexport { default as Masked } from './masked/base.js';\nexport { default as MaskedDate } from './masked/date.js';\nexport { default as MaskedDynamic } from './masked/dynamic.js';\nexport { default as MaskedEnum } from './masked/enum.js';\nexport { default as createMask, normalizeOpts } from './masked/factory.js';\nexport { default as MaskedFunction } from './masked/function.js';\nexport { default as MaskedNumber } from './masked/number.js';\nexport { default as MaskedPattern } from './masked/pattern.js';\nexport { default as ChunksTailDetails } from './masked/pattern/chunk-tail-details.js';\nexport { default as PatternFixedDefinition } from './masked/pattern/fixed-definition.js';\nexport { default as PatternInputDefinition } from './masked/pattern/input-definition.js';\nexport { PIPE_TYPE, createPipe, pipe } from './masked/pipe.js';\nexport { default as MaskedRange } from './masked/range.js';\nexport { default as MaskedRegExp } from './masked/regexp.js';\nexport { default as RepeatBlock } from './masked/repeat.js';\nimport './core/action-details.js';\nimport './controls/input-history.js';\nimport './core/continuous-tail-details.js';\nimport './masked/pattern/cursor.js';\n\ntry {\n globalThis.IMask = IMask;\n} catch {}\n\nexport { IMask as default };\n", "import { Controller } from \"@hotwired/stimulus\";\nimport IMask from \"imask\";\nimport { trackEvent } from \"@/utils/analytics\";\n\n/** @typedef {HTMLInputElement | HTMLSelectElement} SubmittableFormField */\n\nexport default class extends Controller {\n static targets = [\"masked\"];\n static values = {\n autosubmit: Boolean,\n analyticsCategory: String,\n analyticsAction: String,\n };\n\n /**\n * Tracks form state to report to Google Analytics on changed fields\n * @type {null | Record>}\n */\n #formState = null;\n\n connect() {\n if (!(this.element instanceof HTMLFormElement)) throw new TypeError(\"This controller can only be used with `HTMLFormElement`s\");\n const form = /** @type {HTMLFormElement} */ (this.element);\n\n if (this.#analyticsEnabled()) {\n this.#formState = this.#getAnalyticPairs(form.elements);\n form.addEventListener(\"submit\", this.#reportAnalytics, { passive: true });\n }\n\n if (!this.autosubmitValue) return;\n\n form.ownerDocument.addEventListener(\"change\", this.#handleChange, { passive: true });\n form.ownerDocument.addEventListener(\"input\", this.#handleDebouncedInput, { passive: true });\n }\n\n disconnect() {\n const form = /** @type {HTMLFormElement} */ (this.element);\n form.ownerDocument.removeEventListener(\"change\", this.#handleChange);\n form.ownerDocument.removeEventListener(\"input\", this.#handleDebouncedInput);\n }\n\n #analyticsEnabled() {\n return (this.analyticsCategoryValue.trim().length > 0) &&\n (this.analyticsActionValue.trim().length > 0);\n }\n\n /** @param {Event & { target: SubmittableFormField; currentTarget: Document }} event */\n #handleChange = (event) => {\n const field = event.target;\n if (field.form !== this.element || field instanceof HTMLInputElement) return;\n if (this.#skipsAutosubmit(field)) return;\n\n this.#submit(field.form);\n };\n\n // A control that only drives client-side behaviour -- a type-ahead row filter,\n // say -- is part of this form by DOM position alone. Both listeners are on the\n // document and match on `field.form`, so without an opt-out, typing in one\n // resubmits the page it happens to sit inside.\n /** @param {SubmittableFormField} field */\n #skipsAutosubmit(field) {\n return field.hasAttribute(\"data-skip-autosubmit\");\n }\n\n #handleDebouncedInput = (() => {\n let timer;\n\n /** @param {InputEvent & { target: SubmittableFormField; currentTarget: Document }} event */\n return (event) => {\n const field = event.target;\n if (field.form !== this.element || !(field instanceof HTMLInputElement)) return;\n if (this.#skipsAutosubmit(field)) return;\n if (field.hasAttribute(\"data-skip-debounce\")) return this.#submit(field.form);\n\n clearTimeout(timer);\n timer = setTimeout(this.#submit, 1000, field.form);\n };\n })();\n\n /** @param {HTMLFormElement} form */\n #submit = (form) => {\n this.context.logDebugActivity(\"submit\");\n form.classList.add(\"auto-submitting\");\n form.addEventListener(\"turbo:submit-end\", () => form.classList.remove(\"auto-submitting\"), { once: true, passive: true });\n form.requestSubmit();\n };\n\n maskedTargetConnected(element) {\n const maskOptions = { mask: element.dataset.mask };\n IMask(element, maskOptions);\n }\n\n /**\n * Parse form fields that need analytics reported. We are\n * parsing analytic pairs this way because we are using data\n * attributes to identify whether to report analytics.\n * @param {Record} rawNodes\n * @returns {Record>}\n */\n #getAnalyticPairs(rawNodes) {\n const result = {};\n for (const { name, value, dataset, selectedOptions } of Array.from(rawNodes)) {\n if (!name || !dataset?.ga) continue;\n\n result[name] = {\n value,\n reportedValue: dataset.ga === \"value\" ? value : undefined,\n selectedOption: selectedOptions !== undefined ? selectedOptions[0]?.label : undefined,\n };\n }\n\n return result;\n }\n\n /** @param { InputEvent & { target: HTMLFormElement }} target */\n #reportAnalytics = ({ target }) => {\n if (!this.#analyticsEnabled()) return;\n\n const newFormState = this.#getAnalyticPairs(target.elements);\n const diff = { ...newFormState }; // Don't assign by reference\n for (const [key, value] of Object.entries(diff)) {\n if (this.#formState[key].value === value.value) delete diff[key];\n }\n\n if (Object.keys(diff).length === 0) return;\n\n for (const [label, value] of Object.entries(diff)) {\n if (value.reportedValue !== \"\") {\n trackEvent({\n action: this.analyticsActionValue,\n category: this.analyticsCategoryValue,\n value: value.selectedOption !== undefined ? value.selectedOption : value.reportedValue,\n label,\n }, target);\n }\n }\n\n this.#formState = newFormState;\n };\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"format\"\nexport default class extends Controller {\n static values = { type: String };\n\n connect() {\n if (this.element instanceof HTMLInputElement) {\n this.element.value = this.#format(this.element.value);\n } else {\n this.element.innerText = this.#format(this.element.innerText);\n }\n }\n\n change({ target }) {\n target.value = this.#format(target.value);\n }\n\n #format(value) {\n switch (this.typeValue) {\n case \"phone\":\n return this.#formatPhone(value);\n case \"comma_delimited\":\n return this.#formatNumber(value);\n case \"currency\":\n return this.#formatCurrency(value);\n default:\n return value;\n }\n }\n\n #formatPhone(num) {\n let newNum;\n // test for this format: (xxx)xxx-xxxx\n // var re2 = /^\\({1}\\d{3}\\)\\d{3}-\\d{4}/;\n // test for this format: xxx-xxx-xxxx\n const nine = /^\\d{10}/;\n if (nine.test(num) === true) {\n // for format (xxx)xxx-xxxx\n // newNum = '(' + num.substring(0,3) + ')' + num.substring(3,6) + '-' + num.substring(6,10);\n // for format xxx-xxx-xxxx\n newNum = `(${num.substring(0, 3)}) ${num.substring(3, 6)}-${num.substring(6, 10)}`;\n if (num.length > 10) {\n newNum += \" \" + num.substring(11, 255);\n }\n // o.value=newNum;\n } else {\n newNum = num;\n }\n newNum = newNum.trim();\n return newNum;\n }\n\n #formatCurrency(num) {\n num = this.#formatNumber(num);\n\n if (num === \"\") {\n return \"\";\n }\n\n if (!num.match(/\\./)) {\n num = num + \".00\";\n }\n\n if (num.match(/-/)) {\n return `-$${num.replace(\"-\", \"\")}`;\n } else {\n return `$${num}`;\n }\n }\n\n #formatNumber(num) {\n num = num.toString();\n num = num.replace(/\\$|\\,/g, \"\");\n num = num.replace(/k$/i, \"000\");\n\n if (isNaN(num) || num === \"\") {\n return \"\";\n }\n\n let negative = num < 0;\n\n num = Math.abs(num);\n num = Math.floor(num * 100 + 0.50000000001);\n\n let cents = num % 100;\n\n num = Math.floor(num / 100).toString();\n\n if (cents < 10) {\n cents = \"0\" + cents;\n }\n\n num = num.replace(/(\\d)(?=(\\d\\d\\d)+(?!\\d))/g, \"$1,\");\n negative = negative ? \"-\" : \"\";\n cents = cents === \"00\" ? \"\" : `.${cents}`;\n\n return `${negative}${num}${cents}`;\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport { trackEvent as gaTrackEvent } from \"../utils/analytics\";\n\nexport default class extends Controller {\n trackEvent (event) {\n const account_id = event.target.closest(\"[data-ga-account-id]\")?.dataset.gaAccountId;\n const dealership_id = event.target.closest(\"[data-ga-dealership-id]\")?.dataset.gaDealershipId;\n const upsheet_id = event.target.closest(\"[data-ga-upsheet-id]\")?.dataset.gaUpsheetId;\n const parameter1 = event.target.closest(\"[data-ga-parameter1]\")?.dataset.gaParameter1;\n const parameter2 = event.target.closest(\"[data-ga-parameter2]\")?.dataset.gaParameter2;\n const category = event.target.closest(\"[data-ga-category]\")?.dataset.gaCategory;\n const action = event.target.closest(\"[data-ga-action]\")?.dataset.gaAction;\n const label = event.target.closest(\"[data-ga-label]\")?.dataset.gaLabel;\n const value = event.target.closest(\"[data-ga-value]\")?.dataset.gaValue;\n\n gaTrackEvent({ account_id, dealership_id, upsheet_id, parameter1, parameter2, category, action, label, value });\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\nexport default class extends Controller {\n static targets = [\"achieved\", \"progressBar\"];\n static values = {\n achieved: Number,\n target: Number,\n percentage: Number,\n animationDuration: { type: Number, default: 800 },\n };\n\n connect() {\n if (this.targetValue > 0) {\n this.animateCountUp();\n this.animateProgressBar();\n }\n }\n\n animateCountUp() {\n if (!this.hasAchievedTarget) return;\n\n const duration = this.animationDurationValue;\n const start = 0;\n const end = this.achievedValue;\n const startTime = performance.now();\n\n const animate = (currentTime) => {\n const elapsed = currentTime - startTime;\n const progress = Math.min(elapsed / duration, 1);\n const easeProgress = 1 - (1 - progress) * (1 - progress);\n const current = Math.round(start + (end - start) * easeProgress);\n\n this.achievedTarget.textContent = current;\n\n if (progress < 1) {\n requestAnimationFrame(animate);\n }\n };\n\n requestAnimationFrame(animate);\n }\n\n animateProgressBar() {\n if (!this.hasProgressBarTarget) return;\n\n const percentage = Math.min(this.percentageValue, 100);\n\n requestAnimationFrame(() => {\n this.progressBarTarget.style.width = `${percentage}%`;\n });\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\nexport default class extends Controller {\n resizeIframe() {\n // set the height of the iframe as the height of the iframe content\n this.element.style.height = this.element.contentWindow.document.body.scrollHeight + 32 + \"px\";\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Shared description editor used by the IMM gallery for both uploaded media\n// items and feed images. One instance lives in the gallery; items dispatch\n// `imm-media:open-description-editor` with { sourceId, url, description } and\n// the modal PATCHes the supplied URL on save, then echoes\n// `imm-media:description-saved` back so the originating item can refresh its\n// in-memory state.\nexport default class extends Controller {\n static targets = [\"textarea\"];\n\n connect() {\n this._openHandler = (event) => this.handleOpen(event);\n this._keydownHandler = (event) => {\n if (event.key === \"Escape\" && !this.element.classList.contains(\"hidden\")) {\n this.cancel();\n }\n };\n window.addEventListener(\"imm-media:open-description-editor\", this._openHandler);\n document.addEventListener(\"keydown\", this._keydownHandler);\n }\n\n disconnect() {\n window.removeEventListener(\"imm-media:open-description-editor\", this._openHandler);\n document.removeEventListener(\"keydown\", this._keydownHandler);\n }\n\n handleOpen(event) {\n const { description, url, sourceId } = event.detail || {};\n if (!url) return;\n this._url = url;\n this._sourceId = sourceId;\n this.textareaTarget.value = description || \"\";\n this.show();\n this.textareaTarget.focus();\n }\n\n show() {\n this.element.classList.remove(\"hidden\");\n }\n\n hide() {\n this.element.classList.add(\"hidden\");\n this._url = null;\n this._sourceId = null;\n }\n\n cancel(event) {\n event?.preventDefault();\n this.hide();\n }\n\n backdropClick(event) {\n if (event.target === event.currentTarget) this.cancel(event);\n }\n\n async save(event) {\n event.preventDefault();\n if (!this._url) return;\n\n const description = this.textareaTarget.value;\n\n const response = await fetch(this._url, {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CSRF-Token\": this.csrfToken,\n Accept: \"application/json\",\n },\n body: JSON.stringify({ description }),\n });\n\n if (response.ok) {\n window.dispatchEvent(\n new CustomEvent(\"imm-media:description-saved\", {\n detail: { sourceId: this._sourceId, description },\n }),\n );\n this.hide();\n }\n }\n\n get csrfToken() {\n return document.querySelector(\"[name='csrf-token']\")?.content;\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\nexport default class extends Controller {\n static targets = [\n \"grid\",\n \"lightbox\",\n \"lightboxContent\",\n \"lightboxCounter\",\n \"emptyState\",\n ];\n\n static values = {\n mode: { type: String, default: \"manage\" },\n sourceUrl: String,\n };\n\n connect() {\n this.currentIndex = 0;\n this.items = [];\n this.refreshItems();\n }\n\n refreshItems() {\n this.items = Array.from(\n this.gridTarget.querySelectorAll(\"[data-imm--media--item-url-value]\"),\n );\n }\n\n // --- Lightbox ---\n\n openLightbox(event) {\n if (this.modeValue === \"pick\") return;\n\n const item = event.currentTarget.closest(\n \"[data-imm--media--item-url-value]\",\n );\n if (!item) return;\n\n const url = item.getAttribute(\"data-imm--media--item-url-value\");\n const mediaType = item.getAttribute(\n \"data-imm--media--item-media-type-value\",\n );\n\n this.refreshItems();\n this.currentIndex = this.items.indexOf(item);\n\n this.renderLightboxContent(url, mediaType);\n this.lightboxTarget.classList.remove(\"hidden\");\n document.body.classList.add(\"overflow-hidden\");\n\n this.boundKeyHandler = this.handleKeydown.bind(this);\n document.addEventListener(\"keydown\", this.boundKeyHandler);\n }\n\n closeLightbox() {\n this.lightboxTarget.classList.add(\"hidden\");\n this.lightboxContentTarget.innerHTML = \"\";\n document.body.classList.remove(\"overflow-hidden\");\n\n if (this.boundKeyHandler) {\n document.removeEventListener(\"keydown\", this.boundKeyHandler);\n }\n }\n\n prevItem(event) {\n event?.stopPropagation();\n this.refreshItems();\n if (this.items.length === 0) return;\n this.currentIndex =\n (this.currentIndex - 1 + this.items.length) % this.items.length;\n this.showCurrentItem();\n }\n\n nextItem(event) {\n event?.stopPropagation();\n this.refreshItems();\n if (this.items.length === 0) return;\n this.currentIndex = (this.currentIndex + 1) % this.items.length;\n this.showCurrentItem();\n }\n\n showCurrentItem() {\n const item = this.items[this.currentIndex];\n if (!item) return;\n\n const url = item.getAttribute(\"data-imm--media--item-url-value\");\n const mediaType = item.getAttribute(\n \"data-imm--media--item-media-type-value\",\n );\n this.renderLightboxContent(url, mediaType);\n }\n\n renderLightboxContent(url, mediaType) {\n this.lightboxContentTarget.innerHTML = `\n \n
\n \n
\n `;\n\n const spinner = this.lightboxContentTarget.querySelector(\"[data-spinner]\");\n const closeBtn = this.lightboxContentTarget.querySelector(\"[data-close]\");\n const reveal = () => {\n spinner?.remove();\n closeBtn?.classList.remove(\"hidden\");\n };\n\n let media;\n if (mediaType === \"video\") {\n media = document.createElement(\"video\");\n media.controls = true;\n media.className = \"max-w-[90vw] max-h-[85vh] rounded block hidden\";\n media.addEventListener(\"loadeddata\", () => { reveal(); media.classList.remove(\"hidden\"); });\n media.addEventListener(\"error\", reveal);\n media.src = url;\n } else {\n media = document.createElement(\"img\");\n media.className = \"max-w-[90vw] max-h-[85vh] rounded block hidden\";\n media.addEventListener(\"load\", () => { reveal(); media.classList.remove(\"hidden\"); });\n media.addEventListener(\"error\", reveal);\n media.src = url;\n }\n this.lightboxContentTarget.appendChild(media);\n\n if (this.hasLightboxCounterTarget && this.items.length > 0) {\n this.lightboxCounterTarget.textContent = `${this.currentIndex + 1} / ${this.items.length}`;\n }\n }\n\n handleKeydown(event) {\n switch (event.key) {\n case \"Escape\":\n this.closeLightbox();\n break;\n case \"ArrowLeft\":\n this.prevItem();\n break;\n case \"ArrowRight\":\n this.nextItem();\n break;\n }\n }\n\n // --- Empty State ---\n\n updateEmptyState() {\n if (!this.hasEmptyStateTarget) return;\n const hasItems =\n this.gridTarget.querySelectorAll(\"[data-controller='imm--media--item']\")\n .length > 0;\n this.emptyStateTarget.classList.toggle(\"hidden\", hasItems);\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\nexport default class extends Controller {\n static values = {\n id: Number,\n type: String,\n url: String,\n thumbnailUrl: String,\n mediaType: String,\n category: String,\n description: String,\n setHeaderUrl: String,\n updateUrl: String,\n destroyUrl: String,\n excludedFromAisa: Boolean,\n };\n\n static targets = [\"categorySelect\", \"menu\", \"menuButton\", \"menuDropdown\", \"exclusionLabel\", \"aisaExcludedBadge\"];\n\n connect() {\n this._descriptionSavedHandler = (event) => this.handleDescriptionSaved(event);\n window.addEventListener(\"imm-media:description-saved\", this._descriptionSavedHandler);\n }\n\n disconnect() {\n this.removeOutsideClickListener();\n window.removeEventListener(\"imm-media:description-saved\", this._descriptionSavedHandler);\n }\n\n // --- Menu ---\n\n toggleMenu(event) {\n event.stopPropagation();\n const isOpen = !this.menuDropdownTarget.classList.contains(\"hidden\");\n // Close any other open menus on the page first.\n document\n .querySelectorAll(\"[data-imm--media--item-target='menuDropdown']\")\n .forEach((el) => el.classList.add(\"hidden\"));\n document\n .querySelectorAll(\"[data-imm--media--item-target='menuButton']\")\n .forEach((el) => el.setAttribute(\"aria-expanded\", \"false\"));\n\n if (!isOpen) {\n this.menuDropdownTarget.classList.remove(\"hidden\");\n this.menuButtonTarget.setAttribute(\"aria-expanded\", \"true\");\n this.addOutsideClickListener();\n } else {\n this.removeOutsideClickListener();\n }\n }\n\n closeMenu() {\n if (!this.hasMenuDropdownTarget) return;\n this.menuDropdownTarget.classList.add(\"hidden\");\n if (this.hasMenuButtonTarget) {\n this.menuButtonTarget.setAttribute(\"aria-expanded\", \"false\");\n }\n this.removeOutsideClickListener();\n }\n\n addOutsideClickListener() {\n this.removeOutsideClickListener();\n this._outsideClickHandler = (event) => {\n if (!this.hasMenuTarget) return;\n if (!this.menuTarget.contains(event.target)) this.closeMenu();\n };\n document.addEventListener(\"click\", this._outsideClickHandler);\n }\n\n removeOutsideClickListener() {\n if (this._outsideClickHandler) {\n document.removeEventListener(\"click\", this._outsideClickHandler);\n this._outsideClickHandler = null;\n }\n }\n\n // --- Pick Mode ---\n\n pick() {\n this.dispatch(\"pick\", {\n detail: {\n id: this.idValue,\n url: this.urlValue,\n thumbnailUrl: this.thumbnailUrlValue,\n mediaType: this.mediaTypeValue,\n category: this.categoryValue,\n },\n prefix: \"imm-media\",\n bubbles: true,\n });\n\n this.element.classList.add(\"imm-media-item--selected\");\n setTimeout(\n () => this.element.classList.remove(\"imm-media-item--selected\"),\n 1500,\n );\n }\n\n // --- Manage Mode Actions ---\n\n async toggleHeader(event) {\n event.stopPropagation();\n this.closeMenu();\n if (this.mediaTypeValue === \"video\") return; // videos cannot be header\n if (!this.setHeaderUrlValue) return;\n\n const response = await fetch(this.setHeaderUrlValue, {\n method: \"PATCH\",\n headers: { \"X-CSRF-Token\": this.csrfToken, Accept: \"application/json\" },\n });\n\n if (response.ok) {\n // Clear the header marker from any tile and re-show \"Set as header\"\n // buttons on photo items.\n document\n .querySelectorAll(\".imm-media-item--header\")\n .forEach((el) => el.classList.remove(\"imm-media-item--header\"));\n document\n .querySelectorAll(\"[data-action*='toggleHeader']\")\n .forEach((btn) => {\n const item = btn.closest(\"[data-imm--media--item-media-type-value]\");\n const isVideo =\n item?.getAttribute(\"data-imm--media--item-media-type-value\") ===\n \"video\";\n if (!isVideo) btn.classList.remove(\"hidden\");\n });\n\n // Mark this tile as the header\n this.element.classList.add(\"imm-media-item--header\");\n\n // Hide the \"Set as header\" button on the new header\n const headerBtn = this.element.querySelector(\"[data-action*='toggleHeader']\");\n if (headerBtn) headerBtn.classList.add(\"hidden\");\n\n this.dispatch(\"header-change\", {\n detail: { id: this.idValue, url: this.urlValue },\n prefix: \"imm-media\",\n bubbles: true,\n });\n }\n }\n\n async updateCategory(event) {\n event.stopPropagation();\n if (!this.updateUrlValue) return;\n const category = this.categorySelectTarget.value;\n\n await fetch(this.updateUrlValue, {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CSRF-Token\": this.csrfToken,\n Accept: \"application/json\",\n },\n body: JSON.stringify({ category }),\n });\n }\n\n editDescription(event) {\n event.stopPropagation();\n this.closeMenu();\n if (!this.updateUrlValue) return;\n\n window.dispatchEvent(\n new CustomEvent(\"imm-media:open-description-editor\", {\n detail: {\n sourceId: this.element.id,\n url: this.updateUrlValue,\n description: this.descriptionValue,\n },\n }),\n );\n }\n\n handleDescriptionSaved(event) {\n if (event.detail?.sourceId !== this.element.id) return;\n this.descriptionValue = event.detail.description || \"\";\n }\n\n async toggleExclusion(event) {\n event.stopPropagation();\n this.closeMenu();\n if (!this.updateUrlValue) return;\n\n const newValue = !this.excludedFromAisaValue;\n const response = await fetch(this.updateUrlValue, {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CSRF-Token\": this.csrfToken,\n Accept: \"application/json\",\n },\n body: JSON.stringify({ excluded_from_aisa: newValue }),\n });\n\n if (response.ok) {\n this.excludedFromAisaValue = newValue;\n this.element.classList.toggle(\"imm-media-item--aisa-excluded\", newValue);\n this.element\n .querySelectorAll(\"[data-imm--media--item-target='exclusionLabel']\")\n .forEach((el) => {\n el.textContent = newValue ? \"Include in AISA\" : \"Exclude from AISA\";\n });\n if (this.hasAisaExcludedBadgeTarget) {\n this.aisaExcludedBadgeTarget.classList.toggle(\"hidden\", !newValue);\n }\n }\n }\n\n async destroy(event) {\n event.stopPropagation();\n this.closeMenu();\n if (!this.destroyUrlValue) return;\n if (!confirm(\"Delete this media item?\")) return;\n\n const response = await fetch(this.destroyUrlValue, {\n method: \"DELETE\",\n headers: { \"X-CSRF-Token\": this.csrfToken, Accept: \"application/json\" },\n });\n\n if (response.ok) {\n this.element.remove();\n this.dispatch(\"delete\", {\n detail: { id: this.idValue },\n prefix: \"imm-media\",\n bubbles: true,\n });\n }\n }\n\n get csrfToken() {\n return document.querySelector(\"[name='csrf-token']\")?.content;\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Simple single-image lightbox for vehicle list thumbnails.\n// Clicking the thumbnail opens the header image full-size in an overlay.\nexport default class extends Controller {\n static values = { url: String, alt: String };\n\n open(event) {\n event.stopPropagation();\n event.preventDefault();\n\n this.overlay = document.createElement(\"div\");\n this.overlay.className =\n \"fixed inset-0 flex items-center justify-center cursor-pointer\";\n this.overlay.style.backgroundColor = \"rgba(0, 0, 0, 0.92)\";\n this.overlay.style.zIndex = \"9999\";\n this.overlay.addEventListener(\"click\", this.close);\n\n const wrapper = document.createElement(\"div\");\n wrapper.className = \"relative inline-block cursor-default\";\n wrapper.addEventListener(\"click\", (e) => e.stopPropagation());\n\n const closeBtn = document.createElement(\"button\");\n closeBtn.className =\n \"hidden absolute -top-8 -right-8 flex items-center justify-center text-green-600 hover:text-green-300 cursor-pointer z-10\";\n closeBtn.setAttribute(\"aria-label\", \"Close\");\n closeBtn.innerHTML = \"\";\n closeBtn.addEventListener(\"click\", this.close);\n\n const spinner = document.createElement(\"div\");\n spinner.className = \"flex items-center justify-center\";\n spinner.style.minWidth = \"120px\";\n spinner.style.minHeight = \"120px\";\n spinner.innerHTML =\n \"\";\n\n const reveal = () => {\n spinner.remove();\n closeBtn.classList.remove(\"hidden\");\n };\n\n const img = document.createElement(\"img\");\n img.alt = this.altValue;\n img.className =\n \"max-w-[90vw] max-h-[90vh] object-contain rounded shadow-lg block hidden\";\n img.addEventListener(\"load\", () => { reveal(); img.classList.remove(\"hidden\"); });\n img.addEventListener(\"error\", reveal);\n img.src = this.urlValue;\n\n wrapper.appendChild(closeBtn);\n wrapper.appendChild(spinner);\n wrapper.appendChild(img);\n this.overlay.appendChild(wrapper);\n\n document.body.appendChild(this.overlay);\n document.body.classList.add(\"overflow-hidden\");\n\n this.boundKeyHandler = this.handleKeydown.bind(this);\n document.addEventListener(\"keydown\", this.boundKeyHandler);\n }\n\n close = () => {\n if (this.overlay) {\n this.overlay.remove();\n this.overlay = null;\n }\n document.body.classList.remove(\"overflow-hidden\");\n\n if (this.boundKeyHandler) {\n document.removeEventListener(\"keydown\", this.boundKeyHandler);\n this.boundKeyHandler = null;\n }\n };\n\n handleKeydown(event) {\n if (event.key === \"Escape\") this.close();\n }\n\n disconnect() {\n this.close();\n }\n}\n", "/**!\n * Sortable 1.15.7\n * @author\tRubaXa \n * @author\towenm \n * @license MIT\n */\nfunction _arrayLikeToArray(r, a) {\n (null == a || a > r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nfunction _arrayWithoutHoles(r) {\n if (Array.isArray(r)) return _arrayLikeToArray(r);\n}\nfunction _defineProperty(e, r, t) {\n return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n value: t,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[r] = t, e;\n}\nfunction _extends() {\n return _extends = Object.assign ? Object.assign.bind() : function (n) {\n for (var e = 1; e < arguments.length; e++) {\n var t = arguments[e];\n for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n }\n return n;\n }, _extends.apply(null, arguments);\n}\nfunction _iterableToArray(r) {\n if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r);\n}\nfunction _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}\nfunction ownKeys(e, r) {\n var t = Object.keys(e);\n if (Object.getOwnPropertySymbols) {\n var o = Object.getOwnPropertySymbols(e);\n r && (o = o.filter(function (r) {\n return Object.getOwnPropertyDescriptor(e, r).enumerable;\n })), t.push.apply(t, o);\n }\n return t;\n}\nfunction _objectSpread2(e) {\n for (var r = 1; r < arguments.length; r++) {\n var t = null != arguments[r] ? arguments[r] : {};\n r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {\n _defineProperty(e, r, t[r]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {\n Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n });\n }\n return e;\n}\nfunction _objectWithoutProperties(e, t) {\n if (null == e) return {};\n var o,\n r,\n i = _objectWithoutPropertiesLoose(e, t);\n if (Object.getOwnPropertySymbols) {\n var n = Object.getOwnPropertySymbols(e);\n for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);\n }\n return i;\n}\nfunction _objectWithoutPropertiesLoose(r, e) {\n if (null == r) return {};\n var t = {};\n for (var n in r) if ({}.hasOwnProperty.call(r, n)) {\n if (-1 !== e.indexOf(n)) continue;\n t[n] = r[n];\n }\n return t;\n}\nfunction _toConsumableArray(r) {\n return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();\n}\nfunction _toPrimitive(t, r) {\n if (\"object\" != typeof t || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != typeof i) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nfunction _toPropertyKey(t) {\n var i = _toPrimitive(t, \"string\");\n return \"symbol\" == typeof i ? i : i + \"\";\n}\nfunction _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, _typeof(o);\n}\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return _arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;\n }\n}\n\nvar version = \"1.15.7\";\n\nfunction userAgent(pattern) {\n if (typeof window !== 'undefined' && window.navigator) {\n return !! /*@__PURE__*/navigator.userAgent.match(pattern);\n }\n}\nvar IE11OrLess = userAgent(/(?:Trident.*rv[ :]?11\\.|msie|iemobile|Windows Phone)/i);\nvar Edge = userAgent(/Edge/i);\nvar FireFox = userAgent(/firefox/i);\nvar Safari = userAgent(/safari/i) && !userAgent(/chrome/i) && !userAgent(/android/i);\nvar IOS = userAgent(/iP(ad|od|hone)/i);\nvar ChromeForAndroid = userAgent(/chrome/i) && userAgent(/android/i);\n\nvar captureMode = {\n capture: false,\n passive: false\n};\nfunction on(el, event, fn) {\n el.addEventListener(event, fn, !IE11OrLess && captureMode);\n}\nfunction off(el, event, fn) {\n el.removeEventListener(event, fn, !IE11OrLess && captureMode);\n}\nfunction matches( /**HTMLElement*/el, /**String*/selector) {\n if (!selector) return;\n selector[0] === '>' && (selector = selector.substring(1));\n if (el) {\n try {\n if (el.matches) {\n return el.matches(selector);\n } else if (el.msMatchesSelector) {\n return el.msMatchesSelector(selector);\n } else if (el.webkitMatchesSelector) {\n return el.webkitMatchesSelector(selector);\n }\n } catch (_) {\n return false;\n }\n }\n return false;\n}\nfunction getParentOrHost(el) {\n return el.host && el !== document && el.host.nodeType && el.host !== el ? el.host : el.parentNode;\n}\nfunction closest( /**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx, includeCTX) {\n if (el) {\n ctx = ctx || document;\n do {\n if (selector != null && (selector[0] === '>' ? el.parentNode === ctx && matches(el, selector) : matches(el, selector)) || includeCTX && el === ctx) {\n return el;\n }\n if (el === ctx) break;\n /* jshint boss:true */\n } while (el = getParentOrHost(el));\n }\n return null;\n}\nvar R_SPACE = /\\s+/g;\nfunction toggleClass(el, name, state) {\n if (el && name) {\n if (el.classList) {\n el.classList[state ? 'add' : 'remove'](name);\n } else {\n var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' ');\n el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' ');\n }\n }\n}\nfunction css(el, prop, val) {\n var style = el && el.style;\n if (style) {\n if (val === void 0) {\n if (document.defaultView && document.defaultView.getComputedStyle) {\n val = document.defaultView.getComputedStyle(el, '');\n } else if (el.currentStyle) {\n val = el.currentStyle;\n }\n return prop === void 0 ? val : val[prop];\n } else {\n if (!(prop in style) && prop.indexOf('webkit') === -1) {\n prop = '-webkit-' + prop;\n }\n style[prop] = val + (typeof val === 'string' ? '' : 'px');\n }\n }\n}\nfunction matrix(el, selfOnly) {\n var appliedTransforms = '';\n if (typeof el === 'string') {\n appliedTransforms = el;\n } else {\n do {\n var transform = css(el, 'transform');\n if (transform && transform !== 'none') {\n appliedTransforms = transform + ' ' + appliedTransforms;\n }\n /* jshint boss:true */\n } while (!selfOnly && (el = el.parentNode));\n }\n var matrixFn = window.DOMMatrix || window.WebKitCSSMatrix || window.CSSMatrix || window.MSCSSMatrix;\n /*jshint -W056 */\n return matrixFn && new matrixFn(appliedTransforms);\n}\nfunction find(ctx, tagName, iterator) {\n if (ctx) {\n var list = ctx.getElementsByTagName(tagName),\n i = 0,\n n = list.length;\n if (iterator) {\n for (; i < n; i++) {\n iterator(list[i], i);\n }\n }\n return list;\n }\n return [];\n}\nfunction getWindowScrollingElement() {\n var scrollingElement = document.scrollingElement;\n if (scrollingElement) {\n return scrollingElement;\n } else {\n return document.documentElement;\n }\n}\n\n/**\r\n * Returns the \"bounding client rect\" of given element\r\n * @param {HTMLElement} el The element whose boundingClientRect is wanted\r\n * @param {[Boolean]} relativeToContainingBlock Whether the rect should be relative to the containing block of (including) the container\r\n * @param {[Boolean]} relativeToNonStaticParent Whether the rect should be relative to the relative parent of (including) the contaienr\r\n * @param {[Boolean]} undoScale Whether the container's scale() should be undone\r\n * @param {[HTMLElement]} container The parent the element will be placed in\r\n * @return {Object} The boundingClientRect of el, with specified adjustments\r\n */\nfunction getRect(el, relativeToContainingBlock, relativeToNonStaticParent, undoScale, container) {\n if (!el.getBoundingClientRect && el !== window) return;\n var elRect, top, left, bottom, right, height, width;\n if (el !== window && el.parentNode && el !== getWindowScrollingElement()) {\n elRect = el.getBoundingClientRect();\n top = elRect.top;\n left = elRect.left;\n bottom = elRect.bottom;\n right = elRect.right;\n height = elRect.height;\n width = elRect.width;\n } else {\n top = 0;\n left = 0;\n bottom = window.innerHeight;\n right = window.innerWidth;\n height = window.innerHeight;\n width = window.innerWidth;\n }\n if ((relativeToContainingBlock || relativeToNonStaticParent) && el !== window) {\n // Adjust for translate()\n container = container || el.parentNode;\n\n // solves #1123 (see: https://stackoverflow.com/a/37953806/6088312)\n // Not needed on <= IE11\n if (!IE11OrLess) {\n do {\n if (container && container.getBoundingClientRect && (css(container, 'transform') !== 'none' || relativeToNonStaticParent && css(container, 'position') !== 'static')) {\n var containerRect = container.getBoundingClientRect();\n\n // Set relative to edges of padding box of container\n top -= containerRect.top + parseInt(css(container, 'border-top-width'));\n left -= containerRect.left + parseInt(css(container, 'border-left-width'));\n bottom = top + elRect.height;\n right = left + elRect.width;\n break;\n }\n /* jshint boss:true */\n } while (container = container.parentNode);\n }\n }\n if (undoScale && el !== window) {\n // Adjust for scale()\n var elMatrix = matrix(container || el),\n scaleX = elMatrix && elMatrix.a,\n scaleY = elMatrix && elMatrix.d;\n if (elMatrix) {\n top /= scaleY;\n left /= scaleX;\n width /= scaleX;\n height /= scaleY;\n bottom = top + height;\n right = left + width;\n }\n }\n return {\n top: top,\n left: left,\n bottom: bottom,\n right: right,\n width: width,\n height: height\n };\n}\n\n/**\r\n * Checks if a side of an element is scrolled past a side of its parents\r\n * @param {HTMLElement} el The element who's side being scrolled out of view is in question\r\n * @param {String} elSide Side of the element in question ('top', 'left', 'right', 'bottom')\r\n * @param {String} parentSide Side of the parent in question ('top', 'left', 'right', 'bottom')\r\n * @return {HTMLElement} The parent scroll element that the el's side is scrolled past, or null if there is no such element\r\n */\nfunction isScrolledPast(el, elSide, parentSide) {\n var parent = getParentAutoScrollElement(el, true),\n elSideVal = getRect(el)[elSide];\n\n /* jshint boss:true */\n while (parent) {\n var parentSideVal = getRect(parent)[parentSide],\n visible = void 0;\n if (parentSide === 'top' || parentSide === 'left') {\n visible = elSideVal >= parentSideVal;\n } else {\n visible = elSideVal <= parentSideVal;\n }\n if (!visible) return parent;\n if (parent === getWindowScrollingElement()) break;\n parent = getParentAutoScrollElement(parent, false);\n }\n return false;\n}\n\n/**\r\n * Gets nth child of el, ignoring hidden children, sortable's elements (does not ignore clone if it's visible)\r\n * and non-draggable elements\r\n * @param {HTMLElement} el The parent element\r\n * @param {Number} childNum The index of the child\r\n * @param {Object} options Parent Sortable's options\r\n * @return {HTMLElement} The child at index childNum, or null if not found\r\n */\nfunction getChild(el, childNum, options, includeDragEl) {\n var currentChild = 0,\n i = 0,\n children = el.children;\n while (i < children.length) {\n if (children[i].style.display !== 'none' && children[i] !== Sortable.ghost && (includeDragEl || children[i] !== Sortable.dragged) && closest(children[i], options.draggable, el, false)) {\n if (currentChild === childNum) {\n return children[i];\n }\n currentChild++;\n }\n i++;\n }\n return null;\n}\n\n/**\r\n * Gets the last child in the el, ignoring ghostEl or invisible elements (clones)\r\n * @param {HTMLElement} el Parent element\r\n * @param {selector} selector Any other elements that should be ignored\r\n * @return {HTMLElement} The last child, ignoring ghostEl\r\n */\nfunction lastChild(el, selector) {\n var last = el.lastElementChild;\n while (last && (last === Sortable.ghost || css(last, 'display') === 'none' || selector && !matches(last, selector))) {\n last = last.previousElementSibling;\n }\n return last || null;\n}\n\n/**\r\n * Returns the index of an element within its parent for a selected set of\r\n * elements\r\n * @param {HTMLElement} el\r\n * @param {selector} selector\r\n * @return {number}\r\n */\nfunction index(el, selector) {\n var index = 0;\n if (!el || !el.parentNode) {\n return -1;\n }\n\n /* jshint boss:true */\n while (el = el.previousElementSibling) {\n if (el.nodeName.toUpperCase() !== 'TEMPLATE' && el !== Sortable.clone && (!selector || matches(el, selector))) {\n index++;\n }\n }\n return index;\n}\n\n/**\r\n * Returns the scroll offset of the given element, added with all the scroll offsets of parent elements.\r\n * The value is returned in real pixels.\r\n * @param {HTMLElement} el\r\n * @return {Array} Offsets in the format of [left, top]\r\n */\nfunction getRelativeScrollOffset(el) {\n var offsetLeft = 0,\n offsetTop = 0,\n winScroller = getWindowScrollingElement();\n if (el) {\n do {\n var elMatrix = matrix(el),\n scaleX = elMatrix.a,\n scaleY = elMatrix.d;\n offsetLeft += el.scrollLeft * scaleX;\n offsetTop += el.scrollTop * scaleY;\n } while (el !== winScroller && (el = el.parentNode));\n }\n return [offsetLeft, offsetTop];\n}\n\n/**\r\n * Returns the index of the object within the given array\r\n * @param {Array} arr Array that may or may not hold the object\r\n * @param {Object} obj An object that has a key-value pair unique to and identical to a key-value pair in the object you want to find\r\n * @return {Number} The index of the object in the array, or -1\r\n */\nfunction indexOfObject(arr, obj) {\n for (var i in arr) {\n if (!arr.hasOwnProperty(i)) continue;\n for (var key in obj) {\n if (obj.hasOwnProperty(key) && obj[key] === arr[i][key]) return Number(i);\n }\n }\n return -1;\n}\nfunction getParentAutoScrollElement(el, includeSelf) {\n // skip to window\n if (!el || !el.getBoundingClientRect) return getWindowScrollingElement();\n var elem = el;\n var gotSelf = false;\n do {\n // we don't need to get elem css if it isn't even overflowing in the first place (performance)\n if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) {\n var elemCSS = css(elem);\n if (elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') || elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll')) {\n if (!elem.getBoundingClientRect || elem === document.body) return getWindowScrollingElement();\n if (gotSelf || includeSelf) return elem;\n gotSelf = true;\n }\n }\n /* jshint boss:true */\n } while (elem = elem.parentNode);\n return getWindowScrollingElement();\n}\nfunction extend(dst, src) {\n if (dst && src) {\n for (var key in src) {\n if (src.hasOwnProperty(key)) {\n dst[key] = src[key];\n }\n }\n }\n return dst;\n}\nfunction isRectEqual(rect1, rect2) {\n return Math.round(rect1.top) === Math.round(rect2.top) && Math.round(rect1.left) === Math.round(rect2.left) && Math.round(rect1.height) === Math.round(rect2.height) && Math.round(rect1.width) === Math.round(rect2.width);\n}\nvar _throttleTimeout;\nfunction throttle(callback, ms) {\n return function () {\n if (!_throttleTimeout) {\n var args = arguments,\n _this = this;\n if (args.length === 1) {\n callback.call(_this, args[0]);\n } else {\n callback.apply(_this, args);\n }\n _throttleTimeout = setTimeout(function () {\n _throttleTimeout = void 0;\n }, ms);\n }\n };\n}\nfunction cancelThrottle() {\n clearTimeout(_throttleTimeout);\n _throttleTimeout = void 0;\n}\nfunction scrollBy(el, x, y) {\n el.scrollLeft += x;\n el.scrollTop += y;\n}\nfunction clone(el) {\n var Polymer = window.Polymer;\n var $ = window.jQuery || window.Zepto;\n if (Polymer && Polymer.dom) {\n return Polymer.dom(el).cloneNode(true);\n } else if ($) {\n return $(el).clone(true)[0];\n } else {\n return el.cloneNode(true);\n }\n}\nfunction setRect(el, rect) {\n css(el, 'position', 'absolute');\n css(el, 'top', rect.top);\n css(el, 'left', rect.left);\n css(el, 'width', rect.width);\n css(el, 'height', rect.height);\n}\nfunction unsetRect(el) {\n css(el, 'position', '');\n css(el, 'top', '');\n css(el, 'left', '');\n css(el, 'width', '');\n css(el, 'height', '');\n}\nfunction getChildContainingRectFromElement(container, options, ghostEl) {\n var rect = {};\n Array.from(container.children).forEach(function (child) {\n var _rect$left, _rect$top, _rect$right, _rect$bottom;\n if (!closest(child, options.draggable, container, false) || child.animated || child === ghostEl) return;\n var childRect = getRect(child);\n rect.left = Math.min((_rect$left = rect.left) !== null && _rect$left !== void 0 ? _rect$left : Infinity, childRect.left);\n rect.top = Math.min((_rect$top = rect.top) !== null && _rect$top !== void 0 ? _rect$top : Infinity, childRect.top);\n rect.right = Math.max((_rect$right = rect.right) !== null && _rect$right !== void 0 ? _rect$right : -Infinity, childRect.right);\n rect.bottom = Math.max((_rect$bottom = rect.bottom) !== null && _rect$bottom !== void 0 ? _rect$bottom : -Infinity, childRect.bottom);\n });\n rect.width = rect.right - rect.left;\n rect.height = rect.bottom - rect.top;\n rect.x = rect.left;\n rect.y = rect.top;\n return rect;\n}\nvar expando = 'Sortable' + new Date().getTime();\n\nfunction AnimationStateManager() {\n var animationStates = [],\n animationCallbackId;\n return {\n captureAnimationState: function captureAnimationState() {\n animationStates = [];\n if (!this.options.animation) return;\n var children = [].slice.call(this.el.children);\n children.forEach(function (child) {\n if (css(child, 'display') === 'none' || child === Sortable.ghost) return;\n animationStates.push({\n target: child,\n rect: getRect(child)\n });\n var fromRect = _objectSpread2({}, animationStates[animationStates.length - 1].rect);\n\n // If animating: compensate for current animation\n if (child.thisAnimationDuration) {\n var childMatrix = matrix(child, true);\n if (childMatrix) {\n fromRect.top -= childMatrix.f;\n fromRect.left -= childMatrix.e;\n }\n }\n child.fromRect = fromRect;\n });\n },\n addAnimationState: function addAnimationState(state) {\n animationStates.push(state);\n },\n removeAnimationState: function removeAnimationState(target) {\n animationStates.splice(indexOfObject(animationStates, {\n target: target\n }), 1);\n },\n animateAll: function animateAll(callback) {\n var _this = this;\n if (!this.options.animation) {\n clearTimeout(animationCallbackId);\n if (typeof callback === 'function') callback();\n return;\n }\n var animating = false,\n animationTime = 0;\n animationStates.forEach(function (state) {\n var time = 0,\n target = state.target,\n fromRect = target.fromRect,\n toRect = getRect(target),\n prevFromRect = target.prevFromRect,\n prevToRect = target.prevToRect,\n animatingRect = state.rect,\n targetMatrix = matrix(target, true);\n if (targetMatrix) {\n // Compensate for current animation\n toRect.top -= targetMatrix.f;\n toRect.left -= targetMatrix.e;\n }\n target.toRect = toRect;\n if (target.thisAnimationDuration) {\n // Could also check if animatingRect is between fromRect and toRect\n if (isRectEqual(prevFromRect, toRect) && !isRectEqual(fromRect, toRect) &&\n // Make sure animatingRect is on line between toRect & fromRect\n (animatingRect.top - toRect.top) / (animatingRect.left - toRect.left) === (fromRect.top - toRect.top) / (fromRect.left - toRect.left)) {\n // If returning to same place as started from animation and on same axis\n time = calculateRealTime(animatingRect, prevFromRect, prevToRect, _this.options);\n }\n }\n\n // if fromRect != toRect: animate\n if (!isRectEqual(toRect, fromRect)) {\n target.prevFromRect = fromRect;\n target.prevToRect = toRect;\n if (!time) {\n time = _this.options.animation;\n }\n _this.animate(target, animatingRect, toRect, time);\n }\n if (time) {\n animating = true;\n animationTime = Math.max(animationTime, time);\n clearTimeout(target.animationResetTimer);\n target.animationResetTimer = setTimeout(function () {\n target.animationTime = 0;\n target.prevFromRect = null;\n target.fromRect = null;\n target.prevToRect = null;\n target.thisAnimationDuration = null;\n }, time);\n target.thisAnimationDuration = time;\n }\n });\n clearTimeout(animationCallbackId);\n if (!animating) {\n if (typeof callback === 'function') callback();\n } else {\n animationCallbackId = setTimeout(function () {\n if (typeof callback === 'function') callback();\n }, animationTime);\n }\n animationStates = [];\n },\n animate: function animate(target, currentRect, toRect, duration) {\n if (duration) {\n css(target, 'transition', '');\n css(target, 'transform', '');\n var elMatrix = matrix(this.el),\n scaleX = elMatrix && elMatrix.a,\n scaleY = elMatrix && elMatrix.d,\n translateX = (currentRect.left - toRect.left) / (scaleX || 1),\n translateY = (currentRect.top - toRect.top) / (scaleY || 1);\n target.animatingX = !!translateX;\n target.animatingY = !!translateY;\n css(target, 'transform', 'translate3d(' + translateX + 'px,' + translateY + 'px,0)');\n this.forRepaintDummy = repaint(target); // repaint\n\n css(target, 'transition', 'transform ' + duration + 'ms' + (this.options.easing ? ' ' + this.options.easing : ''));\n css(target, 'transform', 'translate3d(0,0,0)');\n typeof target.animated === 'number' && clearTimeout(target.animated);\n target.animated = setTimeout(function () {\n css(target, 'transition', '');\n css(target, 'transform', '');\n target.animated = false;\n target.animatingX = false;\n target.animatingY = false;\n }, duration);\n }\n }\n };\n}\nfunction repaint(target) {\n return target.offsetWidth;\n}\nfunction calculateRealTime(animatingRect, fromRect, toRect, options) {\n return Math.sqrt(Math.pow(fromRect.top - animatingRect.top, 2) + Math.pow(fromRect.left - animatingRect.left, 2)) / Math.sqrt(Math.pow(fromRect.top - toRect.top, 2) + Math.pow(fromRect.left - toRect.left, 2)) * options.animation;\n}\n\nvar plugins = [];\nvar defaults = {\n initializeByDefault: true\n};\nvar PluginManager = {\n mount: function mount(plugin) {\n // Set default static properties\n for (var option in defaults) {\n if (defaults.hasOwnProperty(option) && !(option in plugin)) {\n plugin[option] = defaults[option];\n }\n }\n plugins.forEach(function (p) {\n if (p.pluginName === plugin.pluginName) {\n throw \"Sortable: Cannot mount plugin \".concat(plugin.pluginName, \" more than once\");\n }\n });\n plugins.push(plugin);\n },\n pluginEvent: function pluginEvent(eventName, sortable, evt) {\n var _this = this;\n this.eventCanceled = false;\n evt.cancel = function () {\n _this.eventCanceled = true;\n };\n var eventNameGlobal = eventName + 'Global';\n plugins.forEach(function (plugin) {\n if (!sortable[plugin.pluginName]) return;\n // Fire global events if it exists in this sortable\n if (sortable[plugin.pluginName][eventNameGlobal]) {\n sortable[plugin.pluginName][eventNameGlobal](_objectSpread2({\n sortable: sortable\n }, evt));\n }\n\n // Only fire plugin event if plugin is enabled in this sortable,\n // and plugin has event defined\n if (sortable.options[plugin.pluginName] && sortable[plugin.pluginName][eventName]) {\n sortable[plugin.pluginName][eventName](_objectSpread2({\n sortable: sortable\n }, evt));\n }\n });\n },\n initializePlugins: function initializePlugins(sortable, el, defaults, options) {\n plugins.forEach(function (plugin) {\n var pluginName = plugin.pluginName;\n if (!sortable.options[pluginName] && !plugin.initializeByDefault) return;\n var initialized = new plugin(sortable, el, sortable.options);\n initialized.sortable = sortable;\n initialized.options = sortable.options;\n sortable[pluginName] = initialized;\n\n // Add default options from plugin\n _extends(defaults, initialized.defaults);\n });\n for (var option in sortable.options) {\n if (!sortable.options.hasOwnProperty(option)) continue;\n var modified = this.modifyOption(sortable, option, sortable.options[option]);\n if (typeof modified !== 'undefined') {\n sortable.options[option] = modified;\n }\n }\n },\n getEventProperties: function getEventProperties(name, sortable) {\n var eventProperties = {};\n plugins.forEach(function (plugin) {\n if (typeof plugin.eventProperties !== 'function') return;\n _extends(eventProperties, plugin.eventProperties.call(sortable[plugin.pluginName], name));\n });\n return eventProperties;\n },\n modifyOption: function modifyOption(sortable, name, value) {\n var modifiedValue;\n plugins.forEach(function (plugin) {\n // Plugin must exist on the Sortable\n if (!sortable[plugin.pluginName]) return;\n\n // If static option listener exists for this option, call in the context of the Sortable's instance of this plugin\n if (plugin.optionListeners && typeof plugin.optionListeners[name] === 'function') {\n modifiedValue = plugin.optionListeners[name].call(sortable[plugin.pluginName], value);\n }\n });\n return modifiedValue;\n }\n};\n\nfunction dispatchEvent(_ref) {\n var sortable = _ref.sortable,\n rootEl = _ref.rootEl,\n name = _ref.name,\n targetEl = _ref.targetEl,\n cloneEl = _ref.cloneEl,\n toEl = _ref.toEl,\n fromEl = _ref.fromEl,\n oldIndex = _ref.oldIndex,\n newIndex = _ref.newIndex,\n oldDraggableIndex = _ref.oldDraggableIndex,\n newDraggableIndex = _ref.newDraggableIndex,\n originalEvent = _ref.originalEvent,\n putSortable = _ref.putSortable,\n extraEventProperties = _ref.extraEventProperties;\n sortable = sortable || rootEl && rootEl[expando];\n if (!sortable) return;\n var evt,\n options = sortable.options,\n onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1);\n // Support for new CustomEvent feature\n if (window.CustomEvent && !IE11OrLess && !Edge) {\n evt = new CustomEvent(name, {\n bubbles: true,\n cancelable: true\n });\n } else {\n evt = document.createEvent('Event');\n evt.initEvent(name, true, true);\n }\n evt.to = toEl || rootEl;\n evt.from = fromEl || rootEl;\n evt.item = targetEl || rootEl;\n evt.clone = cloneEl;\n evt.oldIndex = oldIndex;\n evt.newIndex = newIndex;\n evt.oldDraggableIndex = oldDraggableIndex;\n evt.newDraggableIndex = newDraggableIndex;\n evt.originalEvent = originalEvent;\n evt.pullMode = putSortable ? putSortable.lastPutMode : undefined;\n var allEventProperties = _objectSpread2(_objectSpread2({}, extraEventProperties), PluginManager.getEventProperties(name, sortable));\n for (var option in allEventProperties) {\n evt[option] = allEventProperties[option];\n }\n if (rootEl) {\n rootEl.dispatchEvent(evt);\n }\n if (options[onName]) {\n options[onName].call(sortable, evt);\n }\n}\n\nvar _excluded = [\"evt\"];\nvar pluginEvent = function pluginEvent(eventName, sortable) {\n var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},\n originalEvent = _ref.evt,\n data = _objectWithoutProperties(_ref, _excluded);\n PluginManager.pluginEvent.bind(Sortable)(eventName, sortable, _objectSpread2({\n dragEl: dragEl,\n parentEl: parentEl,\n ghostEl: ghostEl,\n rootEl: rootEl,\n nextEl: nextEl,\n lastDownEl: lastDownEl,\n cloneEl: cloneEl,\n cloneHidden: cloneHidden,\n dragStarted: moved,\n putSortable: putSortable,\n activeSortable: Sortable.active,\n originalEvent: originalEvent,\n oldIndex: oldIndex,\n oldDraggableIndex: oldDraggableIndex,\n newIndex: newIndex,\n newDraggableIndex: newDraggableIndex,\n hideGhostForTarget: _hideGhostForTarget,\n unhideGhostForTarget: _unhideGhostForTarget,\n cloneNowHidden: function cloneNowHidden() {\n cloneHidden = true;\n },\n cloneNowShown: function cloneNowShown() {\n cloneHidden = false;\n },\n dispatchSortableEvent: function dispatchSortableEvent(name) {\n _dispatchEvent({\n sortable: sortable,\n name: name,\n originalEvent: originalEvent\n });\n }\n }, data));\n};\nfunction _dispatchEvent(info) {\n dispatchEvent(_objectSpread2({\n putSortable: putSortable,\n cloneEl: cloneEl,\n targetEl: dragEl,\n rootEl: rootEl,\n oldIndex: oldIndex,\n oldDraggableIndex: oldDraggableIndex,\n newIndex: newIndex,\n newDraggableIndex: newDraggableIndex\n }, info));\n}\nvar dragEl,\n parentEl,\n ghostEl,\n rootEl,\n nextEl,\n lastDownEl,\n cloneEl,\n cloneHidden,\n oldIndex,\n newIndex,\n oldDraggableIndex,\n newDraggableIndex,\n activeGroup,\n putSortable,\n awaitingDragStarted = false,\n ignoreNextClick = false,\n sortables = [],\n tapEvt,\n touchEvt,\n lastDx,\n lastDy,\n tapDistanceLeft,\n tapDistanceTop,\n moved,\n lastTarget,\n lastDirection,\n pastFirstInvertThresh = false,\n isCircumstantialInvert = false,\n targetMoveDistance,\n // For positioning ghost absolutely\n ghostRelativeParent,\n ghostRelativeParentInitialScroll = [],\n // (left, top)\n\n _silent = false,\n savedInputChecked = [];\n\n/** @const */\nvar documentExists = typeof document !== 'undefined',\n PositionGhostAbsolutely = IOS,\n CSSFloatProperty = Edge || IE11OrLess ? 'cssFloat' : 'float',\n // This will not pass for IE9, because IE9 DnD only works on anchors\n supportDraggable = documentExists && !ChromeForAndroid && !IOS && 'draggable' in document.createElement('div'),\n supportCssPointerEvents = function () {\n if (!documentExists) return;\n // false when <= IE11\n if (IE11OrLess) {\n return false;\n }\n var el = document.createElement('x');\n el.style.cssText = 'pointer-events:auto';\n return el.style.pointerEvents === 'auto';\n }(),\n _detectDirection = function _detectDirection(el, options) {\n var elCSS = css(el),\n elWidth = parseInt(elCSS.width) - parseInt(elCSS.paddingLeft) - parseInt(elCSS.paddingRight) - parseInt(elCSS.borderLeftWidth) - parseInt(elCSS.borderRightWidth),\n child1 = getChild(el, 0, options),\n child2 = getChild(el, 1, options),\n firstChildCSS = child1 && css(child1),\n secondChildCSS = child2 && css(child2),\n firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + getRect(child1).width,\n secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + getRect(child2).width;\n if (elCSS.display === 'flex') {\n return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse' ? 'vertical' : 'horizontal';\n }\n if (elCSS.display === 'grid') {\n return elCSS.gridTemplateColumns.split(' ').length <= 1 ? 'vertical' : 'horizontal';\n }\n if (child1 && firstChildCSS[\"float\"] && firstChildCSS[\"float\"] !== 'none') {\n var touchingSideChild2 = firstChildCSS[\"float\"] === 'left' ? 'left' : 'right';\n return child2 && (secondChildCSS.clear === 'both' || secondChildCSS.clear === touchingSideChild2) ? 'vertical' : 'horizontal';\n }\n return child1 && (firstChildCSS.display === 'block' || firstChildCSS.display === 'flex' || firstChildCSS.display === 'table' || firstChildCSS.display === 'grid' || firstChildWidth >= elWidth && elCSS[CSSFloatProperty] === 'none' || child2 && elCSS[CSSFloatProperty] === 'none' && firstChildWidth + secondChildWidth > elWidth) ? 'vertical' : 'horizontal';\n },\n _dragElInRowColumn = function _dragElInRowColumn(dragRect, targetRect, vertical) {\n var dragElS1Opp = vertical ? dragRect.left : dragRect.top,\n dragElS2Opp = vertical ? dragRect.right : dragRect.bottom,\n dragElOppLength = vertical ? dragRect.width : dragRect.height,\n targetS1Opp = vertical ? targetRect.left : targetRect.top,\n targetS2Opp = vertical ? targetRect.right : targetRect.bottom,\n targetOppLength = vertical ? targetRect.width : targetRect.height;\n return dragElS1Opp === targetS1Opp || dragElS2Opp === targetS2Opp || dragElS1Opp + dragElOppLength / 2 === targetS1Opp + targetOppLength / 2;\n },\n /**\r\n * Detects first nearest empty sortable to X and Y position using emptyInsertThreshold.\r\n * @param {Number} x X position\r\n * @param {Number} y Y position\r\n * @return {HTMLElement} Element of the first found nearest Sortable\r\n */\n _detectNearestEmptySortable = function _detectNearestEmptySortable(x, y) {\n var ret;\n sortables.some(function (sortable) {\n var threshold = sortable[expando].options.emptyInsertThreshold;\n if (!threshold || lastChild(sortable)) return;\n var rect = getRect(sortable),\n insideHorizontally = x >= rect.left - threshold && x <= rect.right + threshold,\n insideVertically = y >= rect.top - threshold && y <= rect.bottom + threshold;\n if (insideHorizontally && insideVertically) {\n return ret = sortable;\n }\n });\n return ret;\n },\n _prepareGroup = function _prepareGroup(options) {\n function toFn(value, pull) {\n return function (to, from, dragEl, evt) {\n var sameGroup = to.options.group.name && from.options.group.name && to.options.group.name === from.options.group.name;\n if (value == null && (pull || sameGroup)) {\n // Default pull value\n // Default pull and put value if same group\n return true;\n } else if (value == null || value === false) {\n return false;\n } else if (pull && value === 'clone') {\n return value;\n } else if (typeof value === 'function') {\n return toFn(value(to, from, dragEl, evt), pull)(to, from, dragEl, evt);\n } else {\n var otherGroup = (pull ? to : from).options.group.name;\n return value === true || typeof value === 'string' && value === otherGroup || value.join && value.indexOf(otherGroup) > -1;\n }\n };\n }\n var group = {};\n var originalGroup = options.group;\n if (!originalGroup || _typeof(originalGroup) != 'object') {\n originalGroup = {\n name: originalGroup\n };\n }\n group.name = originalGroup.name;\n group.checkPull = toFn(originalGroup.pull, true);\n group.checkPut = toFn(originalGroup.put);\n group.revertClone = originalGroup.revertClone;\n options.group = group;\n },\n _hideGhostForTarget = function _hideGhostForTarget() {\n if (!supportCssPointerEvents && ghostEl) {\n css(ghostEl, 'display', 'none');\n }\n },\n _unhideGhostForTarget = function _unhideGhostForTarget() {\n if (!supportCssPointerEvents && ghostEl) {\n css(ghostEl, 'display', '');\n }\n };\n\n// #1184 fix - Prevent click event on fallback if dragged but item not changed position\nif (documentExists && !ChromeForAndroid) {\n document.addEventListener('click', function (evt) {\n if (ignoreNextClick) {\n evt.preventDefault();\n evt.stopPropagation && evt.stopPropagation();\n evt.stopImmediatePropagation && evt.stopImmediatePropagation();\n ignoreNextClick = false;\n return false;\n }\n }, true);\n}\nvar nearestEmptyInsertDetectEvent = function nearestEmptyInsertDetectEvent(evt) {\n if (dragEl) {\n evt = evt.touches ? evt.touches[0] : evt;\n var nearest = _detectNearestEmptySortable(evt.clientX, evt.clientY);\n if (nearest) {\n // Create imitation event\n var event = {};\n for (var i in evt) {\n if (evt.hasOwnProperty(i)) {\n event[i] = evt[i];\n }\n }\n event.target = event.rootEl = nearest;\n event.preventDefault = void 0;\n event.stopPropagation = void 0;\n nearest[expando]._onDragOver(event);\n }\n }\n};\nvar _checkOutsideTargetEl = function _checkOutsideTargetEl(evt) {\n if (dragEl) {\n dragEl.parentNode[expando]._isOutsideThisEl(evt.target);\n }\n};\n\n/**\r\n * @class Sortable\r\n * @param {HTMLElement} el\r\n * @param {Object} [options]\r\n */\nfunction Sortable(el, options) {\n if (!(el && el.nodeType && el.nodeType === 1)) {\n throw \"Sortable: `el` must be an HTMLElement, not \".concat({}.toString.call(el));\n }\n this.el = el; // root element\n this.options = options = _extends({}, options);\n\n // Export instance\n el[expando] = this;\n var defaults = {\n group: null,\n sort: true,\n disabled: false,\n store: null,\n handle: null,\n draggable: /^[uo]l$/i.test(el.nodeName) ? '>li' : '>*',\n swapThreshold: 1,\n // percentage; 0 <= x <= 1\n invertSwap: false,\n // invert always\n invertedSwapThreshold: null,\n // will be set to same as swapThreshold if default\n removeCloneOnHide: true,\n direction: function direction() {\n return _detectDirection(el, this.options);\n },\n ghostClass: 'sortable-ghost',\n chosenClass: 'sortable-chosen',\n dragClass: 'sortable-drag',\n ignore: 'a, img',\n filter: null,\n preventOnFilter: true,\n animation: 0,\n easing: null,\n setData: function setData(dataTransfer, dragEl) {\n dataTransfer.setData('Text', dragEl.textContent);\n },\n dropBubble: false,\n dragoverBubble: false,\n dataIdAttr: 'data-id',\n delay: 0,\n delayOnTouchOnly: false,\n touchStartThreshold: (Number.parseInt ? Number : window).parseInt(window.devicePixelRatio, 10) || 1,\n forceFallback: false,\n fallbackClass: 'sortable-fallback',\n fallbackOnBody: false,\n fallbackTolerance: 0,\n fallbackOffset: {\n x: 0,\n y: 0\n },\n // Disabled on Safari: #1571; Enabled on Safari IOS: #2244\n supportPointer: Sortable.supportPointer !== false && 'PointerEvent' in window && (!Safari || IOS),\n emptyInsertThreshold: 5\n };\n PluginManager.initializePlugins(this, el, defaults);\n\n // Set default options\n for (var name in defaults) {\n !(name in options) && (options[name] = defaults[name]);\n }\n _prepareGroup(options);\n\n // Bind all private methods\n for (var fn in this) {\n if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {\n this[fn] = this[fn].bind(this);\n }\n }\n\n // Setup drag mode\n this.nativeDraggable = options.forceFallback ? false : supportDraggable;\n if (this.nativeDraggable) {\n // Touch start threshold cannot be greater than the native dragstart threshold\n this.options.touchStartThreshold = 1;\n }\n\n // Bind events\n if (options.supportPointer) {\n on(el, 'pointerdown', this._onTapStart);\n } else {\n on(el, 'mousedown', this._onTapStart);\n on(el, 'touchstart', this._onTapStart);\n }\n if (this.nativeDraggable) {\n on(el, 'dragover', this);\n on(el, 'dragenter', this);\n }\n sortables.push(this.el);\n\n // Restore sorting\n options.store && options.store.get && this.sort(options.store.get(this) || []);\n\n // Add animation state manager\n _extends(this, AnimationStateManager());\n}\nSortable.prototype = /** @lends Sortable.prototype */{\n constructor: Sortable,\n _isOutsideThisEl: function _isOutsideThisEl(target) {\n if (!this.el.contains(target) && target !== this.el) {\n lastTarget = null;\n }\n },\n _getDirection: function _getDirection(evt, target) {\n return typeof this.options.direction === 'function' ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction;\n },\n _onTapStart: function _onTapStart( /** Event|TouchEvent */evt) {\n if (!evt.cancelable) return;\n var _this = this,\n el = this.el,\n options = this.options,\n preventOnFilter = options.preventOnFilter,\n type = evt.type,\n touch = evt.touches && evt.touches[0] || evt.pointerType && evt.pointerType === 'touch' && evt,\n target = (touch || evt).target,\n originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0] || evt.composedPath && evt.composedPath()[0]) || target,\n filter = options.filter;\n _saveInputCheckedState(el);\n\n // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group.\n if (dragEl) {\n return;\n }\n if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) {\n return; // only left button and enabled\n }\n\n // cancel dnd if original target is content editable\n if (originalTarget.isContentEditable) {\n return;\n }\n\n // Safari ignores further event handling after mousedown\n if (!this.nativeDraggable && Safari && target && target.tagName.toUpperCase() === 'SELECT') {\n return;\n }\n target = closest(target, options.draggable, el, false);\n if (target && target.animated) {\n return;\n }\n if (lastDownEl === target) {\n // Ignoring duplicate `down`\n return;\n }\n\n // Get the index of the dragged element within its parent\n oldIndex = index(target);\n oldDraggableIndex = index(target, options.draggable);\n\n // Check filter\n if (typeof filter === 'function') {\n if (filter.call(this, evt, target, this)) {\n _dispatchEvent({\n sortable: _this,\n rootEl: originalTarget,\n name: 'filter',\n targetEl: target,\n toEl: el,\n fromEl: el\n });\n pluginEvent('filter', _this, {\n evt: evt\n });\n preventOnFilter && evt.preventDefault();\n return; // cancel dnd\n }\n } else if (filter) {\n filter = filter.split(',').some(function (criteria) {\n criteria = closest(originalTarget, criteria.trim(), el, false);\n if (criteria) {\n _dispatchEvent({\n sortable: _this,\n rootEl: criteria,\n name: 'filter',\n targetEl: target,\n fromEl: el,\n toEl: el\n });\n pluginEvent('filter', _this, {\n evt: evt\n });\n return true;\n }\n });\n if (filter) {\n preventOnFilter && evt.preventDefault();\n return; // cancel dnd\n }\n }\n if (options.handle && !closest(originalTarget, options.handle, el, false)) {\n return;\n }\n\n // Prepare `dragstart`\n this._prepareDragStart(evt, touch, target);\n },\n _prepareDragStart: function _prepareDragStart( /** Event */evt, /** Touch */touch, /** HTMLElement */target) {\n var _this = this,\n el = _this.el,\n options = _this.options,\n ownerDocument = el.ownerDocument,\n dragStartFn;\n if (target && !dragEl && target.parentNode === el) {\n var dragRect = getRect(target);\n rootEl = el;\n dragEl = target;\n parentEl = dragEl.parentNode;\n nextEl = dragEl.nextSibling;\n lastDownEl = target;\n activeGroup = options.group;\n Sortable.dragged = dragEl;\n tapEvt = {\n target: dragEl,\n clientX: (touch || evt).clientX,\n clientY: (touch || evt).clientY\n };\n tapDistanceLeft = tapEvt.clientX - dragRect.left;\n tapDistanceTop = tapEvt.clientY - dragRect.top;\n this._lastX = (touch || evt).clientX;\n this._lastY = (touch || evt).clientY;\n dragEl.style['will-change'] = 'all';\n dragStartFn = function dragStartFn() {\n pluginEvent('delayEnded', _this, {\n evt: evt\n });\n if (Sortable.eventCanceled) {\n _this._onDrop();\n return;\n }\n // Delayed drag has been triggered\n // we can re-enable the events: touchmove/mousemove\n _this._disableDelayedDragEvents();\n if (!FireFox && _this.nativeDraggable) {\n dragEl.draggable = true;\n }\n\n // Bind the events: dragstart/dragend\n _this._triggerDragStart(evt, touch);\n\n // Drag start event\n _dispatchEvent({\n sortable: _this,\n name: 'choose',\n originalEvent: evt\n });\n\n // Chosen item\n toggleClass(dragEl, options.chosenClass, true);\n };\n\n // Disable \"draggable\"\n options.ignore.split(',').forEach(function (criteria) {\n find(dragEl, criteria.trim(), _disableDraggable);\n });\n on(ownerDocument, 'dragover', nearestEmptyInsertDetectEvent);\n on(ownerDocument, 'mousemove', nearestEmptyInsertDetectEvent);\n on(ownerDocument, 'touchmove', nearestEmptyInsertDetectEvent);\n if (options.supportPointer) {\n on(ownerDocument, 'pointerup', _this._onDrop);\n // Native D&D triggers pointercancel\n !this.nativeDraggable && on(ownerDocument, 'pointercancel', _this._onDrop);\n } else {\n on(ownerDocument, 'mouseup', _this._onDrop);\n on(ownerDocument, 'touchend', _this._onDrop);\n on(ownerDocument, 'touchcancel', _this._onDrop);\n }\n\n // Make dragEl draggable (must be before delay for FireFox)\n if (FireFox && this.nativeDraggable) {\n this.options.touchStartThreshold = 4;\n dragEl.draggable = true;\n }\n pluginEvent('delayStart', this, {\n evt: evt\n });\n\n // Delay is impossible for native DnD in Edge or IE\n if (options.delay && (!options.delayOnTouchOnly || touch) && (!this.nativeDraggable || !(Edge || IE11OrLess))) {\n if (Sortable.eventCanceled) {\n this._onDrop();\n return;\n }\n // If the user moves the pointer or let go the click or touch\n // before the delay has been reached:\n // disable the delayed drag\n if (options.supportPointer) {\n on(ownerDocument, 'pointerup', _this._disableDelayedDrag);\n on(ownerDocument, 'pointercancel', _this._disableDelayedDrag);\n } else {\n on(ownerDocument, 'mouseup', _this._disableDelayedDrag);\n on(ownerDocument, 'touchend', _this._disableDelayedDrag);\n on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);\n }\n on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler);\n on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler);\n options.supportPointer && on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler);\n _this._dragStartTimer = setTimeout(dragStartFn, options.delay);\n } else {\n dragStartFn();\n }\n }\n },\n _delayedDragTouchMoveHandler: function _delayedDragTouchMoveHandler( /** TouchEvent|PointerEvent **/e) {\n var touch = e.touches ? e.touches[0] : e;\n if (Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) >= Math.floor(this.options.touchStartThreshold / (this.nativeDraggable && window.devicePixelRatio || 1))) {\n this._disableDelayedDrag();\n }\n },\n _disableDelayedDrag: function _disableDelayedDrag() {\n dragEl && _disableDraggable(dragEl);\n clearTimeout(this._dragStartTimer);\n this._disableDelayedDragEvents();\n },\n _disableDelayedDragEvents: function _disableDelayedDragEvents() {\n var ownerDocument = this.el.ownerDocument;\n off(ownerDocument, 'mouseup', this._disableDelayedDrag);\n off(ownerDocument, 'touchend', this._disableDelayedDrag);\n off(ownerDocument, 'touchcancel', this._disableDelayedDrag);\n off(ownerDocument, 'pointerup', this._disableDelayedDrag);\n off(ownerDocument, 'pointercancel', this._disableDelayedDrag);\n off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler);\n off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler);\n off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler);\n },\n _triggerDragStart: function _triggerDragStart( /** Event */evt, /** Touch */touch) {\n touch = touch || evt.pointerType == 'touch' && evt;\n if (!this.nativeDraggable || touch) {\n if (this.options.supportPointer) {\n on(document, 'pointermove', this._onTouchMove);\n } else if (touch) {\n on(document, 'touchmove', this._onTouchMove);\n } else {\n on(document, 'mousemove', this._onTouchMove);\n }\n } else {\n on(dragEl, 'dragend', this);\n on(rootEl, 'dragstart', this._onDragStart);\n }\n try {\n if (document.selection) {\n _nextTick(function () {\n document.selection.empty();\n });\n } else {\n window.getSelection().removeAllRanges();\n }\n } catch (err) {}\n },\n _dragStarted: function _dragStarted(fallback, evt) {\n awaitingDragStarted = false;\n if (rootEl && dragEl) {\n pluginEvent('dragStarted', this, {\n evt: evt\n });\n if (this.nativeDraggable) {\n on(document, 'dragover', _checkOutsideTargetEl);\n }\n var options = this.options;\n\n // Apply effect\n !fallback && toggleClass(dragEl, options.dragClass, false);\n toggleClass(dragEl, options.ghostClass, true);\n Sortable.active = this;\n fallback && this._appendGhost();\n\n // Drag start event\n _dispatchEvent({\n sortable: this,\n name: 'start',\n originalEvent: evt\n });\n } else {\n this._nulling();\n }\n },\n _emulateDragOver: function _emulateDragOver() {\n if (touchEvt) {\n this._lastX = touchEvt.clientX;\n this._lastY = touchEvt.clientY;\n _hideGhostForTarget();\n var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY);\n var parent = target;\n while (target && target.shadowRoot) {\n target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY);\n if (target === parent) break;\n parent = target;\n }\n dragEl.parentNode[expando]._isOutsideThisEl(target);\n if (parent) {\n do {\n if (parent[expando]) {\n var inserted = void 0;\n inserted = parent[expando]._onDragOver({\n clientX: touchEvt.clientX,\n clientY: touchEvt.clientY,\n target: target,\n rootEl: parent\n });\n if (inserted && !this.options.dragoverBubble) {\n break;\n }\n }\n target = parent; // store last element\n }\n /* jshint boss:true */ while (parent = getParentOrHost(parent));\n }\n _unhideGhostForTarget();\n }\n },\n _onTouchMove: function _onTouchMove( /**TouchEvent*/evt) {\n if (tapEvt) {\n var options = this.options,\n fallbackTolerance = options.fallbackTolerance,\n fallbackOffset = options.fallbackOffset,\n touch = evt.touches ? evt.touches[0] : evt,\n ghostMatrix = ghostEl && matrix(ghostEl, true),\n scaleX = ghostEl && ghostMatrix && ghostMatrix.a,\n scaleY = ghostEl && ghostMatrix && ghostMatrix.d,\n relativeScrollOffset = PositionGhostAbsolutely && ghostRelativeParent && getRelativeScrollOffset(ghostRelativeParent),\n dx = (touch.clientX - tapEvt.clientX + fallbackOffset.x) / (scaleX || 1) + (relativeScrollOffset ? relativeScrollOffset[0] - ghostRelativeParentInitialScroll[0] : 0) / (scaleX || 1),\n dy = (touch.clientY - tapEvt.clientY + fallbackOffset.y) / (scaleY || 1) + (relativeScrollOffset ? relativeScrollOffset[1] - ghostRelativeParentInitialScroll[1] : 0) / (scaleY || 1);\n\n // only set the status to dragging, when we are actually dragging\n if (!Sortable.active && !awaitingDragStarted) {\n if (fallbackTolerance && Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) < fallbackTolerance) {\n return;\n }\n this._onDragStart(evt, true);\n }\n if (ghostEl) {\n if (ghostMatrix) {\n ghostMatrix.e += dx - (lastDx || 0);\n ghostMatrix.f += dy - (lastDy || 0);\n } else {\n ghostMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n e: dx,\n f: dy\n };\n }\n var cssMatrix = \"matrix(\".concat(ghostMatrix.a, \",\").concat(ghostMatrix.b, \",\").concat(ghostMatrix.c, \",\").concat(ghostMatrix.d, \",\").concat(ghostMatrix.e, \",\").concat(ghostMatrix.f, \")\");\n css(ghostEl, 'webkitTransform', cssMatrix);\n css(ghostEl, 'mozTransform', cssMatrix);\n css(ghostEl, 'msTransform', cssMatrix);\n css(ghostEl, 'transform', cssMatrix);\n lastDx = dx;\n lastDy = dy;\n touchEvt = touch;\n }\n evt.cancelable && evt.preventDefault();\n }\n },\n _appendGhost: function _appendGhost() {\n // Bug if using scale(): https://stackoverflow.com/questions/2637058\n // Not being adjusted for\n if (!ghostEl) {\n var container = this.options.fallbackOnBody ? document.body : rootEl,\n rect = getRect(dragEl, true, PositionGhostAbsolutely, true, container),\n options = this.options;\n\n // Position absolutely\n if (PositionGhostAbsolutely) {\n // Get relatively positioned parent\n ghostRelativeParent = container;\n while (css(ghostRelativeParent, 'position') === 'static' && css(ghostRelativeParent, 'transform') === 'none' && ghostRelativeParent !== document) {\n ghostRelativeParent = ghostRelativeParent.parentNode;\n }\n if (ghostRelativeParent !== document.body && ghostRelativeParent !== document.documentElement) {\n if (ghostRelativeParent === document) ghostRelativeParent = getWindowScrollingElement();\n rect.top += ghostRelativeParent.scrollTop;\n rect.left += ghostRelativeParent.scrollLeft;\n } else {\n ghostRelativeParent = getWindowScrollingElement();\n }\n ghostRelativeParentInitialScroll = getRelativeScrollOffset(ghostRelativeParent);\n }\n ghostEl = dragEl.cloneNode(true);\n toggleClass(ghostEl, options.ghostClass, false);\n toggleClass(ghostEl, options.fallbackClass, true);\n toggleClass(ghostEl, options.dragClass, true);\n css(ghostEl, 'transition', '');\n css(ghostEl, 'transform', '');\n css(ghostEl, 'box-sizing', 'border-box');\n css(ghostEl, 'margin', 0);\n css(ghostEl, 'top', rect.top);\n css(ghostEl, 'left', rect.left);\n css(ghostEl, 'width', rect.width);\n css(ghostEl, 'height', rect.height);\n css(ghostEl, 'opacity', '0.8');\n css(ghostEl, 'position', PositionGhostAbsolutely ? 'absolute' : 'fixed');\n css(ghostEl, 'zIndex', '100000');\n css(ghostEl, 'pointerEvents', 'none');\n Sortable.ghost = ghostEl;\n container.appendChild(ghostEl);\n\n // Set transform-origin\n css(ghostEl, 'transform-origin', tapDistanceLeft / parseInt(ghostEl.style.width) * 100 + '% ' + tapDistanceTop / parseInt(ghostEl.style.height) * 100 + '%');\n }\n },\n _onDragStart: function _onDragStart( /**Event*/evt, /**boolean*/fallback) {\n var _this = this;\n var dataTransfer = evt.dataTransfer;\n var options = _this.options;\n pluginEvent('dragStart', this, {\n evt: evt\n });\n if (Sortable.eventCanceled) {\n this._onDrop();\n return;\n }\n pluginEvent('setupClone', this);\n if (!Sortable.eventCanceled) {\n cloneEl = clone(dragEl);\n cloneEl.removeAttribute(\"id\");\n cloneEl.draggable = false;\n cloneEl.style['will-change'] = '';\n this._hideClone();\n toggleClass(cloneEl, this.options.chosenClass, false);\n Sortable.clone = cloneEl;\n }\n\n // #1143: IFrame support workaround\n _this.cloneId = _nextTick(function () {\n pluginEvent('clone', _this);\n if (Sortable.eventCanceled) return;\n if (!_this.options.removeCloneOnHide) {\n rootEl.insertBefore(cloneEl, dragEl);\n }\n _this._hideClone();\n _dispatchEvent({\n sortable: _this,\n name: 'clone'\n });\n });\n !fallback && toggleClass(dragEl, options.dragClass, true);\n\n // Set proper drop events\n if (fallback) {\n ignoreNextClick = true;\n _this._loopId = setInterval(_this._emulateDragOver, 50);\n } else {\n // Undo what was set in _prepareDragStart before drag started\n off(document, 'mouseup', _this._onDrop);\n off(document, 'touchend', _this._onDrop);\n off(document, 'touchcancel', _this._onDrop);\n if (dataTransfer) {\n dataTransfer.effectAllowed = 'move';\n options.setData && options.setData.call(_this, dataTransfer, dragEl);\n }\n on(document, 'drop', _this);\n\n // #1276 fix:\n css(dragEl, 'transform', 'translateZ(0)');\n }\n awaitingDragStarted = true;\n _this._dragStartId = _nextTick(_this._dragStarted.bind(_this, fallback, evt));\n on(document, 'selectstart', _this);\n moved = true;\n window.getSelection().removeAllRanges();\n if (Safari) {\n css(document.body, 'user-select', 'none');\n }\n },\n // Returns true - if no further action is needed (either inserted or another condition)\n _onDragOver: function _onDragOver( /**Event*/evt) {\n var el = this.el,\n target = evt.target,\n dragRect,\n targetRect,\n revert,\n options = this.options,\n group = options.group,\n activeSortable = Sortable.active,\n isOwner = activeGroup === group,\n canSort = options.sort,\n fromSortable = putSortable || activeSortable,\n vertical,\n _this = this,\n completedFired = false;\n if (_silent) return;\n function dragOverEvent(name, extra) {\n pluginEvent(name, _this, _objectSpread2({\n evt: evt,\n isOwner: isOwner,\n axis: vertical ? 'vertical' : 'horizontal',\n revert: revert,\n dragRect: dragRect,\n targetRect: targetRect,\n canSort: canSort,\n fromSortable: fromSortable,\n target: target,\n completed: completed,\n onMove: function onMove(target, after) {\n return _onMove(rootEl, el, dragEl, dragRect, target, getRect(target), evt, after);\n },\n changed: changed\n }, extra));\n }\n\n // Capture animation state\n function capture() {\n dragOverEvent('dragOverAnimationCapture');\n _this.captureAnimationState();\n if (_this !== fromSortable) {\n fromSortable.captureAnimationState();\n }\n }\n\n // Return invocation when dragEl is inserted (or completed)\n function completed(insertion) {\n dragOverEvent('dragOverCompleted', {\n insertion: insertion\n });\n if (insertion) {\n // Clones must be hidden before folding animation to capture dragRectAbsolute properly\n if (isOwner) {\n activeSortable._hideClone();\n } else {\n activeSortable._showClone(_this);\n }\n if (_this !== fromSortable) {\n // Set ghost class to new sortable's ghost class\n toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : activeSortable.options.ghostClass, false);\n toggleClass(dragEl, options.ghostClass, true);\n }\n if (putSortable !== _this && _this !== Sortable.active) {\n putSortable = _this;\n } else if (_this === Sortable.active && putSortable) {\n putSortable = null;\n }\n\n // Animation\n if (fromSortable === _this) {\n _this._ignoreWhileAnimating = target;\n }\n _this.animateAll(function () {\n dragOverEvent('dragOverAnimationComplete');\n _this._ignoreWhileAnimating = null;\n });\n if (_this !== fromSortable) {\n fromSortable.animateAll();\n fromSortable._ignoreWhileAnimating = null;\n }\n }\n\n // Null lastTarget if it is not inside a previously swapped element\n if (target === dragEl && !dragEl.animated || target === el && !target.animated) {\n lastTarget = null;\n }\n\n // no bubbling and not fallback\n if (!options.dragoverBubble && !evt.rootEl && target !== document) {\n dragEl.parentNode[expando]._isOutsideThisEl(evt.target);\n\n // Do not detect for empty insert if already inserted\n !insertion && nearestEmptyInsertDetectEvent(evt);\n }\n !options.dragoverBubble && evt.stopPropagation && evt.stopPropagation();\n return completedFired = true;\n }\n\n // Call when dragEl has been inserted\n function changed() {\n newIndex = index(dragEl);\n newDraggableIndex = index(dragEl, options.draggable);\n _dispatchEvent({\n sortable: _this,\n name: 'change',\n toEl: el,\n newIndex: newIndex,\n newDraggableIndex: newDraggableIndex,\n originalEvent: evt\n });\n }\n if (evt.preventDefault !== void 0) {\n evt.cancelable && evt.preventDefault();\n }\n target = closest(target, options.draggable, el, true);\n dragOverEvent('dragOver');\n if (Sortable.eventCanceled) return completedFired;\n if (dragEl.contains(evt.target) || target.animated && target.animatingX && target.animatingY || _this._ignoreWhileAnimating === target) {\n return completed(false);\n }\n ignoreNextClick = false;\n if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = parentEl !== rootEl) // Reverting item into the original list\n : putSortable === this || (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt))) {\n vertical = this._getDirection(evt, target) === 'vertical';\n dragRect = getRect(dragEl);\n dragOverEvent('dragOverValid');\n if (Sortable.eventCanceled) return completedFired;\n if (revert) {\n parentEl = rootEl; // actualization\n capture();\n this._hideClone();\n dragOverEvent('revert');\n if (!Sortable.eventCanceled) {\n if (nextEl) {\n rootEl.insertBefore(dragEl, nextEl);\n } else {\n rootEl.appendChild(dragEl);\n }\n }\n return completed(true);\n }\n var elLastChild = lastChild(el, options.draggable);\n if (!elLastChild || _ghostIsLast(evt, vertical, this) && !elLastChild.animated) {\n // Insert to end of list\n\n // If already at end of list: Do not insert\n if (elLastChild === dragEl) {\n return completed(false);\n }\n\n // if there is a last element, it is the target\n if (elLastChild && el === evt.target) {\n target = elLastChild;\n }\n if (target) {\n targetRect = getRect(target);\n }\n if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) {\n capture();\n if (elLastChild && elLastChild.nextSibling) {\n // the last draggable element is not the last node\n el.insertBefore(dragEl, elLastChild.nextSibling);\n } else {\n el.appendChild(dragEl);\n }\n parentEl = el; // actualization\n\n changed();\n return completed(true);\n }\n } else if (elLastChild && _ghostIsFirst(evt, vertical, this)) {\n // Insert to start of list\n var firstChild = getChild(el, 0, options, true);\n if (firstChild === dragEl) {\n return completed(false);\n }\n target = firstChild;\n targetRect = getRect(target);\n if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, false) !== false) {\n capture();\n el.insertBefore(dragEl, firstChild);\n parentEl = el; // actualization\n\n changed();\n return completed(true);\n }\n } else if (target.parentNode === el) {\n targetRect = getRect(target);\n var direction = 0,\n targetBeforeFirstSwap,\n differentLevel = dragEl.parentNode !== el,\n differentRowCol = !_dragElInRowColumn(dragEl.animated && dragEl.toRect || dragRect, target.animated && target.toRect || targetRect, vertical),\n side1 = vertical ? 'top' : 'left',\n scrolledPastTop = isScrolledPast(target, 'top', 'top') || isScrolledPast(dragEl, 'top', 'top'),\n scrollBefore = scrolledPastTop ? scrolledPastTop.scrollTop : void 0;\n if (lastTarget !== target) {\n targetBeforeFirstSwap = targetRect[side1];\n pastFirstInvertThresh = false;\n isCircumstantialInvert = !differentRowCol && options.invertSwap || differentLevel;\n }\n direction = _getSwapDirection(evt, target, targetRect, vertical, differentRowCol ? 1 : options.swapThreshold, options.invertedSwapThreshold == null ? options.swapThreshold : options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target);\n var sibling;\n if (direction !== 0) {\n // Check if target is beside dragEl in respective direction (ignoring hidden elements)\n var dragIndex = index(dragEl);\n do {\n dragIndex -= direction;\n sibling = parentEl.children[dragIndex];\n } while (sibling && (css(sibling, 'display') === 'none' || sibling === ghostEl));\n }\n // If dragEl is already beside target: Do not insert\n if (direction === 0 || sibling === target) {\n return completed(false);\n }\n lastTarget = target;\n lastDirection = direction;\n var nextSibling = target.nextElementSibling,\n after = false;\n after = direction === 1;\n var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after);\n if (moveVector !== false) {\n if (moveVector === 1 || moveVector === -1) {\n after = moveVector === 1;\n }\n _silent = true;\n setTimeout(_unsilent, 30);\n capture();\n if (after && !nextSibling) {\n el.appendChild(dragEl);\n } else {\n target.parentNode.insertBefore(dragEl, after ? nextSibling : target);\n }\n\n // Undo chrome's scroll adjustment (has no effect on other browsers)\n if (scrolledPastTop) {\n scrollBy(scrolledPastTop, 0, scrollBefore - scrolledPastTop.scrollTop);\n }\n parentEl = dragEl.parentNode; // actualization\n\n // must be done before animation\n if (targetBeforeFirstSwap !== undefined && !isCircumstantialInvert) {\n targetMoveDistance = Math.abs(targetBeforeFirstSwap - getRect(target)[side1]);\n }\n changed();\n return completed(true);\n }\n }\n if (el.contains(dragEl)) {\n return completed(false);\n }\n }\n return false;\n },\n _ignoreWhileAnimating: null,\n _offMoveEvents: function _offMoveEvents() {\n off(document, 'mousemove', this._onTouchMove);\n off(document, 'touchmove', this._onTouchMove);\n off(document, 'pointermove', this._onTouchMove);\n off(document, 'dragover', nearestEmptyInsertDetectEvent);\n off(document, 'mousemove', nearestEmptyInsertDetectEvent);\n off(document, 'touchmove', nearestEmptyInsertDetectEvent);\n },\n _offUpEvents: function _offUpEvents() {\n var ownerDocument = this.el.ownerDocument;\n off(ownerDocument, 'mouseup', this._onDrop);\n off(ownerDocument, 'touchend', this._onDrop);\n off(ownerDocument, 'pointerup', this._onDrop);\n off(ownerDocument, 'pointercancel', this._onDrop);\n off(ownerDocument, 'touchcancel', this._onDrop);\n off(document, 'selectstart', this);\n },\n _onDrop: function _onDrop( /**Event*/evt) {\n var el = this.el,\n options = this.options;\n\n // Get the index of the dragged element within its parent\n newIndex = index(dragEl);\n newDraggableIndex = index(dragEl, options.draggable);\n pluginEvent('drop', this, {\n evt: evt\n });\n parentEl = dragEl && dragEl.parentNode;\n\n // Get again after plugin event\n newIndex = index(dragEl);\n newDraggableIndex = index(dragEl, options.draggable);\n if (Sortable.eventCanceled) {\n this._nulling();\n return;\n }\n awaitingDragStarted = false;\n isCircumstantialInvert = false;\n pastFirstInvertThresh = false;\n clearInterval(this._loopId);\n clearTimeout(this._dragStartTimer);\n _cancelNextTick(this.cloneId);\n _cancelNextTick(this._dragStartId);\n\n // Unbind events\n if (this.nativeDraggable) {\n off(document, 'drop', this);\n off(el, 'dragstart', this._onDragStart);\n }\n this._offMoveEvents();\n this._offUpEvents();\n if (Safari) {\n css(document.body, 'user-select', '');\n }\n css(dragEl, 'transform', '');\n if (evt) {\n if (moved) {\n evt.cancelable && evt.preventDefault();\n !options.dropBubble && evt.stopPropagation();\n }\n ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl);\n if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {\n // Remove clone(s)\n cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl);\n }\n if (dragEl) {\n if (this.nativeDraggable) {\n off(dragEl, 'dragend', this);\n }\n _disableDraggable(dragEl);\n dragEl.style['will-change'] = '';\n\n // Remove classes\n // ghostClass is added in dragStarted\n if (moved && !awaitingDragStarted) {\n toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : this.options.ghostClass, false);\n }\n toggleClass(dragEl, this.options.chosenClass, false);\n\n // Drag stop event\n _dispatchEvent({\n sortable: this,\n name: 'unchoose',\n toEl: parentEl,\n newIndex: null,\n newDraggableIndex: null,\n originalEvent: evt\n });\n if (rootEl !== parentEl) {\n if (newIndex >= 0) {\n // Add event\n _dispatchEvent({\n rootEl: parentEl,\n name: 'add',\n toEl: parentEl,\n fromEl: rootEl,\n originalEvent: evt\n });\n\n // Remove event\n _dispatchEvent({\n sortable: this,\n name: 'remove',\n toEl: parentEl,\n originalEvent: evt\n });\n\n // drag from one list and drop into another\n _dispatchEvent({\n rootEl: parentEl,\n name: 'sort',\n toEl: parentEl,\n fromEl: rootEl,\n originalEvent: evt\n });\n _dispatchEvent({\n sortable: this,\n name: 'sort',\n toEl: parentEl,\n originalEvent: evt\n });\n }\n putSortable && putSortable.save();\n } else {\n if (newIndex !== oldIndex) {\n if (newIndex >= 0) {\n // drag & drop within the same list\n _dispatchEvent({\n sortable: this,\n name: 'update',\n toEl: parentEl,\n originalEvent: evt\n });\n _dispatchEvent({\n sortable: this,\n name: 'sort',\n toEl: parentEl,\n originalEvent: evt\n });\n }\n }\n }\n if (Sortable.active) {\n /* jshint eqnull:true */\n if (newIndex == null || newIndex === -1) {\n newIndex = oldIndex;\n newDraggableIndex = oldDraggableIndex;\n }\n _dispatchEvent({\n sortable: this,\n name: 'end',\n toEl: parentEl,\n originalEvent: evt\n });\n\n // Save sorting\n this.save();\n }\n }\n }\n this._nulling();\n },\n _nulling: function _nulling() {\n pluginEvent('nulling', this);\n rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = cloneHidden = tapEvt = touchEvt = moved = newIndex = newDraggableIndex = oldIndex = oldDraggableIndex = lastTarget = lastDirection = putSortable = activeGroup = Sortable.dragged = Sortable.ghost = Sortable.clone = Sortable.active = null;\n var el = this.el;\n savedInputChecked.forEach(function (checkEl) {\n if (el.contains(checkEl)) {\n checkEl.checked = true;\n }\n });\n savedInputChecked.length = lastDx = lastDy = 0;\n },\n handleEvent: function handleEvent( /**Event*/evt) {\n switch (evt.type) {\n case 'drop':\n case 'dragend':\n this._onDrop(evt);\n break;\n case 'dragenter':\n case 'dragover':\n if (dragEl) {\n this._onDragOver(evt);\n _globalDragOver(evt);\n }\n break;\n case 'selectstart':\n evt.preventDefault();\n break;\n }\n },\n /**\r\n * Serializes the item into an array of string.\r\n * @returns {String[]}\r\n */\n toArray: function toArray() {\n var order = [],\n el,\n children = this.el.children,\n i = 0,\n n = children.length,\n options = this.options;\n for (; i < n; i++) {\n el = children[i];\n if (closest(el, options.draggable, this.el, false)) {\n order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));\n }\n }\n return order;\n },\n /**\r\n * Sorts the elements according to the array.\r\n * @param {String[]} order order of the items\r\n */\n sort: function sort(order, useAnimation) {\n var items = {},\n rootEl = this.el;\n this.toArray().forEach(function (id, i) {\n var el = rootEl.children[i];\n if (closest(el, this.options.draggable, rootEl, false)) {\n items[id] = el;\n }\n }, this);\n useAnimation && this.captureAnimationState();\n order.forEach(function (id) {\n if (items[id]) {\n rootEl.removeChild(items[id]);\n rootEl.appendChild(items[id]);\n }\n });\n useAnimation && this.animateAll();\n },\n /**\r\n * Save the current sorting\r\n */\n save: function save() {\n var store = this.options.store;\n store && store.set && store.set(this);\n },\n /**\r\n * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.\r\n * @param {HTMLElement} el\r\n * @param {String} [selector] default: `options.draggable`\r\n * @returns {HTMLElement|null}\r\n */\n closest: function closest$1(el, selector) {\n return closest(el, selector || this.options.draggable, this.el, false);\n },\n /**\r\n * Set/get option\r\n * @param {string} name\r\n * @param {*} [value]\r\n * @returns {*}\r\n */\n option: function option(name, value) {\n var options = this.options;\n if (value === void 0) {\n return options[name];\n } else {\n var modifiedValue = PluginManager.modifyOption(this, name, value);\n if (typeof modifiedValue !== 'undefined') {\n options[name] = modifiedValue;\n } else {\n options[name] = value;\n }\n if (name === 'group') {\n _prepareGroup(options);\n }\n }\n },\n /**\r\n * Destroy\r\n */\n destroy: function destroy() {\n pluginEvent('destroy', this);\n var el = this.el;\n el[expando] = null;\n off(el, 'mousedown', this._onTapStart);\n off(el, 'touchstart', this._onTapStart);\n off(el, 'pointerdown', this._onTapStart);\n if (this.nativeDraggable) {\n off(el, 'dragover', this);\n off(el, 'dragenter', this);\n }\n // Remove draggable attributes\n Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {\n el.removeAttribute('draggable');\n });\n this._onDrop();\n this._disableDelayedDragEvents();\n sortables.splice(sortables.indexOf(this.el), 1);\n this.el = el = null;\n },\n _hideClone: function _hideClone() {\n if (!cloneHidden) {\n pluginEvent('hideClone', this);\n if (Sortable.eventCanceled) return;\n css(cloneEl, 'display', 'none');\n if (this.options.removeCloneOnHide && cloneEl.parentNode) {\n cloneEl.parentNode.removeChild(cloneEl);\n }\n cloneHidden = true;\n }\n },\n _showClone: function _showClone(putSortable) {\n if (putSortable.lastPutMode !== 'clone') {\n this._hideClone();\n return;\n }\n if (cloneHidden) {\n pluginEvent('showClone', this);\n if (Sortable.eventCanceled) return;\n\n // show clone at dragEl or original position\n if (dragEl.parentNode == rootEl && !this.options.group.revertClone) {\n rootEl.insertBefore(cloneEl, dragEl);\n } else if (nextEl) {\n rootEl.insertBefore(cloneEl, nextEl);\n } else {\n rootEl.appendChild(cloneEl);\n }\n if (this.options.group.revertClone) {\n this.animate(dragEl, cloneEl);\n }\n css(cloneEl, 'display', '');\n cloneHidden = false;\n }\n }\n};\nfunction _globalDragOver( /**Event*/evt) {\n if (evt.dataTransfer) {\n evt.dataTransfer.dropEffect = 'move';\n }\n evt.cancelable && evt.preventDefault();\n}\nfunction _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvent, willInsertAfter) {\n var evt,\n sortable = fromEl[expando],\n onMoveFn = sortable.options.onMove,\n retVal;\n // Support for new CustomEvent feature\n if (window.CustomEvent && !IE11OrLess && !Edge) {\n evt = new CustomEvent('move', {\n bubbles: true,\n cancelable: true\n });\n } else {\n evt = document.createEvent('Event');\n evt.initEvent('move', true, true);\n }\n evt.to = toEl;\n evt.from = fromEl;\n evt.dragged = dragEl;\n evt.draggedRect = dragRect;\n evt.related = targetEl || toEl;\n evt.relatedRect = targetRect || getRect(toEl);\n evt.willInsertAfter = willInsertAfter;\n evt.originalEvent = originalEvent;\n fromEl.dispatchEvent(evt);\n if (onMoveFn) {\n retVal = onMoveFn.call(sortable, evt, originalEvent);\n }\n return retVal;\n}\nfunction _disableDraggable(el) {\n el.draggable = false;\n}\nfunction _unsilent() {\n _silent = false;\n}\nfunction _ghostIsFirst(evt, vertical, sortable) {\n var firstElRect = getRect(getChild(sortable.el, 0, sortable.options, true));\n var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl);\n var spacer = 10;\n return vertical ? evt.clientX < childContainingRect.left - spacer || evt.clientY < firstElRect.top && evt.clientX < firstElRect.right : evt.clientY < childContainingRect.top - spacer || evt.clientY < firstElRect.bottom && evt.clientX < firstElRect.left;\n}\nfunction _ghostIsLast(evt, vertical, sortable) {\n var lastElRect = getRect(lastChild(sortable.el, sortable.options.draggable));\n var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl);\n var spacer = 10;\n return vertical ? evt.clientX > childContainingRect.right + spacer || evt.clientY > lastElRect.bottom && evt.clientX > lastElRect.left : evt.clientY > childContainingRect.bottom + spacer || evt.clientX > lastElRect.right && evt.clientY > lastElRect.top;\n}\nfunction _getSwapDirection(evt, target, targetRect, vertical, swapThreshold, invertedSwapThreshold, invertSwap, isLastTarget) {\n var mouseOnAxis = vertical ? evt.clientY : evt.clientX,\n targetLength = vertical ? targetRect.height : targetRect.width,\n targetS1 = vertical ? targetRect.top : targetRect.left,\n targetS2 = vertical ? targetRect.bottom : targetRect.right,\n invert = false;\n if (!invertSwap) {\n // Never invert or create dragEl shadow when target movemenet causes mouse to move past the end of regular swapThreshold\n if (isLastTarget && targetMoveDistance < targetLength * swapThreshold) {\n // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2\n // check if past first invert threshold on side opposite of lastDirection\n if (!pastFirstInvertThresh && (lastDirection === 1 ? mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2 : mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2)) {\n // past first invert threshold, do not restrict inverted threshold to dragEl shadow\n pastFirstInvertThresh = true;\n }\n if (!pastFirstInvertThresh) {\n // dragEl shadow (target move distance shadow)\n if (lastDirection === 1 ? mouseOnAxis < targetS1 + targetMoveDistance // over dragEl shadow\n : mouseOnAxis > targetS2 - targetMoveDistance) {\n return -lastDirection;\n }\n } else {\n invert = true;\n }\n } else {\n // Regular\n if (mouseOnAxis > targetS1 + targetLength * (1 - swapThreshold) / 2 && mouseOnAxis < targetS2 - targetLength * (1 - swapThreshold) / 2) {\n return _getInsertDirection(target);\n }\n }\n }\n invert = invert || invertSwap;\n if (invert) {\n // Invert of regular\n if (mouseOnAxis < targetS1 + targetLength * invertedSwapThreshold / 2 || mouseOnAxis > targetS2 - targetLength * invertedSwapThreshold / 2) {\n return mouseOnAxis > targetS1 + targetLength / 2 ? 1 : -1;\n }\n }\n return 0;\n}\n\n/**\r\n * Gets the direction dragEl must be swapped relative to target in order to make it\r\n * seem that dragEl has been \"inserted\" into that element's position\r\n * @param {HTMLElement} target The target whose position dragEl is being inserted at\r\n * @return {Number} Direction dragEl must be swapped\r\n */\nfunction _getInsertDirection(target) {\n if (index(dragEl) < index(target)) {\n return 1;\n } else {\n return -1;\n }\n}\n\n/**\r\n * Generate id\r\n * @param {HTMLElement} el\r\n * @returns {String}\r\n * @private\r\n */\nfunction _generateId(el) {\n var str = el.tagName + el.className + el.src + el.href + el.textContent,\n i = str.length,\n sum = 0;\n while (i--) {\n sum += str.charCodeAt(i);\n }\n return sum.toString(36);\n}\nfunction _saveInputCheckedState(root) {\n savedInputChecked.length = 0;\n var inputs = root.getElementsByTagName('input');\n var idx = inputs.length;\n while (idx--) {\n var el = inputs[idx];\n el.checked && savedInputChecked.push(el);\n }\n}\nfunction _nextTick(fn) {\n return setTimeout(fn, 0);\n}\nfunction _cancelNextTick(id) {\n return clearTimeout(id);\n}\n\n// Fixed #973:\nif (documentExists) {\n on(document, 'touchmove', function (evt) {\n if ((Sortable.active || awaitingDragStarted) && evt.cancelable) {\n evt.preventDefault();\n }\n });\n}\n\n// Export utils\nSortable.utils = {\n on: on,\n off: off,\n css: css,\n find: find,\n is: function is(el, selector) {\n return !!closest(el, selector, el, false);\n },\n extend: extend,\n throttle: throttle,\n closest: closest,\n toggleClass: toggleClass,\n clone: clone,\n index: index,\n nextTick: _nextTick,\n cancelNextTick: _cancelNextTick,\n detectDirection: _detectDirection,\n getChild: getChild,\n expando: expando\n};\n\n/**\r\n * Get the Sortable instance of an element\r\n * @param {HTMLElement} element The element\r\n * @return {Sortable|undefined} The instance of Sortable\r\n */\nSortable.get = function (element) {\n return element[expando];\n};\n\n/**\r\n * Mount a plugin to Sortable\r\n * @param {...SortablePlugin|SortablePlugin[]} plugins Plugins being mounted\r\n */\nSortable.mount = function () {\n for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) {\n plugins[_key] = arguments[_key];\n }\n if (plugins[0].constructor === Array) plugins = plugins[0];\n plugins.forEach(function (plugin) {\n if (!plugin.prototype || !plugin.prototype.constructor) {\n throw \"Sortable: Mounted plugin must be a constructor function, not \".concat({}.toString.call(plugin));\n }\n if (plugin.utils) Sortable.utils = _objectSpread2(_objectSpread2({}, Sortable.utils), plugin.utils);\n PluginManager.mount(plugin);\n });\n};\n\n/**\r\n * Create sortable instance\r\n * @param {HTMLElement} el\r\n * @param {Object} [options]\r\n */\nSortable.create = function (el, options) {\n return new Sortable(el, options);\n};\n\n// Export\nSortable.version = version;\n\nvar autoScrolls = [],\n scrollEl,\n scrollRootEl,\n scrolling = false,\n lastAutoScrollX,\n lastAutoScrollY,\n touchEvt$1,\n pointerElemChangedInterval;\nfunction AutoScrollPlugin() {\n function AutoScroll() {\n this.defaults = {\n scroll: true,\n forceAutoScrollFallback: false,\n scrollSensitivity: 30,\n scrollSpeed: 10,\n bubbleScroll: true\n };\n\n // Bind all private methods\n for (var fn in this) {\n if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {\n this[fn] = this[fn].bind(this);\n }\n }\n }\n AutoScroll.prototype = {\n dragStarted: function dragStarted(_ref) {\n var originalEvent = _ref.originalEvent;\n if (this.sortable.nativeDraggable) {\n on(document, 'dragover', this._handleAutoScroll);\n } else {\n if (this.options.supportPointer) {\n on(document, 'pointermove', this._handleFallbackAutoScroll);\n } else if (originalEvent.touches) {\n on(document, 'touchmove', this._handleFallbackAutoScroll);\n } else {\n on(document, 'mousemove', this._handleFallbackAutoScroll);\n }\n }\n },\n dragOverCompleted: function dragOverCompleted(_ref2) {\n var originalEvent = _ref2.originalEvent;\n // For when bubbling is canceled and using fallback (fallback 'touchmove' always reached)\n if (!this.options.dragOverBubble && !originalEvent.rootEl) {\n this._handleAutoScroll(originalEvent);\n }\n },\n drop: function drop() {\n if (this.sortable.nativeDraggable) {\n off(document, 'dragover', this._handleAutoScroll);\n } else {\n off(document, 'pointermove', this._handleFallbackAutoScroll);\n off(document, 'touchmove', this._handleFallbackAutoScroll);\n off(document, 'mousemove', this._handleFallbackAutoScroll);\n }\n clearPointerElemChangedInterval();\n clearAutoScrolls();\n cancelThrottle();\n },\n nulling: function nulling() {\n touchEvt$1 = scrollRootEl = scrollEl = scrolling = pointerElemChangedInterval = lastAutoScrollX = lastAutoScrollY = null;\n autoScrolls.length = 0;\n },\n _handleFallbackAutoScroll: function _handleFallbackAutoScroll(evt) {\n this._handleAutoScroll(evt, true);\n },\n _handleAutoScroll: function _handleAutoScroll(evt, fallback) {\n var _this = this;\n var x = (evt.touches ? evt.touches[0] : evt).clientX,\n y = (evt.touches ? evt.touches[0] : evt).clientY,\n elem = document.elementFromPoint(x, y);\n touchEvt$1 = evt;\n\n // IE does not seem to have native autoscroll,\n // Edge's autoscroll seems too conditional,\n // MACOS Safari does not have autoscroll,\n // Firefox and Chrome are good\n if (fallback || this.options.forceAutoScrollFallback || Edge || IE11OrLess || Safari) {\n autoScroll(evt, this.options, elem, fallback);\n\n // Listener for pointer element change\n var ogElemScroller = getParentAutoScrollElement(elem, true);\n if (scrolling && (!pointerElemChangedInterval || x !== lastAutoScrollX || y !== lastAutoScrollY)) {\n pointerElemChangedInterval && clearPointerElemChangedInterval();\n // Detect for pointer elem change, emulating native DnD behaviour\n pointerElemChangedInterval = setInterval(function () {\n var newElem = getParentAutoScrollElement(document.elementFromPoint(x, y), true);\n if (newElem !== ogElemScroller) {\n ogElemScroller = newElem;\n clearAutoScrolls();\n }\n autoScroll(evt, _this.options, newElem, fallback);\n }, 10);\n lastAutoScrollX = x;\n lastAutoScrollY = y;\n }\n } else {\n // if DnD is enabled (and browser has good autoscrolling), first autoscroll will already scroll, so get parent autoscroll of first autoscroll\n if (!this.options.bubbleScroll || getParentAutoScrollElement(elem, true) === getWindowScrollingElement()) {\n clearAutoScrolls();\n return;\n }\n autoScroll(evt, this.options, getParentAutoScrollElement(elem, false), false);\n }\n }\n };\n return _extends(AutoScroll, {\n pluginName: 'scroll',\n initializeByDefault: true\n });\n}\nfunction clearAutoScrolls() {\n autoScrolls.forEach(function (autoScroll) {\n clearInterval(autoScroll.pid);\n });\n autoScrolls = [];\n}\nfunction clearPointerElemChangedInterval() {\n clearInterval(pointerElemChangedInterval);\n}\nvar autoScroll = throttle(function (evt, options, rootEl, isFallback) {\n // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521\n if (!options.scroll) return;\n var x = (evt.touches ? evt.touches[0] : evt).clientX,\n y = (evt.touches ? evt.touches[0] : evt).clientY,\n sens = options.scrollSensitivity,\n speed = options.scrollSpeed,\n winScroller = getWindowScrollingElement();\n var scrollThisInstance = false,\n scrollCustomFn;\n\n // New scroll root, set scrollEl\n if (scrollRootEl !== rootEl) {\n scrollRootEl = rootEl;\n clearAutoScrolls();\n scrollEl = options.scroll;\n scrollCustomFn = options.scrollFn;\n if (scrollEl === true) {\n scrollEl = getParentAutoScrollElement(rootEl, true);\n }\n }\n var layersOut = 0;\n var currentParent = scrollEl;\n do {\n var el = currentParent,\n rect = getRect(el),\n top = rect.top,\n bottom = rect.bottom,\n left = rect.left,\n right = rect.right,\n width = rect.width,\n height = rect.height,\n canScrollX = void 0,\n canScrollY = void 0,\n scrollWidth = el.scrollWidth,\n scrollHeight = el.scrollHeight,\n elCSS = css(el),\n scrollPosX = el.scrollLeft,\n scrollPosY = el.scrollTop;\n if (el === winScroller) {\n canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll' || elCSS.overflowX === 'visible');\n canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll' || elCSS.overflowY === 'visible');\n } else {\n canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll');\n canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll');\n }\n var vx = canScrollX && (Math.abs(right - x) <= sens && scrollPosX + width < scrollWidth) - (Math.abs(left - x) <= sens && !!scrollPosX);\n var vy = canScrollY && (Math.abs(bottom - y) <= sens && scrollPosY + height < scrollHeight) - (Math.abs(top - y) <= sens && !!scrollPosY);\n if (!autoScrolls[layersOut]) {\n for (var i = 0; i <= layersOut; i++) {\n if (!autoScrolls[i]) {\n autoScrolls[i] = {};\n }\n }\n }\n if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) {\n autoScrolls[layersOut].el = el;\n autoScrolls[layersOut].vx = vx;\n autoScrolls[layersOut].vy = vy;\n clearInterval(autoScrolls[layersOut].pid);\n if (vx != 0 || vy != 0) {\n scrollThisInstance = true;\n /* jshint loopfunc:true */\n autoScrolls[layersOut].pid = setInterval(function () {\n // emulate drag over during autoscroll (fallback), emulating native DnD behaviour\n if (isFallback && this.layer === 0) {\n Sortable.active._onTouchMove(touchEvt$1); // To move ghost if it is positioned absolutely\n }\n var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0;\n var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0;\n if (typeof scrollCustomFn === 'function') {\n if (scrollCustomFn.call(Sortable.dragged.parentNode[expando], scrollOffsetX, scrollOffsetY, evt, touchEvt$1, autoScrolls[this.layer].el) !== 'continue') {\n return;\n }\n }\n scrollBy(autoScrolls[this.layer].el, scrollOffsetX, scrollOffsetY);\n }.bind({\n layer: layersOut\n }), 24);\n }\n }\n layersOut++;\n } while (options.bubbleScroll && currentParent !== winScroller && (currentParent = getParentAutoScrollElement(currentParent, false)));\n scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not\n}, 30);\n\nvar drop = function drop(_ref) {\n var originalEvent = _ref.originalEvent,\n putSortable = _ref.putSortable,\n dragEl = _ref.dragEl,\n activeSortable = _ref.activeSortable,\n dispatchSortableEvent = _ref.dispatchSortableEvent,\n hideGhostForTarget = _ref.hideGhostForTarget,\n unhideGhostForTarget = _ref.unhideGhostForTarget;\n if (!originalEvent) return;\n var toSortable = putSortable || activeSortable;\n hideGhostForTarget();\n var touch = originalEvent.changedTouches && originalEvent.changedTouches.length ? originalEvent.changedTouches[0] : originalEvent;\n var target = document.elementFromPoint(touch.clientX, touch.clientY);\n unhideGhostForTarget();\n if (toSortable && !toSortable.el.contains(target)) {\n dispatchSortableEvent('spill');\n this.onSpill({\n dragEl: dragEl,\n putSortable: putSortable\n });\n }\n};\nfunction Revert() {}\nRevert.prototype = {\n startIndex: null,\n dragStart: function dragStart(_ref2) {\n var oldDraggableIndex = _ref2.oldDraggableIndex;\n this.startIndex = oldDraggableIndex;\n },\n onSpill: function onSpill(_ref3) {\n var dragEl = _ref3.dragEl,\n putSortable = _ref3.putSortable;\n this.sortable.captureAnimationState();\n if (putSortable) {\n putSortable.captureAnimationState();\n }\n var nextSibling = getChild(this.sortable.el, this.startIndex, this.options);\n if (nextSibling) {\n this.sortable.el.insertBefore(dragEl, nextSibling);\n } else {\n this.sortable.el.appendChild(dragEl);\n }\n this.sortable.animateAll();\n if (putSortable) {\n putSortable.animateAll();\n }\n },\n drop: drop\n};\n_extends(Revert, {\n pluginName: 'revertOnSpill'\n});\nfunction Remove() {}\nRemove.prototype = {\n onSpill: function onSpill(_ref4) {\n var dragEl = _ref4.dragEl,\n putSortable = _ref4.putSortable;\n var parentSortable = putSortable || this.sortable;\n parentSortable.captureAnimationState();\n dragEl.parentNode && dragEl.parentNode.removeChild(dragEl);\n parentSortable.animateAll();\n },\n drop: drop\n};\n_extends(Remove, {\n pluginName: 'removeOnSpill'\n});\n\nvar lastSwapEl;\nfunction SwapPlugin() {\n function Swap() {\n this.defaults = {\n swapClass: 'sortable-swap-highlight'\n };\n }\n Swap.prototype = {\n dragStart: function dragStart(_ref) {\n var dragEl = _ref.dragEl;\n lastSwapEl = dragEl;\n },\n dragOverValid: function dragOverValid(_ref2) {\n var completed = _ref2.completed,\n target = _ref2.target,\n onMove = _ref2.onMove,\n activeSortable = _ref2.activeSortable,\n changed = _ref2.changed,\n cancel = _ref2.cancel;\n if (!activeSortable.options.swap) return;\n var el = this.sortable.el,\n options = this.options;\n if (target && target !== el) {\n var prevSwapEl = lastSwapEl;\n if (onMove(target) !== false) {\n toggleClass(target, options.swapClass, true);\n lastSwapEl = target;\n } else {\n lastSwapEl = null;\n }\n if (prevSwapEl && prevSwapEl !== lastSwapEl) {\n toggleClass(prevSwapEl, options.swapClass, false);\n }\n }\n changed();\n completed(true);\n cancel();\n },\n drop: function drop(_ref3) {\n var activeSortable = _ref3.activeSortable,\n putSortable = _ref3.putSortable,\n dragEl = _ref3.dragEl;\n var toSortable = putSortable || this.sortable;\n var options = this.options;\n lastSwapEl && toggleClass(lastSwapEl, options.swapClass, false);\n if (lastSwapEl && (options.swap || putSortable && putSortable.options.swap)) {\n if (dragEl !== lastSwapEl) {\n toSortable.captureAnimationState();\n if (toSortable !== activeSortable) activeSortable.captureAnimationState();\n swapNodes(dragEl, lastSwapEl);\n toSortable.animateAll();\n if (toSortable !== activeSortable) activeSortable.animateAll();\n }\n }\n },\n nulling: function nulling() {\n lastSwapEl = null;\n }\n };\n return _extends(Swap, {\n pluginName: 'swap',\n eventProperties: function eventProperties() {\n return {\n swapItem: lastSwapEl\n };\n }\n });\n}\nfunction swapNodes(n1, n2) {\n var p1 = n1.parentNode,\n p2 = n2.parentNode,\n i1,\n i2;\n if (!p1 || !p2 || p1.isEqualNode(n2) || p2.isEqualNode(n1)) return;\n i1 = index(n1);\n i2 = index(n2);\n if (p1.isEqualNode(p2) && i1 < i2) {\n i2++;\n }\n p1.insertBefore(n2, p1.children[i1]);\n p2.insertBefore(n1, p2.children[i2]);\n}\n\nvar multiDragElements = [],\n multiDragClones = [],\n lastMultiDragSelect,\n // for selection with modifier key down (SHIFT)\n multiDragSortable,\n initialFolding = false,\n // Initial multi-drag fold when drag started\n folding = false,\n // Folding any other time\n dragStarted = false,\n dragEl$1,\n clonesFromRect,\n clonesHidden;\nfunction MultiDragPlugin() {\n function MultiDrag(sortable) {\n // Bind all private methods\n for (var fn in this) {\n if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {\n this[fn] = this[fn].bind(this);\n }\n }\n if (!sortable.options.avoidImplicitDeselect) {\n if (sortable.options.supportPointer) {\n on(document, 'pointerup', this._deselectMultiDrag);\n } else {\n on(document, 'mouseup', this._deselectMultiDrag);\n on(document, 'touchend', this._deselectMultiDrag);\n }\n }\n on(document, 'keydown', this._checkKeyDown);\n on(document, 'keyup', this._checkKeyUp);\n this.defaults = {\n selectedClass: 'sortable-selected',\n multiDragKey: null,\n avoidImplicitDeselect: false,\n setData: function setData(dataTransfer, dragEl) {\n var data = '';\n if (multiDragElements.length && multiDragSortable === sortable) {\n multiDragElements.forEach(function (multiDragElement, i) {\n data += (!i ? '' : ', ') + multiDragElement.textContent;\n });\n } else {\n data = dragEl.textContent;\n }\n dataTransfer.setData('Text', data);\n }\n };\n }\n MultiDrag.prototype = {\n multiDragKeyDown: false,\n isMultiDrag: false,\n delayStartGlobal: function delayStartGlobal(_ref) {\n var dragged = _ref.dragEl;\n dragEl$1 = dragged;\n },\n delayEnded: function delayEnded() {\n this.isMultiDrag = ~multiDragElements.indexOf(dragEl$1);\n },\n setupClone: function setupClone(_ref2) {\n var sortable = _ref2.sortable,\n cancel = _ref2.cancel;\n if (!this.isMultiDrag) return;\n for (var i = 0; i < multiDragElements.length; i++) {\n multiDragClones.push(clone(multiDragElements[i]));\n multiDragClones[i].sortableIndex = multiDragElements[i].sortableIndex;\n multiDragClones[i].draggable = false;\n multiDragClones[i].style['will-change'] = '';\n toggleClass(multiDragClones[i], this.options.selectedClass, false);\n multiDragElements[i] === dragEl$1 && toggleClass(multiDragClones[i], this.options.chosenClass, false);\n }\n sortable._hideClone();\n cancel();\n },\n clone: function clone(_ref3) {\n var sortable = _ref3.sortable,\n rootEl = _ref3.rootEl,\n dispatchSortableEvent = _ref3.dispatchSortableEvent,\n cancel = _ref3.cancel;\n if (!this.isMultiDrag) return;\n if (!this.options.removeCloneOnHide) {\n if (multiDragElements.length && multiDragSortable === sortable) {\n insertMultiDragClones(true, rootEl);\n dispatchSortableEvent('clone');\n cancel();\n }\n }\n },\n showClone: function showClone(_ref4) {\n var cloneNowShown = _ref4.cloneNowShown,\n rootEl = _ref4.rootEl,\n cancel = _ref4.cancel;\n if (!this.isMultiDrag) return;\n insertMultiDragClones(false, rootEl);\n multiDragClones.forEach(function (clone) {\n css(clone, 'display', '');\n });\n cloneNowShown();\n clonesHidden = false;\n cancel();\n },\n hideClone: function hideClone(_ref5) {\n var _this = this;\n var sortable = _ref5.sortable,\n cloneNowHidden = _ref5.cloneNowHidden,\n cancel = _ref5.cancel;\n if (!this.isMultiDrag) return;\n multiDragClones.forEach(function (clone) {\n css(clone, 'display', 'none');\n if (_this.options.removeCloneOnHide && clone.parentNode) {\n clone.parentNode.removeChild(clone);\n }\n });\n cloneNowHidden();\n clonesHidden = true;\n cancel();\n },\n dragStartGlobal: function dragStartGlobal(_ref6) {\n var sortable = _ref6.sortable;\n if (!this.isMultiDrag && multiDragSortable) {\n multiDragSortable.multiDrag._deselectMultiDrag();\n }\n multiDragElements.forEach(function (multiDragElement) {\n multiDragElement.sortableIndex = index(multiDragElement);\n });\n\n // Sort multi-drag elements\n multiDragElements = multiDragElements.sort(function (a, b) {\n return a.sortableIndex - b.sortableIndex;\n });\n dragStarted = true;\n },\n dragStarted: function dragStarted(_ref7) {\n var _this2 = this;\n var sortable = _ref7.sortable;\n if (!this.isMultiDrag) return;\n if (this.options.sort) {\n // Capture rects,\n // hide multi drag elements (by positioning them absolute),\n // set multi drag elements rects to dragRect,\n // show multi drag elements,\n // animate to rects,\n // unset rects & remove from DOM\n\n sortable.captureAnimationState();\n if (this.options.animation) {\n multiDragElements.forEach(function (multiDragElement) {\n if (multiDragElement === dragEl$1) return;\n css(multiDragElement, 'position', 'absolute');\n });\n var dragRect = getRect(dragEl$1, false, true, true);\n multiDragElements.forEach(function (multiDragElement) {\n if (multiDragElement === dragEl$1) return;\n setRect(multiDragElement, dragRect);\n });\n folding = true;\n initialFolding = true;\n }\n }\n sortable.animateAll(function () {\n folding = false;\n initialFolding = false;\n if (_this2.options.animation) {\n multiDragElements.forEach(function (multiDragElement) {\n unsetRect(multiDragElement);\n });\n }\n\n // Remove all auxiliary multidrag items from el, if sorting enabled\n if (_this2.options.sort) {\n removeMultiDragElements();\n }\n });\n },\n dragOver: function dragOver(_ref8) {\n var target = _ref8.target,\n completed = _ref8.completed,\n cancel = _ref8.cancel;\n if (folding && ~multiDragElements.indexOf(target)) {\n completed(false);\n cancel();\n }\n },\n revert: function revert(_ref9) {\n var fromSortable = _ref9.fromSortable,\n rootEl = _ref9.rootEl,\n sortable = _ref9.sortable,\n dragRect = _ref9.dragRect;\n if (multiDragElements.length > 1) {\n // Setup unfold animation\n multiDragElements.forEach(function (multiDragElement) {\n sortable.addAnimationState({\n target: multiDragElement,\n rect: folding ? getRect(multiDragElement) : dragRect\n });\n unsetRect(multiDragElement);\n multiDragElement.fromRect = dragRect;\n fromSortable.removeAnimationState(multiDragElement);\n });\n folding = false;\n insertMultiDragElements(!this.options.removeCloneOnHide, rootEl);\n }\n },\n dragOverCompleted: function dragOverCompleted(_ref10) {\n var sortable = _ref10.sortable,\n isOwner = _ref10.isOwner,\n insertion = _ref10.insertion,\n activeSortable = _ref10.activeSortable,\n parentEl = _ref10.parentEl,\n putSortable = _ref10.putSortable;\n var options = this.options;\n if (insertion) {\n // Clones must be hidden before folding animation to capture dragRectAbsolute properly\n if (isOwner) {\n activeSortable._hideClone();\n }\n initialFolding = false;\n // If leaving sort:false root, or already folding - Fold to new location\n if (options.animation && multiDragElements.length > 1 && (folding || !isOwner && !activeSortable.options.sort && !putSortable)) {\n // Fold: Set all multi drag elements's rects to dragEl's rect when multi-drag elements are invisible\n var dragRectAbsolute = getRect(dragEl$1, false, true, true);\n multiDragElements.forEach(function (multiDragElement) {\n if (multiDragElement === dragEl$1) return;\n setRect(multiDragElement, dragRectAbsolute);\n\n // Move element(s) to end of parentEl so that it does not interfere with multi-drag clones insertion if they are inserted\n // while folding, and so that we can capture them again because old sortable will no longer be fromSortable\n parentEl.appendChild(multiDragElement);\n });\n folding = true;\n }\n\n // Clones must be shown (and check to remove multi drags) after folding when interfering multiDragElements are moved out\n if (!isOwner) {\n // Only remove if not folding (folding will remove them anyways)\n if (!folding) {\n removeMultiDragElements();\n }\n if (multiDragElements.length > 1) {\n var clonesHiddenBefore = clonesHidden;\n activeSortable._showClone(sortable);\n\n // Unfold animation for clones if showing from hidden\n if (activeSortable.options.animation && !clonesHidden && clonesHiddenBefore) {\n multiDragClones.forEach(function (clone) {\n activeSortable.addAnimationState({\n target: clone,\n rect: clonesFromRect\n });\n clone.fromRect = clonesFromRect;\n clone.thisAnimationDuration = null;\n });\n }\n } else {\n activeSortable._showClone(sortable);\n }\n }\n }\n },\n dragOverAnimationCapture: function dragOverAnimationCapture(_ref11) {\n var dragRect = _ref11.dragRect,\n isOwner = _ref11.isOwner,\n activeSortable = _ref11.activeSortable;\n multiDragElements.forEach(function (multiDragElement) {\n multiDragElement.thisAnimationDuration = null;\n });\n if (activeSortable.options.animation && !isOwner && activeSortable.multiDrag.isMultiDrag) {\n clonesFromRect = _extends({}, dragRect);\n var dragMatrix = matrix(dragEl$1, true);\n clonesFromRect.top -= dragMatrix.f;\n clonesFromRect.left -= dragMatrix.e;\n }\n },\n dragOverAnimationComplete: function dragOverAnimationComplete() {\n if (folding) {\n folding = false;\n removeMultiDragElements();\n }\n },\n drop: function drop(_ref12) {\n var evt = _ref12.originalEvent,\n rootEl = _ref12.rootEl,\n parentEl = _ref12.parentEl,\n sortable = _ref12.sortable,\n dispatchSortableEvent = _ref12.dispatchSortableEvent,\n oldIndex = _ref12.oldIndex,\n putSortable = _ref12.putSortable;\n var toSortable = putSortable || this.sortable;\n if (!evt) return;\n var options = this.options,\n children = parentEl.children;\n\n // Multi-drag selection\n if (!dragStarted) {\n if (options.multiDragKey && !this.multiDragKeyDown) {\n this._deselectMultiDrag();\n }\n toggleClass(dragEl$1, options.selectedClass, !~multiDragElements.indexOf(dragEl$1));\n if (!~multiDragElements.indexOf(dragEl$1)) {\n multiDragElements.push(dragEl$1);\n dispatchEvent({\n sortable: sortable,\n rootEl: rootEl,\n name: 'select',\n targetEl: dragEl$1,\n originalEvent: evt\n });\n\n // Modifier activated, select from last to dragEl\n if (evt.shiftKey && lastMultiDragSelect && sortable.el.contains(lastMultiDragSelect)) {\n var lastIndex = index(lastMultiDragSelect),\n currentIndex = index(dragEl$1);\n if (~lastIndex && ~currentIndex && lastIndex !== currentIndex) {\n (function () {\n // Must include lastMultiDragSelect (select it), in case modified selection from no selection\n // (but previous selection existed)\n var n, i;\n if (currentIndex > lastIndex) {\n i = lastIndex;\n n = currentIndex;\n } else {\n i = currentIndex;\n n = lastIndex + 1;\n }\n var filter = options.filter;\n for (; i < n; i++) {\n if (~multiDragElements.indexOf(children[i])) continue;\n // Check if element is draggable\n if (!closest(children[i], options.draggable, parentEl, false)) continue;\n // Check if element is filtered\n var filtered = filter && (typeof filter === 'function' ? filter.call(sortable, evt, children[i], sortable) : filter.split(',').some(function (criteria) {\n return closest(children[i], criteria.trim(), parentEl, false);\n }));\n if (filtered) continue;\n toggleClass(children[i], options.selectedClass, true);\n multiDragElements.push(children[i]);\n dispatchEvent({\n sortable: sortable,\n rootEl: rootEl,\n name: 'select',\n targetEl: children[i],\n originalEvent: evt\n });\n }\n })();\n }\n } else {\n lastMultiDragSelect = dragEl$1;\n }\n multiDragSortable = toSortable;\n } else {\n multiDragElements.splice(multiDragElements.indexOf(dragEl$1), 1);\n lastMultiDragSelect = null;\n dispatchEvent({\n sortable: sortable,\n rootEl: rootEl,\n name: 'deselect',\n targetEl: dragEl$1,\n originalEvent: evt\n });\n }\n }\n\n // Multi-drag drop\n if (dragStarted && this.isMultiDrag) {\n folding = false;\n // Do not \"unfold\" after around dragEl if reverted\n if ((parentEl[expando].options.sort || parentEl !== rootEl) && multiDragElements.length > 1) {\n var dragRect = getRect(dragEl$1),\n multiDragIndex = index(dragEl$1, ':not(.' + this.options.selectedClass + ')');\n if (!initialFolding && options.animation) dragEl$1.thisAnimationDuration = null;\n toSortable.captureAnimationState();\n if (!initialFolding) {\n if (options.animation) {\n dragEl$1.fromRect = dragRect;\n multiDragElements.forEach(function (multiDragElement) {\n multiDragElement.thisAnimationDuration = null;\n if (multiDragElement !== dragEl$1) {\n var rect = folding ? getRect(multiDragElement) : dragRect;\n multiDragElement.fromRect = rect;\n\n // Prepare unfold animation\n toSortable.addAnimationState({\n target: multiDragElement,\n rect: rect\n });\n }\n });\n }\n\n // Multi drag elements are not necessarily removed from the DOM on drop, so to reinsert\n // properly they must all be removed\n removeMultiDragElements();\n multiDragElements.forEach(function (multiDragElement) {\n if (children[multiDragIndex]) {\n parentEl.insertBefore(multiDragElement, children[multiDragIndex]);\n } else {\n parentEl.appendChild(multiDragElement);\n }\n multiDragIndex++;\n });\n\n // If initial folding is done, the elements may have changed position because they are now\n // unfolding around dragEl, even though dragEl may not have his index changed, so update event\n // must be fired here as Sortable will not.\n if (oldIndex === index(dragEl$1)) {\n var update = false;\n multiDragElements.forEach(function (multiDragElement) {\n if (multiDragElement.sortableIndex !== index(multiDragElement)) {\n update = true;\n return;\n }\n });\n if (update) {\n dispatchSortableEvent('update');\n dispatchSortableEvent('sort');\n }\n }\n }\n\n // Must be done after capturing individual rects (scroll bar)\n multiDragElements.forEach(function (multiDragElement) {\n unsetRect(multiDragElement);\n });\n toSortable.animateAll();\n }\n multiDragSortable = toSortable;\n }\n\n // Remove clones if necessary\n if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {\n multiDragClones.forEach(function (clone) {\n clone.parentNode && clone.parentNode.removeChild(clone);\n });\n }\n },\n nullingGlobal: function nullingGlobal() {\n this.isMultiDrag = dragStarted = false;\n multiDragClones.length = 0;\n },\n destroyGlobal: function destroyGlobal() {\n this._deselectMultiDrag();\n off(document, 'pointerup', this._deselectMultiDrag);\n off(document, 'mouseup', this._deselectMultiDrag);\n off(document, 'touchend', this._deselectMultiDrag);\n off(document, 'keydown', this._checkKeyDown);\n off(document, 'keyup', this._checkKeyUp);\n },\n _deselectMultiDrag: function _deselectMultiDrag(evt) {\n if (typeof dragStarted !== \"undefined\" && dragStarted) return;\n\n // Only deselect if selection is in this sortable\n if (multiDragSortable !== this.sortable) return;\n\n // Only deselect if target is not item in this sortable\n if (evt && closest(evt.target, this.options.draggable, this.sortable.el, false)) return;\n\n // Only deselect if left click\n if (evt && evt.button !== 0) return;\n while (multiDragElements.length) {\n var el = multiDragElements[0];\n toggleClass(el, this.options.selectedClass, false);\n multiDragElements.shift();\n dispatchEvent({\n sortable: this.sortable,\n rootEl: this.sortable.el,\n name: 'deselect',\n targetEl: el,\n originalEvent: evt\n });\n }\n },\n _checkKeyDown: function _checkKeyDown(evt) {\n if (evt.key === this.options.multiDragKey) {\n this.multiDragKeyDown = true;\n }\n },\n _checkKeyUp: function _checkKeyUp(evt) {\n if (evt.key === this.options.multiDragKey) {\n this.multiDragKeyDown = false;\n }\n }\n };\n return _extends(MultiDrag, {\n // Static methods & properties\n pluginName: 'multiDrag',\n utils: {\n /**\r\n * Selects the provided multi-drag item\r\n * @param {HTMLElement} el The element to be selected\r\n */\n select: function select(el) {\n var sortable = el.parentNode[expando];\n if (!sortable || !sortable.options.multiDrag || ~multiDragElements.indexOf(el)) return;\n if (multiDragSortable && multiDragSortable !== sortable) {\n multiDragSortable.multiDrag._deselectMultiDrag();\n multiDragSortable = sortable;\n }\n toggleClass(el, sortable.options.selectedClass, true);\n multiDragElements.push(el);\n },\n /**\r\n * Deselects the provided multi-drag item\r\n * @param {HTMLElement} el The element to be deselected\r\n */\n deselect: function deselect(el) {\n var sortable = el.parentNode[expando],\n index = multiDragElements.indexOf(el);\n if (!sortable || !sortable.options.multiDrag || !~index) return;\n toggleClass(el, sortable.options.selectedClass, false);\n multiDragElements.splice(index, 1);\n }\n },\n eventProperties: function eventProperties() {\n var _this3 = this;\n var oldIndicies = [],\n newIndicies = [];\n multiDragElements.forEach(function (multiDragElement) {\n oldIndicies.push({\n multiDragElement: multiDragElement,\n index: multiDragElement.sortableIndex\n });\n\n // multiDragElements will already be sorted if folding\n var newIndex;\n if (folding && multiDragElement !== dragEl$1) {\n newIndex = -1;\n } else if (folding) {\n newIndex = index(multiDragElement, ':not(.' + _this3.options.selectedClass + ')');\n } else {\n newIndex = index(multiDragElement);\n }\n newIndicies.push({\n multiDragElement: multiDragElement,\n index: newIndex\n });\n });\n return {\n items: _toConsumableArray(multiDragElements),\n clones: [].concat(multiDragClones),\n oldIndicies: oldIndicies,\n newIndicies: newIndicies\n };\n },\n optionListeners: {\n multiDragKey: function multiDragKey(key) {\n key = key.toLowerCase();\n if (key === 'ctrl') {\n key = 'Control';\n } else if (key.length > 1) {\n key = key.charAt(0).toUpperCase() + key.substr(1);\n }\n return key;\n }\n }\n });\n}\nfunction insertMultiDragElements(clonesInserted, rootEl) {\n multiDragElements.forEach(function (multiDragElement, i) {\n var target = rootEl.children[multiDragElement.sortableIndex + (clonesInserted ? Number(i) : 0)];\n if (target) {\n rootEl.insertBefore(multiDragElement, target);\n } else {\n rootEl.appendChild(multiDragElement);\n }\n });\n}\n\n/**\r\n * Insert multi-drag clones\r\n * @param {[Boolean]} elementsInserted Whether the multi-drag elements are inserted\r\n * @param {HTMLElement} rootEl\r\n */\nfunction insertMultiDragClones(elementsInserted, rootEl) {\n multiDragClones.forEach(function (clone, i) {\n var target = rootEl.children[clone.sortableIndex + (elementsInserted ? Number(i) : 0)];\n if (target) {\n rootEl.insertBefore(clone, target);\n } else {\n rootEl.appendChild(clone);\n }\n });\n}\nfunction removeMultiDragElements() {\n multiDragElements.forEach(function (multiDragElement) {\n if (multiDragElement === dragEl$1) return;\n multiDragElement.parentNode && multiDragElement.parentNode.removeChild(multiDragElement);\n });\n}\n\nSortable.mount(new AutoScrollPlugin());\nSortable.mount(Remove, Revert);\n\nexport default Sortable;\nexport { MultiDragPlugin as MultiDrag, Sortable, SwapPlugin as Swap };\n", "import { Controller } from \"@hotwired/stimulus\";\nimport Sortable from \"sortablejs\";\n\nexport default class extends Controller {\n static targets = [\"list\"];\n static values = { url: String };\n\n connect() {\n if (!this.hasListTarget) return;\n\n this.sortable = new Sortable(this.listTarget, {\n animation: 150,\n ghostClass: \"opacity-30\",\n handle: \"[data-sortable-handle]\",\n onEnd: this.onSortEnd.bind(this),\n });\n }\n\n disconnect() {\n this.sortable?.destroy();\n }\n\n onSortEnd() {\n const order = Array.from(this.listTarget.children)\n .map(el => el.getAttribute(\"data-imm--media--item-id-value\"))\n .filter(Boolean);\n\n if (order.length === 0 || !this.urlValue) return;\n\n fetch(this.urlValue, {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CSRF-Token\": this.csrfToken,\n },\n body: JSON.stringify({ order }),\n });\n }\n\n get csrfToken() {\n return document.querySelector(\"[name='csrf-token']\")?.content;\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport { DirectUpload } from \"@rails/activestorage\";\nimport * as Turbo from \"@hotwired/turbo\";\n\n// Browser-quirk fallback only: some containers (e.g. .mkv on Chrome/Linux)\n// report an empty MIME type, so we also accept by extension. The backend\n// re-validates content type authoritatively.\nconst ALLOWED_EXTENSIONS = [\n \"jpg\",\n \"jpeg\",\n \"png\",\n \"gif\",\n \"webp\",\n \"heic\",\n \"heif\",\n \"mp4\",\n \"mov\",\n \"qt\",\n \"webm\",\n \"mkv\",\n \"avi\",\n];\n\nexport default class extends Controller {\n static targets = [\n \"input\",\n \"cameraInput\",\n \"videoCameraInput\",\n \"dropzone\",\n \"progress\",\n ];\n\n static values = {\n url: String,\n allowedTypes: Array,\n maxSize: Number,\n };\n\n isAllowedFile(file) {\n if (this.allowedTypesValue.includes(file.type)) return true;\n\n const ext = file.name.split(\".\").pop()?.toLowerCase();\n return ext && ALLOWED_EXTENSIONS.includes(ext);\n }\n\n openFilePicker() {\n this.inputTarget.click();\n }\n\n openCamera() {\n this.cameraInputTarget.click();\n }\n\n openVideoCamera() {\n this.videoCameraInputTarget.click();\n }\n\n selectFiles(event) {\n this.uploadFiles(Array.from(event.target.files));\n event.target.value = \"\";\n }\n\n drop(event) {\n event.preventDefault();\n this.dropzoneTarget.classList.remove(\"imm-media-upload-zone--dragover\");\n const files = Array.from(event.dataTransfer.files);\n this.uploadFiles(files);\n }\n\n dragover(event) {\n event.preventDefault();\n this.dropzoneTarget.classList.add(\"imm-media-upload-zone--dragover\");\n }\n\n dragleave() {\n this.dropzoneTarget.classList.remove(\"imm-media-upload-zone--dragover\");\n }\n\n uploadFiles(files) {\n if (files.length === 0) return;\n\n const maxSizeMb = Math.round(this.maxSizeValue / (1024 * 1024));\n const valid = [];\n files.forEach((file) => {\n if (!this.isAllowedFile(file)) {\n this.showRejection(file.name, \"unsupported file type\");\n return;\n }\n if (file.size > this.maxSizeValue) {\n this.showRejection(file.name, `file is too large (max ${maxSizeMb}MB)`);\n return;\n }\n valid.push(file);\n });\n\n if (valid.length === 0) return;\n\n this.progressTarget.classList.remove(\"hidden\");\n valid.forEach((file) => this.uploadFile(file));\n }\n\n showRejection(filename, reason) {\n const id = `upload-rejected-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n this.progressTarget.classList.remove(\"hidden\");\n const html = `\n
\n ${this.escapeHtml(filename)}\n
\n
\n
\n ${this.escapeHtml(reason)}\n \\u274C\n
`;\n this.progressTarget.insertAdjacentHTML(\"beforeend\", html);\n setTimeout(() => {\n const el = document.getElementById(id);\n if (el) el.remove();\n if (this.progressTarget.children.length === 0) {\n this.progressTarget.classList.add(\"hidden\");\n }\n }, 5000);\n }\n\n uploadFile(file) {\n const progressId = `upload-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n this.addProgressBar(progressId, file.name);\n\n const upload = new DirectUpload(\n file,\n \"/rails/active_storage/direct_uploads\",\n {\n directUploadWillStoreFileWithXHR: (request) => {\n request.upload.addEventListener(\"progress\", (event) => {\n const percent = Math.round((event.loaded / event.total) * 100);\n this.updateProgressBar(progressId, percent);\n });\n },\n },\n );\n\n upload.create((error, blob) => {\n if (error) {\n this.markProgressError(progressId, error);\n } else {\n this.updateProgressBar(progressId, 100);\n this.createMediaRecord(blob.signed_id, file.type, progressId);\n }\n });\n }\n\n createMediaRecord(signedId, contentType, progressId) {\n const mediaType = contentType.startsWith(\"video/\") ? \"video\" : \"photo\";\n const formData = new FormData();\n formData.append(\"file\", signedId);\n formData.append(\"media_type\", mediaType);\n\n fetch(this.urlValue, {\n method: \"POST\",\n body: formData,\n headers: {\n \"X-CSRF-Token\": this.csrfToken,\n Accept: \"text/vnd.turbo-stream.html\",\n },\n })\n .then((response) => {\n if (response.ok) {\n return response.text().then((html) => {\n this.markProgressSuccess(progressId);\n Turbo.renderStreamMessage(html);\n this.dispatch(\"complete\", { prefix: \"imm-media\", bubbles: true });\n });\n } else {\n this.markProgressError(progressId, \"Upload failed\");\n }\n })\n .catch(() => {\n this.markProgressError(progressId, \"Network error\");\n });\n }\n\n // --- Progress UI ---\n\n addProgressBar(id, filename) {\n const html = `\n
\n ${this.escapeHtml(filename)}\n
\n
\n
\n 0%\n \n
`;\n this.progressTarget.insertAdjacentHTML(\"beforeend\", html);\n }\n\n updateProgressBar(id, percent) {\n const el = document.getElementById(id);\n if (!el) return;\n el.querySelector(\"[data-bar]\").style.width = `${percent}%`;\n el.querySelector(\"[data-percent]\").textContent = `${percent}%`;\n }\n\n markProgressSuccess(id) {\n const el = document.getElementById(id);\n if (!el) return;\n el.querySelector(\"[data-bar]\").style.width = \"100%\";\n el.querySelector(\"[data-percent]\").textContent = \"100%\";\n const icon = el.querySelector(\"[data-icon]\");\n icon.textContent = \"\\u2705\";\n // Extra breathing room for the check icon: \"100%\" sits at the right\n // edge of its fixed-width w-16 span, so a larger gap reads as balanced.\n // Error icons keep the default ml-2 -- their status text is auto-width\n // and already ends adjacent to the icon column.\n //\n // NOTE: this Tailwind config has `important: true`, so `ml-2` is\n // !important in the compiled CSS. A plain inline style loses to it.\n // setProperty with 'important' is required to override.\n icon.style.setProperty(\"margin-left\", \"20px\", \"important\");\n\n setTimeout(() => this.removeProgressBar(id), 1500);\n }\n\n removeProgressBar(id) {\n const el = document.getElementById(id);\n if (el) el.remove();\n\n if (this.progressTarget.children.length === 0) {\n this.progressTarget.classList.add(\"hidden\");\n }\n }\n\n markProgressError(id, error) {\n const el = document.getElementById(id);\n if (!el) return;\n el.querySelector(\"[data-bar]\").classList.replace(\n \"bg-green-500\",\n \"bg-red-500\",\n );\n const status = el.querySelector(\"[data-percent]\");\n // Drop the fixed width so longer error text (\"Network error\",\n // \"Upload failed\", etc.) can size to its content instead of\n // overflowing and colliding with the icon.\n status.classList.remove(\"w-16\");\n status.textContent = error || \"Error\";\n status.classList.add(\"text-red-500\");\n el.querySelector(\"[data-icon]\").textContent = \"\\u274C\";\n\n setTimeout(() => this.removeProgressBar(id), 5000);\n }\n\n escapeHtml(text) {\n const div = document.createElement(\"div\");\n div.textContent = text;\n return div.innerHTML;\n }\n\n get csrfToken() {\n return document.querySelector(\"[name='csrf-token']\")?.content;\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Gates the \"Save & Continue\" button on the Map Data step: the button stays\n// disabled until every required input has a value (all sales-rep mappings,\n// default assignee, default lost reason, default upsheet date). Inputs opt in\n// via the \"required\" target; input/change events bubble up to the form.\nexport default class extends Controller {\n static targets = [\"required\", \"submit\"];\n\n connect() {\n this.validate();\n }\n\n validate() {\n const allFilled = this.requiredTargets.every((el) => el.value.trim() !== \"\");\n this.submitTarget.disabled = !allFilled;\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport fetch from \"@/utils/fetch\";\n\n// Connects to data-controller=\"import-connection-reorder\"\nexport default class extends Controller {\n static targets = [\"body\"];\n static values = { url: String };\n\n connect() {\n this.draggedRow = null;\n }\n\n // Drag starts from the handle , but we drag the whole \n dragstart(event) {\n this.draggedRow = event.target.closest(\"tr\");\n this.draggedRow.classList.add(\"dragging\");\n event.dataTransfer.effectAllowed = \"move\";\n event.dataTransfer.setDragImage(this.draggedRow, 0, 0);\n }\n\n dragover(event) {\n event.preventDefault();\n event.dataTransfer.dropEffect = \"move\";\n\n const target = event.target.closest(\"tr[data-id]\");\n if (!target || target === this.draggedRow) return;\n\n const tbody = this.bodyTarget;\n const rows = [...tbody.querySelectorAll(\"tr[data-id]\")];\n const draggedIndex = rows.indexOf(this.draggedRow);\n const targetIndex = rows.indexOf(target);\n\n if (draggedIndex < targetIndex) {\n target.after(this.draggedRow);\n } else {\n target.before(this.draggedRow);\n }\n }\n\n dragend() {\n if (!this.draggedRow) return;\n this.draggedRow.classList.remove(\"dragging\");\n this.draggedRow = null;\n\n this.updatePriorityLabels();\n this.saveOrder();\n }\n\n updatePriorityLabels() {\n const rows = this.bodyTarget.querySelectorAll(\"tr[data-id]\");\n rows.forEach((row, index) => {\n const label = row.querySelector(\"[data-priority]\");\n if (label) label.textContent = index + 1;\n });\n }\n\n async saveOrder() {\n const rows = this.bodyTarget.querySelectorAll(\"tr[data-id]\");\n const orderedIds = [...rows].map((row) => parseInt(row.dataset.id, 10));\n\n try {\n const response = await fetch(this.urlValue, {\n method: \"PATCH\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ ordered_ids: orderedIds }),\n });\n\n if (!response.ok) {\n alert(\"Failed to save order. The page will reload.\");\n window.location.reload();\n }\n } catch {\n alert(\"Failed to save order. The page will reload.\");\n window.location.reload();\n }\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"import-source-fields\"\n//\n// The \"Dealership ID\" box means something different for every source, and for the\n// ones backed by a vendor API it is the one thing the integration cannot run\n// without. Leaving it as another blank box in the row is how a source gets added\n// with an empty key and then quietly imports nothing, so name it and mark it\n// required as soon as such a source is picked.\n//\n// Those same sources authenticate with one AutoRaptor-wide credential read from\n// the environment (PBS_USERNAME / PBS_PASSWORD), never with anything typed here,\n// so the username and password boxes are hidden and disabled for them \u2014 leaving\n// them in the row invites a per-dealership login that nothing would ever read.\nexport default class extends Controller {\n static targets = [\"source\", \"uniqueKey\", \"hint\", \"credential\"];\n static values = { serialRequiredSourceIds: Array };\n\n connect() {\n this.refresh();\n }\n\n refresh() {\n const needsSerial = this.serialRequiredSourceIdsValue.includes(\n Number(this.sourceTarget.value),\n );\n\n this.uniqueKeyTarget.required = needsSerial;\n this.uniqueKeyTarget.placeholder = needsSerial ? \"Serial\" : \"\";\n if (this.hasHintTarget) this.hintTarget.hidden = !needsSerial;\n\n // Disabled as well as hidden: a hidden-but-enabled input still posts its\n // value, and the point is that there is no per-connection credential.\n this.credentialTargets.forEach((field) => {\n field.hidden = needsSerial;\n field.disabled = needsSerial;\n if (needsSerial) field.value = \"\";\n });\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Polls the import show endpoint (as JSON) on an interval to update the\n// progress bar, row counts, and percentage. Reloads the page once the import\n// (or rollback) finishes so the user sees the final state with result actions.\n//\n// This controller is only attached by the view while the import is actively\n// running (importing / rolling_back), so reloading whenever complete is true is\n// safe: the reloaded terminal page no longer attaches the controller, so there\n// is no reload loop \u2014 even if the job finished before the first poll.\nexport default class extends Controller {\n static targets = [\n \"progressBar\", \"processedCount\", \"failedCount\", \"failedRowsTitle\",\n \"failedSection\", \"skippedCount\", \"percentage\", \"status\",\n ];\n\n static values = { url: String, interval: { type: Number, default: 5000 } };\n\n connect() {\n this.poll();\n }\n\n disconnect() {\n clearTimeout(this.timer);\n }\n\n async poll() {\n try {\n const response = await fetch(this.urlValue, {\n headers: { Accept: \"application/json\" },\n });\n const data = await response.json();\n\n this.updateProgress(data);\n\n if (!data.complete) {\n this.timer = setTimeout(() => this.poll(), this.intervalValue);\n }\n } catch {\n this.timer = setTimeout(() => this.poll(), this.intervalValue);\n }\n }\n\n updateProgress(data) {\n const pct = data.total_rows > 0 ? ((data.processed_rows / data.total_rows) * 100).toFixed(1) : 0;\n\n if (this.hasProgressBarTarget) this.progressBarTarget.value = pct;\n if (this.hasPercentageTarget) this.percentageTarget.textContent = `${pct}%`;\n if (this.hasProcessedCountTarget) this.processedCountTarget.textContent = data.processed_rows;\n if (this.hasFailedCountTarget) this.failedCountTarget.textContent = data.failed_rows;\n if (this.hasSkippedCountTarget) this.skippedCountTarget.textContent = data.skipped_rows;\n if (this.hasFailedRowsTitleTarget) this.failedRowsTitleTarget.textContent = data.failed_rows;\n if (this.hasFailedSectionTarget) this.failedSectionTarget.hidden = data.failed_rows === 0;\n\n if (data.complete) {\n window.location.reload();\n }\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Adjusts the file input based on the selected import type.\n// Standard imports accept a single file; VinSolutions requires exactly three.\nexport default class extends Controller {\n static targets = [\"fileInput\", \"hint\"];\n\n connect() {\n this.update();\n }\n\n update() {\n const type = this.element.querySelector(\"[data-import-type-select]\").value;\n\n if (type === \"vinsolutions\") {\n this.fileInputTarget.multiple = true;\n this.hintTarget.textContent = \"Upload exactly 3 files: customers, leads, and users (.csv, .xlsx)\";\n } else {\n this.fileInputTarget.multiple = false;\n // Clear selection if more than one file was previously selected\n if (this.fileInputTarget.files && this.fileInputTarget.files.length > 1) {\n this.fileInputTarget.value = \"\";\n }\n this.hintTarget.textContent = \"Accepted formats: .csv, .xlsx\";\n }\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport fetch from \"@/utils/fetch\";\n\nconst FIELDS = [\"year\", \"make\", \"model\", \"trim\"];\n\n// Fills the empty identity boxes on Add vehicle once the VIN is 17 characters.\n// A box the user has typed in is left alone; a box this controller filled is\n// replaced when a different VIN decodes.\nexport default class extends Controller {\n static targets = [\"vin\", \"year\", \"make\", \"model\", \"trim\", \"note\"];\n\n static values = { url: String };\n\n connect() {\n this.owned = new Set();\n this.requestSeq = 0;\n this.pendingVin = \"\";\n }\n\n decode() {\n const vin = this.vinTarget.value.trim().toUpperCase();\n if (vin.length !== 17) {\n this.pendingVin = \"\";\n this.noteTarget.textContent = \"\";\n return;\n }\n if (vin === this.pendingVin) return;\n\n this.pendingVin = vin;\n this.lookup(vin);\n }\n\n // The user took this box over, so the next decode must not replace it.\n keep({ target }) {\n const field = target.dataset.vinDecodeField;\n if (field) this.owned.delete(field);\n }\n\n async lookup(vin) {\n const request = ++this.requestSeq;\n this.noteTarget.textContent = \"Looking up this VIN\u2026\";\n\n try {\n const response = await fetch(this.urlValue, {\n method: \"POST\",\n headers: { Accept: \"application/json\", \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ vin }),\n });\n if (request !== this.requestSeq) return;\n\n const data = await response.json();\n if (request !== this.requestSeq) return;\n\n if (data.status === \"decoded\") {\n FIELDS.forEach((field) => this.write(field, data[field]));\n }\n this.noteTarget.textContent = this.message(data);\n } catch {\n if (request !== this.requestSeq) return;\n if (this.pendingVin === vin) this.pendingVin = \"\";\n this.noteTarget.textContent = \"VIN lookup is unavailable. Fill in the details.\";\n }\n }\n\n write(field, value) {\n const input = this[`${field}Target`];\n const text = value == null ? \"\" : String(value);\n if (input.value.trim() !== \"\" && !this.owned.has(field)) return;\n\n if (text === \"\") {\n if (this.owned.has(field)) input.value = \"\";\n this.owned.delete(field);\n return;\n }\n\n input.value = text;\n this.owned.add(field);\n }\n\n message(data) {\n if (data.status === \"not_found\") return \"No vehicle data for this VIN. Fill in the details.\";\n if (data.status !== \"decoded\") return \"This VIN could not be decoded. Fill in the details.\";\n\n const notes = [];\n if (data.year_ambiguous) notes.push(\"The year is ambiguous. Enter it.\");\n if (data.ambiguous) notes.push(\"This VIN matches more than one trim. Choose the trim.\");\n return notes.join(\" \") || \"Filled in from the VIN.\";\n }\n}\n", "import { createWorker, OEM, PSM } from \"tesseract.js\";\nimport { findVin } from \"@/utils/vin\";\n\n// Reads a VIN printed as text (the dash plate behind the windshield), which the\n// Scandit barcode scanner cannot. The worker, the WASM core and the English\n// model are served from public/tesseract, staged by package.json's postinstall.\n// The paths must be absolute: the worker boots from a blob: URL, where a\n// relative path has nothing to resolve against.\nconst assetUrl = (path) => new URL(`/tesseract/${path}`, document.baseURI).toString();\nconst VIN_CHARACTERS = \"ABCDEFGHJKLMNPRSTUVWXYZ0123456789\";\n\n// The guide band: a strip across the middle of the frame. The crop sent to OCR\n// is exactly this strip, and it has to be thin: on the field photo a 6:1 strip\n// around the plate read the VIN and a 4:1 one, with dash and glare in it, read\n// nothing.\nconst BAND = { left: 0.06, width: 0.88, aspect: 6 };\nconst OCR_WIDTH = 1280;\nconst RETRY_DELAY_MS = 150;\nexport const GIVE_UP_MS = 20_000;\n\nexport class VinTextReader {\n /** @param {HTMLElement} container */\n constructor(container) {\n this.container = container;\n this.open = false;\n }\n\n /**\n * Resolves with the VIN, or with null when nothing readable turned up before\n * GIVE_UP_MS. Rejects when the camera or the OCR engine cannot start.\n * @param {(status: string) => void} onStatus\n * @returns {Promise}\n */\n async read(onStatus) {\n this.open = true;\n onStatus(\"Starting the camera\u2026\");\n\n this.stream = await navigator.mediaDevices.getUserMedia({\n audio: false,\n video: { facingMode: { ideal: \"environment\" }, width: { ideal: 1920 }, height: { ideal: 1080 } },\n });\n if (!this.open) return this.#stop();\n\n this.video = this.#mountVideo();\n this.video.srcObject = this.stream;\n await this.video.play();\n\n onStatus(\"Loading text recognition\u2026\");\n this.worker = await createWorker(\"eng\", OEM.LSTM_ONLY, {\n workerPath: assetUrl(\"worker.min.js\"),\n corePath: assetUrl(\"core\"),\n langPath: assetUrl(\"lang\"),\n }, {\n // A VIN is not a word: the dictionaries only pull reads toward English.\n load_system_dawg: \"0\",\n load_freq_dawg: \"0\",\n });\n await this.worker.setParameters({\n tessedit_char_whitelist: VIN_CHARACTERS,\n tessedit_pageseg_mode: PSM.SINGLE_LINE,\n });\n if (!this.open) return this.#stop();\n\n onStatus(\"Line the VIN up inside the box.\");\n const canvas = document.createElement(\"canvas\");\n const deadline = Date.now() + GIVE_UP_MS;\n\n // The check digit still lets one random misread in eleven through, so a VIN\n // only counts once two frames in a row read the same one.\n let previous = null;\n while (this.open && Date.now() < deadline) {\n const { data } = await this.worker.recognize(this.#cropBand(canvas));\n const vin = findVin(data.text);\n if (vin && vin === previous) {\n await this.#stop();\n return vin;\n }\n previous = vin;\n await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));\n }\n\n return this.#stop();\n }\n\n close() {\n this.open = false;\n return this.#stop();\n }\n\n #mountVideo() {\n const frame = document.createElement(\"div\");\n frame.className = \"relative w-full overflow-hidden rounded-lg bg-black\";\n\n const video = document.createElement(\"video\");\n video.className = \"block w-full h-auto\";\n video.muted = true;\n video.playsInline = true;\n video.setAttribute(\"playsinline\", \"\");\n\n const band = document.createElement(\"div\");\n band.className = \"absolute top-1/2 -translate-y-1/2 border-2 border-solid border-white rounded-sm shadow-[0_0_0_9999px_rgba(0,0,0,0.45)]\";\n band.style.left = `${BAND.left * 100}%`;\n band.style.width = `${BAND.width * 100}%`;\n band.style.aspectRatio = String(BAND.aspect);\n\n frame.append(video, band);\n this.container.replaceChildren(frame);\n return video;\n }\n\n // The video is drawn at its natural aspect ratio (w-full h-auto), so the band's\n // place in the element is the same place in the camera frame.\n /** @param {HTMLCanvasElement} canvas */\n #cropBand(canvas) {\n const { videoWidth, videoHeight } = this.video;\n const sw = videoWidth * BAND.width;\n const sh = sw / BAND.aspect;\n const sx = videoWidth * BAND.left;\n const sy = (videoHeight - sh) / 2;\n const scale = OCR_WIDTH / sw;\n\n canvas.width = OCR_WIDTH;\n canvas.height = Math.round(sh * scale);\n // No contrast filter: Tesseract binarizes on its own, and on the field photo\n // a contrast(1.4) pass washed the embossed characters out until nothing read.\n const context = canvas.getContext(\"2d\");\n context.drawImage(this.video, sx, sy, sw, sh, 0, 0, canvas.width, canvas.height);\n return canvas;\n }\n\n async #stop() {\n this.open = false;\n this.stream?.getTracks().forEach((track) => track.stop());\n this.stream = null;\n if (this.video) this.video.srcObject = null;\n this.video = null;\n this.container.replaceChildren();\n\n const worker = this.worker;\n this.worker = null;\n await worker?.terminate();\n return null;\n }\n}\n\nexport default VinTextReader;\n", "// Mirrors app/models/vin.rb. I, O and Q never appear in a VIN.\n// Each letter's transliteration value, in the order of LETTERS.\nconst LETTERS = \"ABCDEFGHJKLMNPRSTUVWXYZ\";\nconst LETTER_VALUES = \"12345678123457923456789\";\nconst POSITION_WEIGHTS = [8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2];\nconst CHECK_DIGIT_INDEX = 8;\n\n/** @param {string} vin */\nexport function checkDigitMatches(vin) {\n if (!/^[A-HJ-NPR-Z0-9]{17}$/.test(vin)) return false;\n\n const sum = [...vin].reduce((total, char, i) => {\n const value = /\\d/.test(char) ? Number(char) : Number(LETTER_VALUES[LETTERS.indexOf(char)]);\n return total + value * POSITION_WEIGHTS[i];\n }, 0);\n const checksum = sum % 11 === 10 ? \"X\" : String(sum % 11);\n return vin[CHECK_DIGIT_INDEX] === checksum;\n}\n\n// OCR output is noisy: spaces inside the VIN, stray marks around it (the edge\n// of the plate often reads as a lone character), a \"VIN\" label in front of it,\n// and the letters a VIN cannot hold read in place of the digits they look like.\n// A random 17 characters pass the check digit one time in eleven, so a window\n// that starts and ends where the OCR broke the text wins over one that cuts\n// through a word, and a line still left with more than one candidate yields\n// nothing: better no read than a wrong VIN in the box.\n/** @param {string} text */\nexport function findVin(text) {\n for (const line of text.toUpperCase().split(/\\n/)) {\n const words = line\n .replace(/^[^A-Z0-9]*V\\W*[I1L]\\W*N\\b/, \"\")\n .split(/[^A-Z0-9]+/)\n .filter(Boolean)\n .map((word) => word.replace(/[OQ]/g, \"0\").replace(/I/g, \"1\"));\n\n const compact = words.join(\"\");\n const breaks = new Set([0]);\n words.reduce((end, word) => { breaks.add(end + word.length); return end + word.length; }, 0);\n\n const aligned = new Set();\n const unaligned = new Set();\n for (let start = 0; start + 17 <= compact.length; start++) {\n const candidate = compact.slice(start, start + 17);\n if (!checkDigitMatches(candidate)) continue;\n (breaks.has(start) && breaks.has(start + 17) ? aligned : unaligned).add(candidate);\n }\n\n const matches = aligned.size > 0 ? aligned : unaligned;\n if (matches.size === 1) return [...matches][0];\n }\n return null;\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport VinTextReader from \"@/ui/vin_text_reader\";\nimport ErrorNotifier from \"../../error_notifier\";\n\n// Connects to data-controller=\"inventory--vin-text\"\n// Reads the VIN printed on the dash plate with OCR, for cars where there is no\n// barcode to point the Scandit scanner at.\nexport default class extends Controller {\n static targets = [\"output\", \"status\", \"button\", \"vinInput\"];\n\n connect() {\n this.reader = new VinTextReader(this.outputTarget);\n }\n\n disconnect() {\n this.reader.close();\n }\n\n async toggle() {\n if (this.reader.open) {\n this.cancelled = true;\n await this.reader.close();\n this.#finish(\"\");\n return;\n }\n\n this.cancelled = false;\n this.buttonTarget.setAttribute(\"aria-pressed\", \"true\");\n this.statusTarget.removeAttribute(\"data-error\");\n\n try {\n const vin = await this.reader.read((status) => { this.statusTarget.textContent = status; });\n if (this.cancelled) return;\n\n if (vin) {\n this.#fill(vin);\n this.#finish(\"\");\n } else {\n this.#finish(\"Couldn't read the VIN. Move closer, avoid glare on the glass, or type it in.\", true);\n }\n } catch (error) {\n // close() terminates the worker mid-recognize, which rejects; that is the user stopping, not a failure.\n if (this.cancelled) return;\n await this.reader.close();\n this.#finish(this.#errorMessage(error), true);\n }\n }\n\n /** @param {string} vin */\n #fill(vin) {\n this.vinInputTarget.value = vin;\n this.dispatch(\"scan\", { detail: { vin } });\n this.vinInputTarget.dispatchEvent(new InputEvent(\"input\", { bubbles: true }));\n this.vinInputTarget.dispatchEvent(new Event(\"change\", { bubbles: true }));\n }\n\n /** @param {string} message */\n #finish(message, error = false) {\n this.buttonTarget.setAttribute(\"aria-pressed\", \"false\");\n this.statusTarget.textContent = message;\n this.statusTarget.toggleAttribute(\"data-error\", error);\n }\n\n /** @param {Error} error */\n #errorMessage(error) {\n if (error.name === \"NotAllowedError\") return \"To read the VIN, please enable camera access in your browser settings.\";\n if (error.name === \"NotFoundError\") return \"No camera detected on this device.\";\n\n ErrorNotifier.notify({ error: `VIN text reader error: ${error.message}`, context: error });\n return \"There was an issue starting the VIN reader. Please try again.\";\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\nexport default class extends Controller {\n static targets = [\"modal\", \"textarea\"];\n\n static values = {\n modalId: String,\n fieldName: String,\n templateType: String,\n };\n\n connect() {\n this.templates = {\n business_rules: {\n return_policy: \"7-day/500-mile return policy on all certified pre-owned vehicles\\n30-day exchange option available on new vehicles\\nAll sales final on vehicles sold \\\"as-is\\\"\\nReturn requires original condition with no modifications\",\n test_drive: \"Valid driver's license required for all test drives\\nInsurance verification required for extended test drives\\nTest drives limited to 30 minutes/15 miles\\nSales associate must accompany on all test drives\",\n pricing: \"All advertised prices include dealer fees\\nPrices exclude tax, title, and registration\\nWe match written competitor quotes within 50 miles\\nInternet pricing valid for 7 days from quote date\",\n warranty: \"All new vehicles include full manufacturer warranty\\nCertified pre-owned includes 12-month/12,000-mile warranty\\nExtended warranties available up to 7 years/100,000 miles\\nWarranty work performed by certified technicians only\",\n },\n behavioral_instructions: {\n consultative: \"Always start by understanding the customer's needs and budget\\nAsk open-ended questions about their lifestyle and preferences\\nRecommend vehicles based on their stated requirements\\nNever push a sale - focus on finding the right fit\\nOffer multiple options at different price points\",\n friendly: \"Use a warm, conversational tone like talking to a friend\\nShow genuine interest in helping them find the perfect vehicle\\nShare personal experiences when relevant\\nUse the customer's name once you learn it\\nKeep the conversation light but informative\",\n luxury: \"Maintain a sophisticated, professional demeanor\\nEmphasize premium features and exclusive benefits\\nFocus on the experience, not just the vehicle\\nHighlight white-glove services and attention to detail\\nSpeak to long-term value and investment quality\",\n value: \"Always mention current incentives and savings opportunities\\nHighlight total cost of ownership, not just purchase price\\nEmphasize reliability ratings and low maintenance costs\\nCompare value against competitors\\nFocus on practical benefits and smart financial decisions\",\n },\n business_information: {\n established: \"Family-owned and operated since [YEAR]\\n[NUMBER] years serving the [CITY/REGION] community\\nThree generations of automotive excellence\\nOver [NUMBER] satisfied customers\",\n awards: \"[YEAR] [Brand] President's Award Winner\\n[Rating] star Google/Yelp rating with [number] reviews\\nBBB A+ Accredited Business\\n[Publication] Best Dealership Award [YEAR]\",\n community: \"Proud sponsor of [local sports team/school]\\nActive supporter of [local charity]\\nEmploying [number] local residents\\nContributing $[amount] annually to community causes\",\n facilities: \"[NUMBER] acre campus with [NUMBER] showrooms\\n[NUMBER]-bay state-of-the-art service center\\nComfortable customer lounge with WiFi and refreshments\\n[NUMBER] vehicle inventory with indoor showroom\",\n },\n response_scripts: {\n pricing: \"User asks about \\\"best price\\\" -> \\\"I'd be happy to discuss pricing! Our vehicles are competitively priced, and I can share current incentives. Which vehicle are you interested in?\\\"\\n\\nUser asks for discount -> \\\"I understand you're looking for the best value. Let me check what incentives and programs you might qualify for. Are you trading in a vehicle?\\\"\\n\\nUser says price is too high -> \\\"I appreciate your concern about the price. Let's explore financing options that could make this work within your budget. What monthly payment range were you considering?\\\"\",\n tradein: \"User asks about trade-in -> \\\"We'd love to evaluate your trade-in! You can get an instant estimate on our website, or I can connect you with our appraisal team. What vehicle would you be trading?\\\"\\n\\nUser asks if we buy cars -> \\\"Yes, we buy cars even if you don't purchase from us! We offer competitive prices based on current market values. Would you like to schedule an appraisal?\\\"\",\n financing: \"User asks about financing -> \\\"We work with over 20 lenders to find you the best rates! Approval takes just minutes. Would you like to get pre-qualified with no impact to your credit?\\\"\\n\\nUser worried about credit -> \\\"We help customers with all credit situations. Our finance team specializes in finding solutions. Shall I connect you with them for a confidential consultation?\\\"\",\n objections: \"User says \\\"just looking\\\" -> \\\"That's perfectly fine! Feel free to browse, and I'm here if you have any questions. Is there a particular type of vehicle you're interested in?\\\"\\n\\nUser needs to think about it -> \\\"I completely understand - this is an important decision. Can I send you the information we discussed so you can review it at your convenience?\\\"\\n\\nUser wants to shop around -> \\\"That makes sense! I'd encourage you to compare. Would you like me to put together a detailed quote that includes all our current incentives for your comparison?\\\"\",\n },\n additional_context: {\n multilingual: \"Spanish-speaking sales and service staff available\\nAll documents available in Spanish and English\\nChinese (Mandarin) speaking staff available by appointment\\nWebsite and materials available in multiple languages\",\n special_programs: \"Military and veteran discount program - $500 off\\nFirst responder appreciation discount\\nCollege graduate program with special financing\\nCorporate fleet accounts welcome\\nState employee purchase program participant\",\n fleet: \"Dedicated fleet sales department\\nVolume discounts available for 5+ vehicles\\nCustom upfitting services available\\nFlexible commercial financing options\\nOn-site service for fleet customers\",\n ev: \"Certified electric vehicle dealer\\nLevel 2 and Level 3 charging stations on-site\\nEV-trained technicians and sales staff\\nTax credit assistance and paperwork support\\nHome charging installation partnerships available\",\n },\n primary_goals: {\n lead_qualification: \"* Identify customer's vehicle type preference (new/used) within first 3 exchanges\\n* Determine budget range or monthly payment comfort level\\n* Understand timeline for purchase (immediate, this month, researching)\\n* Capture verified contact information before providing detailed quotes\\n* Qualify trade-in interest and gather basic vehicle information\",\n sales_conversion: \"* Present 2-3 specific vehicles matching customer's stated needs\\n* Highlight unique selling points and current promotions\\n* Create urgency with limited-time offers or low inventory alerts\\n* Schedule test drives for qualified buyers within the conversation\\n* Provide competitive advantages over other dealerships\",\n appointment_focused: \"* Establish vehicle preferences and needs upfront\\n* Confirm inventory availability for customer's interests\\n* Schedule specific appointment times within 48 hours\\n* Capture complete contact information for appointment reminders\\n* Send appointment confirmation with dealership directions\",\n trade_focused: \"* Identify current vehicle details (year, make, model, mileage)\\n* Assess condition and any modifications or damage\\n* Provide instant trade-in value estimate range\\n* Explain trade-in process and required documents\\n* Schedule in-person appraisal appointment\",\n service_excellence: \"* Answer all questions thoroughly before requesting contact info\\n* Provide detailed vehicle specifications and availability\\n* Offer multiple communication channels for follow-up\\n* Connect customers with appropriate department specialists\\n* Ensure positive experience regardless of purchase timeline\",\n },\n dealership_goals: {\n lead_qualification: \"* Identify customer's vehicle type preference (new/used) within first 3 exchanges\\n* Determine budget range or monthly payment comfort level\\n* Understand timeline for purchase (immediate, this month, researching)\\n* Capture verified contact information before providing detailed quotes\\n* Qualify trade-in interest and gather basic vehicle information\",\n sales_conversion: \"* Present 2-3 specific vehicles matching customer's stated needs\\n* Highlight unique selling points and current promotions\\n* Create urgency with limited-time offers or low inventory alerts\\n* Schedule test drives for qualified buyers within the conversation\\n* Provide competitive advantages over other dealerships\",\n appointment_focused: \"* Establish vehicle preferences and needs upfront\\n* Confirm inventory availability for customer's interests\\n* Schedule specific appointment times within 48 hours\\n* Capture complete contact information for appointment reminders\\n* Send appointment confirmation with dealership directions\",\n trade_focused: \"* Identify current vehicle details (year, make, model, mileage)\\n* Assess condition and any modifications or damage\\n* Provide instant trade-in value estimate range\\n* Explain trade-in process and required documents\\n* Schedule in-person appraisal appointment\",\n service_excellence: \"* Answer all questions thoroughly before requesting contact info\\n* Provide detailed vehicle specifications and availability\\n* Offer multiple communication channels for follow-up\\n* Connect customers with appropriate department specialists\\n* Ensure positive experience regardless of purchase timeline\",\n },\n };\n\n this.setupEscapeKey();\n }\n\n setupEscapeKey() {\n this.escapeHandler = (event) => {\n if (event.key === \"Escape\") {\n const openModal = this.element.querySelector(\"[data-knowledge-help-modal-target=\\\"modal\\\"].show\");\n if (openModal) {\n this.closeModalById(openModal.id);\n }\n }\n };\n document.addEventListener(\"keydown\", this.escapeHandler);\n }\n\n disconnect() {\n if (this.escapeHandler) {\n document.removeEventListener(\"keydown\", this.escapeHandler);\n }\n }\n\n open(event) {\n event.preventDefault();\n const modalId = event.currentTarget.dataset.modalId || this.modalIdValue;\n this.openModal(modalId);\n }\n\n close(event) {\n event.preventDefault();\n const modalId = event.currentTarget.dataset.modalId ||\n event.currentTarget.closest(\"[data-knowledge-help-modal-target=\\\"modal\\\"]\")?.id;\n if (modalId) {\n this.closeModalById(modalId);\n }\n }\n\n closeOnBackdrop(event) {\n if (event.target === event.currentTarget) {\n const modalId = event.currentTarget.id;\n this.closeModalById(modalId);\n }\n }\n\n stopPropagation(event) {\n event.stopPropagation();\n }\n\n openModal(modalId) {\n const modal = document.getElementById(modalId);\n if (modal) {\n modal.classList.add(\"show\");\n document.body.style.overflow = \"hidden\";\n // Ensure modal scrolls to top when opened\n modal.scrollTop = 0;\n window.scrollTo(0, 0);\n\n // Hide the main content to prevent interference\n const header = document.querySelector(\".z-topmost\") || document.querySelector(\"[data-controller=\\\"layout--header\\\"]\");\n const nav = document.querySelector(\".sticky.top-0\") || document.querySelector(\"nav\");\n const main = document.querySelector(\"main\") || document.querySelector(\"#main\") || document.querySelector(\".main\");\n\n if (header) header.style.display = \"none\";\n if (nav) nav.style.display = \"none\";\n if (main) main.style.display = \"none\";\n\n // Store references for restoration\n this.hiddenElements = { header, nav, main };\n }\n }\n\n closeModalById(modalId) {\n const modal = document.getElementById(modalId);\n if (modal) {\n modal.classList.remove(\"show\");\n document.body.style.overflow = \"auto\";\n\n // Restore hidden elements\n if (this.hiddenElements) {\n if (this.hiddenElements.header) this.hiddenElements.header.style.display = \"\";\n if (this.hiddenElements.nav) this.hiddenElements.nav.style.display = \"\";\n if (this.hiddenElements.main) this.hiddenElements.main.style.display = \"\";\n this.hiddenElements = null;\n } else {\n // Fallback: try to restore elements even if they weren't stored\n const header = document.querySelector(\".z-topmost\") || document.querySelector(\"[data-controller=\\\"layout--header\\\"]\");\n const nav = document.querySelector(\".sticky.top-0\") || document.querySelector(\"nav\");\n const main = document.querySelector(\"main\") || document.querySelector(\"#main\") || document.querySelector(\".main\");\n\n if (header) header.style.display = \"\";\n if (nav) nav.style.display = \"\";\n if (main) main.style.display = \"\";\n }\n }\n }\n\n insertTemplate(event) {\n event.preventDefault();\n const button = event.currentTarget;\n const fieldName = button.dataset.fieldName || this.fieldNameValue;\n const templateType = button.dataset.templateType || this.templateTypeValue;\n\n // Find the textarea field in the AISA configuration form\n const textarea = document.querySelector(`textarea[name=\"aisa_dealership_configuration[${fieldName}]\"]`);\n\n if (textarea && this.templates[fieldName] && this.templates[fieldName][templateType]) {\n const currentValue = textarea.value;\n const newTemplate = this.templates[fieldName][templateType];\n\n if (currentValue) {\n textarea.value = currentValue + \"\\n\\n\" + newTemplate;\n } else {\n textarea.value = newTemplate;\n }\n\n const modalId = fieldName.replace(/_/g, \"-\") + \"-modal\";\n this.closeModalById(modalId);\n\n textarea.style.backgroundColor = \"#e8f5e9\";\n setTimeout(() => {\n textarea.style.backgroundColor = \"\";\n }, 500);\n\n textarea.scrollIntoView({ behavior: \"smooth\", block: \"center\" });\n }\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"layout--global-search\"\nexport default class extends Controller {\n static targets = [\n \"query\",\n ];\n\n connect() {\n const el = this.queryTarget;\n const len = el.value.length;\n\n if (el.setSelectionRange) {\n el.focus();\n el.setSelectionRange(len, len);\n } else {\n if (el.createTextRange) {\n const range = el.createTextRange();\n range.collapse(true);\n range.moveEnd(\"character\", len);\n range.moveStart(\"character\", len);\n range.select();\n }\n }\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport fetch from \"@/utils/fetch\";\n\n// Connects to data-controller=\"layout--header\"\nexport default class extends Controller {\n static targets = [\n \"available\",\n \"busy\",\n \"mobileNavigation\",\n \"navigationBar\",\n \"offWork\",\n \"onWork\",\n \"userSwitcher\",\n \"userSwitcherContainer\",\n \"userSwitcherToggle\",\n \"workStatus\",\n ];\n\n static values = {\n togglePath: String,\n };\n\n toggleBusy({ params: { status } }) {\n fetch(this.togglePathValue, {\n method: \"POST\",\n body: JSON.stringify({ status }),\n headers: {\n \"Content-type\": \"application/json\",\n },\n })\n .then(() => {\n this.#toggleStatus(status);\n })\n .catch(() => alert(\"Error setting work status\"))\n ;\n }\n\n toggleUserSwitcher() {\n this.#setUserSwitcherOpen(this.userSwitcherTarget.classList.contains(\"hide\"));\n }\n\n // Bound to click/esc on the window so the switcher can never be left hanging\n // open behind another menu. Clicking the toggle itself is handled by\n // toggleUserSwitcher, and any click inside the panel is a real interaction.\n closeUserSwitcher({ target }) {\n if (this.userSwitcherContainerTarget.contains(target)) {\n return;\n }\n\n this.#setUserSwitcherOpen(false);\n }\n\n // Esc closes even when focus is inside the panel, so it can't use the\n // containment check above.\n closeUserSwitcherOnEscape() {\n this.#setUserSwitcherOpen(false);\n }\n\n #setUserSwitcherOpen(open) {\n this.userSwitcherTarget.classList.toggle(\"hide\", !open);\n this.userSwitcherToggleTarget.setAttribute(\"aria-expanded\", String(open));\n }\n\n // `hidden` rather than `hide`: see the note on the overlay itself in\n // layouts/header/_mobile_navigation.\n toggleNav() {\n this.mobileNavigationTarget.classList.toggle(\"hidden\");\n }\n\n // On a phone the menu bar scrolls sideways, so a tab past the screen edge\n // (Reports, Insights) would be the current page with nothing showing it.\n // Scrolling the bar itself, not scrollIntoView, keeps the page where it is.\n // Measured again once the web fonts land, since they widen every tab.\n navigationBarTargetConnected(bar) {\n this.#revealActiveTab(bar);\n document.fonts?.ready.then(() => this.#revealActiveTab(bar));\n }\n\n #revealActiveTab(bar) {\n const active = bar.querySelector(\"[aria-current=page]\");\n if (!active || bar.scrollWidth <= bar.clientWidth) return;\n\n // Centred rather than pinned to the edge, so the bar reads as a strip with\n // tabs either side instead of one cut off at the border.\n const tab = active.getBoundingClientRect();\n const box = bar.getBoundingClientRect();\n if (tab.right > box.right) {\n bar.scrollLeft += (tab.left + tab.width / 2) - (box.left + box.width / 2);\n }\n }\n\n workStatusTargetConnected(target) {\n const offWork = target.dataset.offWork === \"true\";\n\n this.onWorkTargets.forEach(element => element.classList.toggle(\"hidden\", !offWork));\n this.offWorkTargets.forEach(element => element.classList.toggle(\"hidden\", offWork));\n\n this.#toggleStatus(target.dataset.status);\n }\n\n #toggleStatus(status) {\n const busy = status === \"busy\";\n\n this.availableTargets.forEach(element => element.classList.toggle(\"hidden\", !busy));\n this.busyTargets.forEach(element => element.classList.toggle(\"hidden\", busy));\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport fetch from \"@/utils/fetch\";\nimport { capturePosthogEvent } from \"@/utils/posthog_capture\";\n\nconst SCOPES = [\"all\", \"upsheets\", \"contacts\", \"vehicles\", \"messages\"];\nconst SELECTED = [\"bg-surface-muted\", \"shadow-[inset_3px_0_0_#00C807]\"];\n// Every keystroke that survives the debounce costs four Elasticsearch queries,\n// so wait for a pause, and for at least two characters (an empty field still\n// loads the recent searches).\nexport const DEBOUNCE_MS = 300;\nexport const MIN_QUERY_LENGTH = 2;\n\n// Connects to data-controller=\"layout--omnibox\"\n//\n// The \"/\" and \u2318F omnibox. Results come back as an HTML fragment from\n// /search/omnibox; this controller opens the dialog, debounces the request (and waits for two characters),\n// keeps the scope / mine / exact knobs, shows the busy and error states and\n// moves the keyboard highlight. Rows carry their link inside, so \u21B5 and a click\n// are the same thing. The markup is an APG combobox: the input announces the\n// selected row through aria-activedescendant, a status region reads the counts.\n//\n// PostHog: search_opened, search_performed (once the query settles, 1 s after\n// its results land) and search_result_clicked. The query text itself is never\n// sent \u2014 it is mostly customer names and phone numbers \u2014 only its shape.\nexport default class extends Controller {\n static targets = [\"dialog\", \"input\", \"results\", \"row\", \"all\", \"status\", \"loading\"];\n\n static values = {\n url: String,\n searchUrl: String,\n userId: Number,\n findShortcut: Boolean,\n };\n\n connect() {\n this.#reset();\n }\n\n // \"/\" opens the omnibox from anywhere outside a field. \u2318F / Ctrl+F opens it\n // too only when the account opted in (accounts.ctrl_f_opens_search, off by\n // default); otherwise it stays the browser's find-in-page. It never steals a\n // keystroke from a field the user is typing in, and with the omnibox already\n // open a second \u2318F falls through to the browser's own find-in-page.\n shortcut(event) {\n if (this.dialogTarget.open || this.#editable(event.target)) {\n return;\n }\n\n const mod = event.metaKey || event.ctrlKey;\n const slash = event.key === \"/\" && !mod && !event.altKey;\n const find = this.findShortcutValue && mod && !event.altKey && !event.shiftKey && event.key.toLowerCase() === \"f\";\n if (!slash && !find) {\n return;\n }\n\n event.preventDefault();\n this.open(slash ? \"slash\" : \"find\");\n }\n\n // `trigger` is a string from #shortcut, or the click event from the header.\n open(trigger) {\n // /search already is the expanded omnibox: focus its own field instead of\n // stacking a second result list on top of the first.\n const pageQuery = document.getElementById(\"search-page-query\");\n if (pageQuery) {\n pageQuery.focus();\n pageQuery.select();\n return;\n }\n\n this.#reset();\n capturePosthogEvent(\"search_opened\", { trigger: typeof trigger === \"string\" ? trigger : \"click\" });\n\n if (!this.dialogTarget.open) {\n this.dialogTarget.showModal();\n }\n\n this.inputTarget.focus();\n this.inputTarget.select();\n this.#load();\n }\n\n close() {\n this.dialogTarget.close();\n }\n\n // A click on the backdrop lands on the itself, not on its content.\n closeOnBackdrop(event) {\n if (event.target === this.dialogTarget) {\n this.close();\n }\n }\n\n search() {\n clearTimeout(this.timer);\n if (this.#query().length === 1) {\n // One character matches too much to be useful: stop what is in flight and\n // wait for the next keystroke, leaving the results on screen.\n this.request?.abort();\n return;\n }\n this.timer = setTimeout(() => this.#load(), DEBOUNCE_MS);\n }\n\n setScope(event) {\n this.scopeName = event.currentTarget.dataset.scope;\n this.#load();\n this.inputTarget.focus();\n }\n\n showAll() {\n this.scopeName = \"all\";\n this.#load();\n this.inputTarget.focus();\n }\n\n toggleMine(event) {\n this.mineOnly = event.currentTarget.checked;\n this.#load();\n this.inputTarget.focus();\n }\n\n // Sticks until the field is cleared or the omnibox is reopened, so fixing a\n // typo does not silently bring the phone-number rewrite back.\n useExact() {\n this.exactText = true;\n this.#load();\n this.inputTarget.focus();\n }\n\n // Bound to clicks anywhere in the dialog; only a link inside a result row or\n // the \"All results\" link counts as a pick.\n trackClick(event) {\n const link = event.target.closest(\"a\");\n const row = link?.closest(\"[role=option]\");\n if (!link || (!row && link !== this.allTarget)) {\n return;\n }\n\n this.#flushPerformed();\n capturePosthogEvent(\"search_result_clicked\", {\n ...this.#searchProps(),\n type: row ? row.id.replace(/^omnibox-row-/, \"\").replace(/-\\d+$/, \"\") : \"see_all\",\n position: row ? this.rowTargets.indexOf(row) : null,\n });\n }\n\n retry() {\n this.#load();\n }\n\n hoverRow(event) {\n this.#highlight(this.rowTargets.indexOf(event.currentTarget));\n }\n\n navigate(event) {\n switch (event.key) {\n case \"ArrowDown\":\n event.preventDefault();\n this.#highlight(this.index + 1);\n break;\n case \"ArrowUp\":\n event.preventDefault();\n this.#highlight(this.index - 1);\n break;\n case \"ArrowLeft\":\n case \"ArrowRight\": {\n if (!event.altKey) {\n return;\n }\n event.preventDefault();\n const step = event.key === \"ArrowRight\" ? 1 : -1;\n this.scopeName = SCOPES[(SCOPES.indexOf(this.scopeName) + step + SCOPES.length) % SCOPES.length];\n this.#load();\n break;\n }\n case \"Enter\": {\n event.preventDefault();\n const row = this.rowTargets[this.index];\n const target = row ? (row.querySelector(\"a\") ?? row) : (this.#query() ? this.allTarget : null);\n target?.click();\n break;\n }\n }\n }\n\n #reset() {\n this.scopeName = \"all\";\n this.mineOnly = false;\n this.exactText = false;\n this.retried = false;\n }\n\n #editable(element) {\n return element instanceof HTMLElement &&\n (element.isContentEditable || [\"INPUT\", \"TEXTAREA\", \"SELECT\"].includes(element.tagName));\n }\n\n #query() {\n return this.inputTarget.value.trim();\n }\n\n #params(q) {\n const params = new URLSearchParams({ q, scope: this.scopeName });\n if (this.mineOnly) params.set(\"mine\", \"1\");\n if (this.exactText) params.set(\"exact\", \"1\");\n return params;\n }\n\n async #load() {\n const q = this.#query();\n if (q === \"\") {\n this.exactText = false;\n }\n\n this.request?.abort();\n this.request = new AbortController();\n const pending = setTimeout(() => this.#busy(true), 120);\n\n try {\n const response = await fetch(`${this.urlValue}?${this.#params(q)}`, { signal: this.request.signal });\n this.resultsTarget.innerHTML = await response.text();\n this.retried = false;\n if (q !== \"\") this.#queuePerformed();\n } catch (error) {\n if (error.name === \"AbortError\") {\n return;\n }\n // One quiet retry for a dropped connection; then say so, keeping the\n // previous results and the tabs on screen.\n if (!this.retried) {\n this.retried = true;\n setTimeout(() => this.#load(), 1000);\n return;\n }\n this.#showError();\n } finally {\n clearTimeout(pending);\n this.#busy(false);\n }\n\n this.#updateAllLink(q);\n this.#announce();\n this.#highlight(0);\n }\n\n #searchProps() {\n const q = this.#query();\n return {\n scope: this.scopeName,\n mine: this.mineOnly,\n exact: this.exactText,\n query_shape: queryShape(q),\n query_length: q.length,\n word_count: q.split(/\\s+/).filter(Boolean).length,\n };\n }\n\n #queuePerformed() {\n const total = Number(this.resultsTarget.querySelector(\"[data-omnibox-total]\")?.dataset.omniboxTotal ?? 0);\n clearTimeout(this.performedTimer);\n this.performed = { ...this.#searchProps(), result_count: total, zero_results: total === 0 };\n this.performedTimer = setTimeout(() => this.#flushPerformed(), 1000);\n }\n\n #flushPerformed() {\n clearTimeout(this.performedTimer);\n if (this.performed) capturePosthogEvent(\"search_performed\", this.performed);\n this.performed = null;\n }\n\n #busy(on) {\n this.loadingTarget.hidden = !on;\n this.resultsTarget.setAttribute(\"aria-busy\", String(on));\n this.resultsTarget.classList.toggle(\"opacity-60\", on);\n }\n\n #showError() {\n this.resultsTarget.querySelector(\"[data-omnibox-error]\")?.remove();\n this.resultsTarget.insertAdjacentHTML(\"afterbegin\", `\n
\n Search didn't answer. Check the connection and try again.\n \n
`);\n this.statusTarget.textContent = \"Search didn't answer. Try again.\";\n }\n\n #updateAllLink(q) {\n const params = new URLSearchParams({ q });\n if (this.scopeName !== \"all\") params.append(\"types[]\", this.scopeName);\n if (this.mineOnly) params.set(\"user_id\", String(this.userIdValue));\n if (this.exactText) params.set(\"exact\", \"1\");\n const total = this.resultsTarget.querySelector(\"[data-omnibox-total]\")?.dataset.omniboxTotal;\n\n this.allTarget.href = `${this.searchUrlValue}?${params}`;\n this.allTarget.textContent = total && total !== \"0\" ? `All ${total} results \u2192` : \"All results \u2192\";\n this.allTarget.classList.toggle(\"invisible\", q === \"\");\n }\n\n #announce() {\n const summary = this.resultsTarget.querySelector(\"[data-omnibox-summary]\")?.dataset.omniboxSummary;\n this.statusTarget.textContent = summary ?? \"\";\n }\n\n #highlight(i) {\n const rows = this.rowTargets;\n\n if (rows.length === 0) {\n this.index = -1;\n this.inputTarget.removeAttribute(\"aria-activedescendant\");\n return;\n }\n\n this.index = (i + rows.length) % rows.length;\n rows.forEach((row, n) => {\n const on = n === this.index;\n SELECTED.forEach((c) => row.classList.toggle(c, on));\n row.setAttribute(\"aria-selected\", String(on));\n });\n this.inputTarget.setAttribute(\"aria-activedescendant\", rows[this.index].id);\n rows[this.index].scrollIntoView({ block: \"nearest\" });\n }\n}\n\n// What kind of thing was typed, without the thing itself.\nexport function queryShape(q) {\n if (q.includes(\"@\")) return \"email\";\n if (/^[\\d\\s()+.-]{7,}$/.test(q)) return \"phone\";\n if (/^[A-HJ-NPR-Z0-9]{17}$/i.test(q)) return \"vin\";\n if (/^\\S*\\d\\S*$/.test(q)) return \"number\";\n return q.includes(\" \") ? \"words\" : \"word\";\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Dealer-facing Lead Resurrection settings (story 16220).\n//\n// Owns the client half of the go-live ceremony: unchecking the verify-mode\n// switch (or clicking \"Go live\") opens a confirmation modal whose primary\n// button stays disabled until the acknowledgement checkbox is ticked;\n// confirming stamps confirmed_live=1 and submits the form. The server\n// re-checks the transition, so none of this is load-bearing for safety \u2014\n// it is load-bearing for honesty (the modal restates cap, audiences and\n// cooldown from the live form values, not stale copy).\nexport default class extends Controller {\n static targets = [\n \"form\", \"confirmedLive\", \"dryRunField\",\n \"verifyCard\", \"liveCard\", \"verifySwitch\",\n \"modal\", \"ack\", \"confirmButton\",\n \"modalCap\", \"modalAudiences\", \"modalCooldown\", \"modalCooldownRow\",\n \"audience\", \"tradeCheckbox\", \"bandSection\", \"audienceFloorNote\",\n \"templateField\", \"capInput\",\n ];\n\n // --- audiences ---------------------------------------------------------\n\n audienceChanged(event) {\n if (this.checkedAudiences().length === 0) {\n // The model rejects an empty audience list; keep the UI from ever\n // building one. \"Stop everything\" is the master switch's job.\n event.target.checked = true;\n this.audienceFloorNoteTarget.classList.remove(\"hidden\");\n return;\n }\n this.audienceFloorNoteTarget.classList.add(\"hidden\");\n if (this.hasBandSectionTarget && this.hasTradeCheckboxTarget) {\n this.bandSectionTarget.classList.toggle(\"hidden\", !this.tradeCheckboxTarget.checked);\n }\n }\n\n checkedAudiences() {\n return this.audienceTargets.filter((box) => box.checked);\n }\n\n // --- outreach mode ------------------------------------------------------\n\n modeChanged(event) {\n const templateMode = event.target.value === \"template\" && event.target.checked;\n this.templateFieldTarget.classList.toggle(\"hidden\", !templateMode);\n }\n\n // --- verify / live ------------------------------------------------------\n\n verifySwitchChanged(event) {\n if (!event.target.checked) {\n // Unchecking verify mode is a go-live attempt \u2014 put the switch back\n // until the modal is confirmed.\n event.target.checked = true;\n this.attemptGoLive();\n }\n }\n\n attemptGoLive() {\n this.fillModal();\n this.ackTarget.checked = false;\n this.confirmButtonTarget.disabled = true;\n this.modalTarget.classList.remove(\"hidden\");\n }\n\n cancelModal() {\n this.modalTarget.classList.add(\"hidden\");\n if (this.hasVerifySwitchTarget) this.verifySwitchTarget.checked = true;\n }\n\n ackChanged() {\n this.confirmButtonTarget.disabled = !this.ackTarget.checked;\n }\n\n confirmLive() {\n this.dryRunFieldTarget.value = \"0\";\n this.confirmedLiveTarget.value = \"1\";\n this.formTarget.requestSubmit();\n }\n\n backToVerify() {\n this.dryRunFieldTarget.value = \"1\";\n this.confirmedLiveTarget.value = \"0\";\n this.formTarget.requestSubmit();\n }\n\n // --- modal copy ---------------------------------------------------------\n\n AUDIENCE_LABELS = {\n lost_recoverable: \"Lost recoverable\",\n active_cold: \"Active cold\",\n active_warm: \"Active warm\",\n active_hot: \"Active hot\",\n trade_cycle: \"Trade cycle\",\n };\n\n fillModal() {\n const cap = this.hasCapInputTarget && this.capInputTarget.value ? this.capInputTarget.value : \"\u2014\";\n this.modalCapTarget.textContent = cap;\n\n const names = this.checkedAudiences().map((box) => this.AUDIENCE_LABELS[box.value] || box.value);\n const count = names.length;\n this.modalAudiencesTarget.textContent =\n `${count} audience${count === 1 ? \"\" : \"s\"} \u2014 ${names.join(\", \")}`;\n\n const cooldownInput = this.element.querySelector(\"#lead_resurrection_configuration_cooldown_days\");\n const cooldown = cooldownInput && cooldownInput.value;\n this.modalCooldownRowTarget.classList.toggle(\"hidden\", !cooldown);\n if (cooldown) this.modalCooldownTarget.textContent = cooldown;\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"mainline-assignment\"\n//\n// A device belongs to a team member or carries a label, never both. Only the\n// chosen panel shows, and the other's input is disabled so it never submits.\nexport default class extends Controller {\n static targets = [\"panel\"];\n\n switch(event) {\n this.panelTargets.forEach((panel) => {\n const chosen = panel.dataset.mode === event.target.value;\n panel.hidden = !chosen;\n panel.querySelectorAll(\"input, select\").forEach((input) => { input.disabled = !chosen; });\n });\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"mainline-call-group\"\n//\n// Checked members sit on top in ring order and post in that order. Only the\n// strategy's own ring time is enabled, so the other one never submits.\nexport default class extends Controller {\n static targets = [\"help\", \"ringPanel\", \"hopPanel\", \"panel\", \"order\", \"total\"];\n static values = { pause: Number, limit: Number };\n\n connect() {\n this.update();\n }\n\n update() {\n const strategy = this.element.querySelector(\"input[name='strategy']:checked\")?.value;\n const sequential = strategy !== \"simultaneous\";\n this.helpTargets.forEach((help) => { help.hidden = help.dataset.strategy !== strategy; });\n this.#show(this.ringPanelTarget, !sequential);\n this.#show(this.hopPanelTarget, sequential);\n\n const rows = this.#rows();\n const members = rows.filter((row) => this.#checked(row));\n rows.forEach((row) => {\n const position = members.indexOf(row);\n row.querySelector(\"[data-order]\").hidden = !sequential || position < 0;\n row.querySelector(\"[data-move='up']\").disabled = position <= 0;\n row.querySelector(\"[data-move='down']\").disabled = position < 0 || position === members.length - 1;\n });\n\n const names = members.map((row) => row.querySelector(\"[data-member-name]\").textContent.trim());\n this.orderTarget.textContent = `Ring order: ${names.join(\" \u2192 \")}`;\n this.orderTarget.hidden = !sequential || names.length < 2;\n this.#total(members.length);\n }\n\n toggle(event) {\n const row = event.target.closest(\"li\");\n const others = this.#rows().filter((other) => other !== row);\n if (event.target.checked) {\n const last = others.filter((other) => this.#checked(other)).at(-1);\n last ? last.after(row) : row.parentElement.prepend(row);\n } else {\n const next = others.find((other) => !this.#checked(other) && other.dataset.name > row.dataset.name);\n next ? next.before(row) : row.parentElement.append(row);\n }\n this.update();\n }\n\n up(event) {\n const row = event.currentTarget.closest(\"li\");\n row.previousElementSibling?.before(row);\n this.update();\n event.currentTarget.focus();\n }\n\n down(event) {\n const row = event.currentTarget.closest(\"li\");\n row.nextElementSibling?.after(row);\n this.update();\n event.currentTarget.focus();\n }\n\n box(event) {\n this.panelTargets.forEach((panel) => this.#show(panel, panel.dataset.boxId === event.target.value));\n this.update();\n }\n\n #rows() {\n const panel = this.panelTargets.find((target) => !target.hidden);\n return panel ? Array.from(panel.querySelectorAll(\"li\")) : [];\n }\n\n #checked(row) {\n return row.querySelector(\"input[type='checkbox']\").checked;\n }\n\n #show(panel, shown) {\n panel.hidden = !shown;\n panel.querySelectorAll(\"input, select\").forEach((input) => { input.disabled = !shown; });\n }\n\n // A phone system rests a moment between members and caps the whole call.\n #total(count) {\n const seconds = Number(this.hopPanelTarget.querySelector(\"input\").value);\n if (count === 0 || !seconds) {\n this.totalTarget.textContent = \"\";\n return;\n }\n\n const total = count * (seconds + this.pauseValue);\n const over = this.limitValue > 0 && total > this.limitValue;\n const limit = this.limitValue > 0 ? ` The phone system allows ${this.limitValue}.` : \"\";\n this.totalTarget.textContent = `${count} ${count === 1 ? \"member rings\" : \"members ring\"} for up to ${total} seconds in all.${limit}`;\n this.totalTarget.classList.toggle(\"text-red-700\", over);\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"mainline-hold-music-preview\"\n//\n// Plays one track at a time from the clicked button's data-url; clicking the\n// playing one stops it.\nexport default class extends Controller {\n disconnect() {\n this.stop();\n }\n\n toggle(event) {\n const button = event.currentTarget;\n const wasPlaying = this.button === button;\n this.stop();\n if (wasPlaying) return;\n\n const audio = new Audio(button.dataset.url);\n audio.addEventListener(\"ended\", () => {\n if (this.audio === audio) this.stop();\n });\n this.audio = audio;\n this.button = button;\n this.show(button, true);\n audio.play().catch(() => {\n if (this.audio === audio) this.stop();\n });\n }\n\n stop() {\n this.audio?.pause();\n if (this.button) this.show(this.button, false);\n this.audio = null;\n this.button = null;\n }\n\n show(button, playing) {\n button.querySelector(\"i\").className = playing ? \"ri-stop-fill\" : \"ri-play-fill\";\n button.setAttribute(\"aria-pressed\", playing);\n }\n}\n", "// Physical line keys around each model's screen, by mainline phone profile.\n// Keys number down the left column, then down the right.\n//\n// A Yealink with more keys set than it has buttons turns its bottom-right\n// button into a page switch key. A Grandstream pages with a softkey, so every\n// button holds a key on every page.\nexport const LAYOUTS = {\n \"yealink-27-keys\": [{ models: \"T54W, T46U, T46S\", left: 5, right: 5, pageKey: true }],\n \"yealink-21-keys\": [{ models: \"T53W, T53, T43U\", left: 4, right: 4, pageKey: true }],\n \"yealink-15-keys\": [{ models: \"T42U\", left: 3, right: 3, pageKey: true }],\n \"yealink-12-keys\": [{ models: \"T33G\", left: 0, right: 4, pageKey: true }],\n \"yealink-2-keys\": [{ models: \"T31G, T31P, T31\", left: 0, right: 2, pageKey: false }],\n \"grandstream-grp-56-keys\": [{ models: \"GRP2650\", left: 7, right: 7, pageKey: false }],\n \"grandstream-grp-48-keys\": [{ models: \"GRP2636\", left: 6, right: 6, pageKey: false }],\n \"grandstream-grp-40-keys\": [{ models: \"GRP2615\", left: 5, right: 5, pageKey: false }],\n \"grandstream-grp-32-keys\": [{ models: \"GRP2624, GRP2634\", left: 4, right: 4, pageKey: false }],\n \"grandstream-grp-24-keys\": [\n { models: \"GRP2613\", left: 3, right: 3, pageKey: false },\n { models: \"GRP2616\", left: 6, right: 0, pageKey: false },\n ],\n \"grandstream-grp-16-keys\": [\n { models: \"GRP2612\", left: 2, right: 2, pageKey: false },\n { models: \"GRP2614\", left: 4, right: 0, pageKey: false },\n ],\n \"grandstream-grp-12-keys\": [{ models: \"GRP2611G, GRP2604, GRP2603\", left: 3, right: 0, pageKey: false }],\n \"grandstream-grp-8-keys\": [{ models: \"GRP2610, GRP2602\", left: 2, right: 0, pageKey: false }],\n};\n\nfunction buttons(layout) {\n return layout.left + layout.right;\n}\n\nfunction paged(layout, count) {\n return layout.pageKey && count > buttons(layout);\n}\n\nexport function keysPerPage(layout, count) {\n return paged(layout, count) ? buttons(layout) - 1 : buttons(layout);\n}\n\nexport function pageCount(layout, count) {\n return Math.max(1, Math.ceil(count / keysPerPage(layout, count)));\n}\n\nexport function pageOf(layout, count, key) {\n return Math.floor((key - 1) / keysPerPage(layout, count));\n}\n\n// Every button on one page: the key it holds (null when unused) or the page switch key.\nexport function pageSlots(layout, count, page) {\n const perPage = keysPerPage(layout, count);\n\n return Array.from({ length: buttons(layout) }, (_, slot) => {\n const column = slot < layout.left ? \"left\" : \"right\";\n const row = column === \"left\" ? slot : slot - layout.left;\n\n if (slot >= perPage) {\n return { column, row, key: null, pageKey: true };\n }\n\n return { column, row, key: page * perPage + slot + 1, pageKey: false };\n });\n}\n", "import { Controller } from \"@hotwired/stimulus\";\nimport { LAYOUTS, pageCount, pageOf, pageSlots } from \"@/mainline/phone_layouts\";\n\nconst WIDTH = 340;\nconst SIDE = 48;\nconst ROW = 30;\nconst STATUS = 24;\nconst POINTED = \"bg-(--ar-green-50)\";\n\nfunction escape(text) {\n return text.replace(/[&<>\"]/g, (character) => ({ \"&\": \"&\", \"<\": \"<\", \">\": \">\", \"\\\"\": \""\" })[character]);\n}\n\nfunction clip(text, length) {\n return text.length > length ? `${text.slice(0, length - 1)}\u2026` : text;\n}\n\n// Connects to data-controller=\"mainline-provisioning\"\n//\n// A supported model takes a MAC, a serial and as many colleague keys as it has\n// room for. Hidden fields are disabled so they never submit.\nexport default class extends Controller {\n static targets = [\"profile\", \"device\", \"keys\", \"list\", \"template\", \"add\", \"phone\"];\n static values = { other: String };\n\n #variant = 0;\n #page = 0;\n #pointed = null;\n\n connect() {\n this.draw();\n }\n\n switch() {\n const supported = this.profileTarget.value !== this.otherValue;\n this.#show(this.deviceTarget, supported);\n this.#show(this.keysTarget, this.#room() > 0);\n this.#variant = 0;\n this.#page = 0;\n this.#refresh();\n }\n\n add() {\n this.listTarget.append(this.templateTarget.content.cloneNode(true));\n this.#refresh();\n }\n\n remove(event) {\n event.target.closest(\"li\").remove();\n this.#pointed = null;\n this.#refresh();\n }\n\n // Keeps the caret after the same hex digit it followed.\n formatMac(event) {\n const input = event.target;\n const digitsBeforeCaret = input.value.slice(0, input.selectionStart).replace(/[^0-9a-f]/gi, \"\").length;\n const digits = input.value.replace(/[^0-9a-f]/gi, \"\").toUpperCase().slice(0, 12);\n input.value = digits.match(/.{1,2}/g)?.join(\":\") || \"\";\n\n const caret = Math.min(digitsBeforeCaret, digits.length);\n const position = caret + Math.floor(Math.max(caret - 1, 0) / 2);\n input.setSelectionRange(position, position);\n }\n\n showVariant({ params: { index } }) {\n this.#variant = index;\n this.#page = 0;\n this.draw();\n }\n\n showPage({ params: { index } }) {\n this.#page = index;\n this.#pointed = null;\n this.draw();\n }\n\n pointRow(event) {\n const row = event.target.closest(\"li\");\n this.#point(row ? this.#rows().indexOf(row) + 2 : null);\n }\n\n pointKey(event) {\n const key = Number(event.target.closest(\"[data-key]\")?.dataset.key);\n this.#point(key > 1 ? key : null);\n }\n\n unpoint() {\n this.#point(null);\n }\n\n draw() {\n const layouts = LAYOUTS[this.profileTarget.value];\n const layout = layouts?.[this.#variant];\n this.phoneTarget.hidden = !layout;\n if (!layout) {\n return;\n }\n\n const count = this.#rows().length + 1;\n const pages = pageCount(layout, count);\n if (this.#pointed) {\n this.#page = pageOf(layout, count, this.#pointed);\n }\n this.#page = Math.min(this.#page, pages - 1);\n\n this.phoneTarget.innerHTML = [\n layouts.length > 1 ? this.#buttons(layouts.map((each) => each.models), this.#variant, \"showVariant\", \"Model\") : \"\",\n this.#svg(layout, count, pages),\n pages > 1 ? this.#buttons(Array.from({ length: pages }, (_, page) => `Page ${page + 1}`), this.#page, \"showPage\", \"Page\") : \"\",\n `

${escape(layout.models)}

`,\n ].join(\"\");\n\n this.#rows().forEach((row, index) => row.classList.toggle(POINTED, index + 2 === this.#pointed));\n }\n\n #point(key) {\n if (key === this.#pointed) {\n return;\n }\n\n this.#pointed = key;\n this.draw();\n }\n\n #rows() {\n return Array.from(this.listTarget.children);\n }\n\n #room() {\n return Number(this.profileTarget.selectedOptions[0]?.dataset.colleagueKeys || 0);\n }\n\n #show(panel, shown) {\n panel.hidden = !shown;\n panel.querySelectorAll(\"input, select\").forEach((input) => { input.disabled = !shown; });\n }\n\n // Key 1 is the phone's own line.\n #refresh() {\n const rows = this.#rows();\n rows.forEach((row, index) => { row.querySelector(\"[data-key]\").textContent = `Key ${index + 2}`; });\n this.addTarget.hidden = rows.length >= this.#room();\n this.draw();\n }\n\n #label(key) {\n if (key === 1) {\n return \"This phone\";\n }\n\n const option = this.#rows()[key - 2]?.querySelector(\"select\")?.selectedOptions[0];\n return option?.value ? option.text.split(\" \u00B7 \")[0] : null;\n }\n\n #buttons(labels, current, action, name) {\n const buttons = labels.map((label, index) => `\n `);\n return `
${buttons.join(\"\")}
`;\n }\n\n #svg(layout, count, pages) {\n const room = this.#room() + 1;\n const rows = Math.max(layout.left, layout.right);\n const twoColumns = layout.left > 0 && layout.right > 0;\n const screenLeft = layout.left ? SIDE : 14;\n const screenRight = WIDTH - (layout.right ? SIDE : 14);\n const screenWidth = screenRight - screenLeft;\n const screenHeight = STATUS + rows * ROW + 8;\n const height = screenHeight + 32;\n const length = twoColumns ? 15 : 30;\n\n const slots = pageSlots(layout, count, this.#page).map((slot) => {\n const y = 16 + STATUS + slot.row * ROW;\n const left = slot.column === \"left\";\n const buttonX = left ? 12 : WIDTH - 38;\n const key = slot.key <= room ? slot.key : null;\n const label = slot.pageKey ? \"Next page \u203A\" : key && this.#label(key);\n const used = slot.pageKey || (key && key <= count);\n const pointed = key && key === this.#pointed;\n const textX = left ? screenLeft + 10 : screenRight - 10;\n const highlightX = left || !twoColumns ? screenLeft + 2 : WIDTH / 2;\n const highlightWidth = twoColumns ? screenWidth / 2 - 2 : screenWidth - 4;\n const labelStyle = `font: ${pointed || key === 1 ? 600 : 400} 12px var(--ar-font-sans); fill: ${slot.pageKey ? \"var(--ar-fg-muted)\" : \"var(--ar-fg-strong)\"}`;\n\n return `\n \n ${pointed ? `` : \"\"}\n \n ${slot.pageKey ? `\u203A` : \"\"}\n ${key ? `${key}` : \"\"}\n ${used && !slot.pageKey ? `` : \"\"}\n ${label ? `${escape(clip(label, length))}` : \"\"}\n `;\n });\n\n return `\n mainline-provisioning#pointKey mouseleave->mainline-provisioning#unpoint\">\n \n \n ${pages > 1 ? `Page ${this.#page + 1} of ${pages}` : \"\"}\n ${slots.join(\"\")}\n `;\n }\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\n// Connects to data-controller=\"mainline-recording-playback\"\n//\n// Renders the