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4B,MAACg5B,GAAQ,MAAK,IAAK,GAAE,GACxD,SAAAH,EAAA,KAACQ,GAAoB,QAAQJ,GAC3B,UAAAj5B,EAAA,IAAC58E,GAAY,UACZo0G,GAAI,KACP,EACF,EACF,CACF,EACF","names":["m","require$$0","createRoot","formatProdErrorMessage","code","$$observable","symbol_observable_default","randomString","ActionTypes","actionTypes_default","isPlainObject","obj","proto","createStore","reducer","preloadedState","enhancer","currentReducer","currentState","currentListeners","nextListeners","listenerIdCounter","isDispatching","ensureCanMutateNextListeners","listener","key","getState","subscribe","isSubscribed","listenerId","dispatch","action","replaceReducer","nextReducer","observable","outerSubscribe","observer","observeState","observerAsObserver","assertReducerShape","reducers","combineReducers","reducerKeys","finalReducers","finalReducerKeys","shapeAssertionError","e","state","hasChanged","nextState","i","previousStateForKey","nextStateForKey","compose","funcs","arg","a","b","args","applyMiddleware","middlewares","createStore2","store","middlewareAPI","chain","middleware","isAction","NOTHING","DRAFTABLE","DRAFT_STATE","die","error","getPrototypeOf","isDraft","value","isDraftable","_a","isMap","isSet","objectCtorString","Ctor","each","iter","getArchtype","entry","index","thing","has","prop","set","propOrOldValue","t","is","x","y","target","latest","shallowCopy","base","strict","isPlain","descriptors","keys","desc","freeze","deep","isFrozen","dontMutateFrozenCollections","plugins","getPlugin","pluginKey","plugin","currentScope","getCurrentScope","createScope","parent_","immer_","usePatchesInScope","scope","patchListener","revokeScope","leaveScope","revokeDraft","enterScope","immer2","draft","processResult","result","baseDraft","finalize","maybeFreeze","rootScope","path","childValue","finalizeProperty","resultEach","isSet2","parentState","targetObject","rootPath","targetIsSet","res","createProxyProxy","parent","isArray","traps","objectTraps","arrayTraps","revoke","proxy","source","readPropFromProto","peek","prepareCopy","createProxy","getDescriptorFromProto","current2","markChanged","owner","fn","Immer2","config","recipe","defaultBase","self","base2","hasError","p","ip","patches","inversePatches","current","patch","applyPatchesImpl","currentImpl","copy","immer","produce","assertIsFunction","func","errorMessage","assertIsObject","object","assertIsArrayOfFunctions","array","item","itemTypes","ensureIsArray","getDependencies","createSelectorArgs","dependencies","collectInputSelectorResults","inputSelectorArgs","inputSelectorResults","length","StrongRef","Ref","UNTERMINATED","TERMINATED","createCacheNode","weakMapMemoize","options","fnNode","resultEqualityCheck","lastResult","resultsCount","memoized","cacheNode","l","objectCache","objectNode","primitiveCache","primitiveNode","terminatedNode","lastResultValue","createSelectorCreator","memoizeOrOptions","memoizeOptionsFromArgs","createSelectorCreatorOptions","createSelector2","recomputations","dependencyRecomputations","directlyPassedOptions","resultFunc","combinedOptions","memoize","memoizeOptions","argsMemoize","argsMemoizeOptions","devModeChecks","finalMemoizeOptions","finalArgsMemoizeOptions","memoizedResultFunc","selector","createSelector","createStructuredSelector","inputSelectorsObject","selectorCreator","inputSelectorKeys","composition","createThunkMiddleware","extraArgument","next","thunk","withExtraArgument","createDraftSafeSelectorCreator","createDraftSafeSelector2","args2","wrappedSelector","rest","composeWithDevTools","createAction","type","prepareAction","actionCreator","prepared","Tuple","_Tuple","items","arr","freezeDraftable","val","createNextState","emplace","map","handler","inserted","isBoolean","buildGetDefaultMiddleware","immutableCheck","serializableCheck","actionCreatorCheck","middlewareArray","thunkMiddleware","SHOULD_AUTOBATCH","createQueueWithTimer","timeout","notify","rAF","autoBatchEnhancer","notifying","shouldNotifyAtEndOfTick","notificationQueued","listeners","queueCallback","notifyListeners","listener2","wrappedListener","unsubscribe","buildGetDefaultEnhancers","middlewareEnhancer","autoBatch","enhancerArray","IS_PRODUCTION","configureStore","getDefaultMiddleware","devTools","enhancers","rootReducer","isPlainObject2","finalMiddleware","finalCompose","compose2","getDefaultEnhancers","storeEnhancers","composedEnhancer","executeReducerBuilderCallback","builderCallback","actionsMap","actionMatchers","defaultCaseReducer","builder","typeOrActionCreator","matcher","isStateFunction","createReducer","initialState","mapOrBuilderCallback","finalActionMatchers","finalDefaultCaseReducer","getInitialState","frozenInitialState","caseReducers","reducer2","cr","previousState","caseReducer","isDraft2","isDraftable2","createNextState2","urlAlphabet","nanoid","size","id","asyncThunkSymbol","getType","slice","actionKey","buildCreateSlice","creators","cAT","name","reducerPath","buildReducerCreators","reducerNames","context","contextMethods","name2","reducerName","reducerDefinition","reducerDetails","isAsyncThunkSliceReducerDefinition","handleThunkCaseReducerDefinition","handleNormalReducerDefinition","buildReducer","extraReducers","finalCaseReducers","sM","selectSelf","injectedSelectorCache","_reducer","makeSelectorProps","reducerPath2","injected","selectSlice","sliceState","getSelectors","selectState","selectorCache","wrapSelector","injectable","pathOpt","newReducerPath","wrapper","rootState","createSlice","asyncThunk","payloadCreator","prepare","createNotation","maybeReducerWithPrepare","prepareCallback","isCaseReducerWithPrepareDefinition","fulfilled","pending","rejected","settled","noop","assertFunction","expected","alm","getListenerEntryPropsFrom","predicate","effect","createListenerEntry","addListener","removeListener","getUser","user","cookiePrefix","initialUser","initialAuthToken","isLoggedIn","authSlice","userData","handleLogin","handleLogout","auth","transactionFiltersSlice","filter","tempFilter","filters","transactionFilters","g","n","q","r","u","v","useSyncExternalStoreWithSelector_production_min","h","c","f","d","k","withSelectorModule","React","ReactOriginal","ReactOriginal[\"default\"]","ContextKey","gT","getContext","contextMap","realContext","ReactReduxContext","notInitialized","createReduxContextHook","useReduxContext","useSyncExternalStoreWithSelector","initializeUseSelector","refEquality","createSelectorHook","useReduxContext2","useSelector2","equalityFnOrOptions","equalityFn","subscription","getServerState","stabilityCheck","identityFunctionCheck","selectedState","useSelector","defaultNoopBatch","callback","createListenerCollection","first","last","nullListeners","createSubscription","parentSub","subscriptionsAmount","selfSubscribed","addNestedSub","trySubscribe","cleanupListener","removed","tryUnsubscribe","notifyNestedSubs","handleChangeWrapper","trySubscribeSelf","tryUnsubscribeSelf","canUseDOM","isReactNative","useIsomorphicLayoutEffect","Provider","children","serverState","contextValue","Context","Provider_default","createStoreHook","useStore2","useStore","createDispatchHook","useDispatch2","useDispatch","useSyncExternalStoreWithSelector2","ScrollToTop","pathname","useLocation","useLayoutEffect","DEBUG_BUILD","SDK_VERSION","GLOBAL_OBJ","getGlobalSingleton","creator","gbl","__SENTRY__","versionedCarrier","PREFIX","CONSOLE_LEVELS","originalConsoleMethods","consoleSandbox","console","wrappedFuncs","wrappedLevels","level","originalConsoleMethod","makeLogger","enabled","logger","STACKTRACE_FRAME_LIMIT","UNKNOWN_FUNCTION","WEBPACK_ERROR_REGEXP","STRIP_FRAME_REGEXP","createStackParser","parsers","sortedParsers","stack","skipFirstLines","framesToPop","frames","lines","line","cleanedLine","parser","frame","stripSentryFramesAndReverse","stackParserFromStackParserOptions","stackParser","localStack","getLastStackFrame","defaultFunctionName","getFunctionName","getFramesFromEvent","event","exception","handlers","instrumented","addHandler","maybeInstrument","instrumentFn","triggerHandlers","data","typeHandlers","_oldOnErrorHandler","addGlobalErrorInstrumentationHandler","instrumentError","msg","url","column","_oldOnUnhandledRejectionHandler","addGlobalUnhandledRejectionInstrumentationHandler","instrumentUnhandledRejection","getMainCarrier","getSentryCarrier","carrier","objectToString","isError","wat","isInstanceOf","isBuiltin","className","isErrorEvent","isDOMError","isDOMException","isString","isParameterizedString","isPrimitive","isEvent","isElement","isRegExp","isThenable","isSyntheticEvent","isVueViewModel","WINDOW","DEFAULT_MAX_STRING_LENGTH","htmlTreeAsString","elem","currentElem","MAX_TRAVERSE_HEIGHT","out","height","len","separator","sepLength","nextStr","keyAttrs","maxStringLength","_htmlElementAsString","el","keyAttrPairs","keyAttr","keyAttrPair","classes","allowedAttrs","attr","getLocationHref","getDomElement","getComponentName","truncate","str","max","safeJoin","input","delimiter","output","isMatchingPattern","pattern","requireExactStringMatch","stringMatchesSomePattern","testString","patterns","fill","replacementFactory","original","wrapped","markFunctionWrapped","addNonEnumerableProperty","getOriginalFunction","convertToPlainObject","getOwnProperties","newObj","serializeEventTarget","extractedProps","property","extractExceptionKeysForMessage","maxLength","firstKey","includedKeys","serialized","dropUndefinedKeys","inputValue","_dropUndefinedKeys","memoizationMap","isPojo","memoVal","returnValue","ONE_SECOND_IN_MS","dateTimestampInSeconds","createUnixTimestampInSecondsFunc","performance","approxStartingTimeOrigin","timeOrigin","timestampInSeconds","browserPerformanceTimeOrigin","threshold","performanceNow","dateNow","timeOriginDelta","timeOriginIsReliable","navigationStart","navigationStartDelta","navigationStartIsReliable","uuid4","crypto","getRandomByte","typedArray","getFirstException","getEventDescription","message","eventId","firstException","addExceptionTypeValue","values","addExceptionMechanism","newMechanism","defaultMechanism","currentMechanism","mergedData","checkOrSetAlreadyCaught","isAlreadyCaptured","States","RESOLVED","REJECTED","resolvedSyncPromise","SyncPromise","resolve","rejectedSyncPromise","reason","_","reject","executor","onfulfilled","onrejected","onfinally","isRejected","cachedHandlers","makeSession","startingTime","session","sessionToJSON","updateSession","duration","closeSession","status","generateTraceId","generateSpanId","merge","initialObj","mergeObj","levels","SCOPE_SPAN_FIELD","_setSpanForScope","span","_getSpanForScope","DEFAULT_MAX_BREADCRUMBS","ScopeClass","newScope","client","lastEventId","requestSession","tags","extras","extra","fingerprint","captureContext","scopeToMerge","scopeInstance","Scope","contexts","propagationContext","breadcrumb","maxBreadcrumbs","maxCrumbs","mergedBreadcrumb","breadcrumbs","attachment","newData","hint","syntheticException","getDefaultCurrentScope","getDefaultIsolationScope","AsyncContextStack","isolationScope","assignedScope","assignedIsolationScope","maybePromiseResult","getAsyncContextStack","registry","sentry","withScope","withSetScope","withIsolationScope","getStackAsyncContextStrategy","_isolationScope","getAsyncContextStrategy","getIsolationScope","getGlobalScope","acs","getClient","getTraceContextFromScope","traceId","spanId","parentSpanId","METRICS_SPAN_FIELD","getMetricSummaryJsonForSpan","storage","exportKey","summary","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON","SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT","SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE","SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME","SEMANTIC_ATTRIBUTE_PROFILE_ID","SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME","SPAN_STATUS_UNSET","SPAN_STATUS_OK","SPAN_STATUS_ERROR","getSpanStatusFromHttpCode","httpStatus","setHttpStatus","spanStatus","SENTRY_BAGGAGE_KEY_PREFIX","SENTRY_BAGGAGE_KEY_PREFIX_REGEX","MAX_BAGGAGE_STRING_LENGTH","baggageHeaderToDynamicSamplingContext","baggageHeader","baggageObject","parseBaggageHeader","dynamicSamplingContext","acc","nonPrefixedKey","dynamicSamplingContextToSentryBaggageHeader","sentryPrefixedDSC","dscKey","dscValue","objectToBaggageHeader","curr","currBaggageObject","baggageHeaderToObject","baggageEntry","keyOrValue","objectKey","objectValue","currentIndex","newBaggageHeader","TRACEPARENT_REGEXP","extractTraceparentData","traceparent","matches","parentSampled","propagationContextFromHeaders","sentryTrace","baggage","traceparentData","virtualSpanId","generateSentryTraceHeader","sampled","sampledString","TRACE_FLAG_NONE","TRACE_FLAG_SAMPLED","hasShownSpanDropWarning","spanToTransactionTraceContext","span_id","trace_id","op","parent_span_id","origin","spanToJSON","spanToTraceContext","isRemote","spanToTraceHeader","spanIsSampled","spanTimeInputToSeconds","ensureTimestampInSeconds","timestamp","spanIsSentrySpan","spanIsOpenTelemetrySdkTraceBaseSpan","attributes","startTime","endTime","getStatusMessage","castSpan","traceFlags","CHILD_SPANS_FIELD","ROOT_SPAN_FIELD","addChildSpanToSpan","childSpan","rootSpan","removeChildSpanFromSpan","getSpanDescendants","resultSet","addSpanChildren","childSpans","getRootSpan","getActiveSpan","showSpanDropWarning","errorsInstrumented","registerSpanErrorInstrumentation","errorCallback","activeSpan","SCOPE_ON_START_SPAN_FIELD","ISOLATION_SCOPE_ON_START_SPAN_FIELD","setCapturedScopesOnSpan","getCapturedScopesOnSpan","hasTracingEnabled","maybeOptions","SentryNonRecordingSpan","spanContext","_timestamp","_key","_value","_values","_status","_name","_attributesOrStartTime","_startTime","_link","_links","_exception","_time","DEFAULT_ENVIRONMENT","FROZEN_DSC_FIELD","freezeDscOnSpan","dsc","getDynamicSamplingContextFromClient","public_key","getDynamicSamplingContextFromScope","getDynamicSamplingContextFromSpan","frozenDsc","traceState","traceStateDsc","dscOnTraceState","jsonSpan","maybeSampleRate","logSpanStart","description","isRootSpan","header","infoParts","logSpanEnd","parseSampleRate","sampleRate","rate","sampleSpan","samplingContext","parsedSampleRate","DSN_REGEX","isValidProtocol","protocol","dsnToString","dsn","withPassword","host","pass","port","projectId","publicKey","dsnFromString","match","lastPath","split","projectMatch","dsnFromComponents","components","validateDsn","component","makeDsn","from","memoBuilder","hasWeakSet","inner","unmemoize","normalize","depth","maxProperties","visit","err","normalizeToSize","maxSize","normalized","jsonSize","memo","stringified","stringifyValue","remainingDepth","valueWithToJSON","jsonValue","numAdded","visitable","visitKey","visitValue","objName","getConstructorName","prototype","utf8Length","createEnvelope","headers","addItemToEnvelope","envelope","newItem","forEachEnvelopeItem","envelopeItems","envelopeItem","envelopeItemType","encodeUTF8","serializeEnvelope","envHeaders","parts","append","itemHeaders","payload","stringifiedPayload","concatBuffers","buffers","totalLength","buf","merged","offset","buffer","createSpanEnvelopeItem","spanJson","createAttachmentEnvelopeItem","ITEM_TYPE_TO_DATA_CATEGORY_MAP","envelopeItemTypeToDataCategory","getSdkMetadataForEnvelopeHeader","metadataOrEvent","version","createEventEnvelopeHeaders","sdkInfo","tunnel","enhanceEventWithSdkInfo","createSessionEnvelope","metadata","envelopeHeaders","createEventEnvelope","eventType","createSpanEnvelope","spans","dscHasRequiredProps","beforeSendSpan","convertToSpanJSON","setMeasurement","unit","timedEventsToMeasurements","events","measurements","MAX_SPAN_COUNT","SentrySpan","timeInput","endTimestamp","attributesOrStartTime","time","isSpanTimeInput","sendSpanEnvelope","transactionEvent","isFullFinishedSpan","capturedSpanScope","capturedSpanIsolationScope","isStandaloneSpan","transaction","spanItems","SUPPRESS_TRACING_KEY","startInactiveSpan","getAcs","spanArguments","parseSentrySpanArguments","forceTransaction","customParentSpan","withActiveSpan","parentSpan","getParentSpan","createChildOrRootSpan","_startChildSpan","_startRootSpan","initialCtx","ctx","TRACING_DEFAULTS","FINISH_REASON_HEARTBEAT_FAILED","FINISH_REASON_IDLE_TIMEOUT","FINISH_REASON_FINAL_TIMEOUT","FINISH_REASON_EXTERNAL_FINISH","startIdleSpan","startSpanOptions","activities","_finished","_idleTimeoutID","_finishReason","_autoFinishAllowed","_cleanupHooks","idleTimeout","finalTimeout","childSpanTimeout","beforeSpanEnd","previousActiveSpan","_startIdleSpan","thisArg","definedEndTimestamp","spanEndTimestamp","child","onIdleSpanEnded","childEndTimestamps","latestSpanEndTimestamp","spanStartTimestamp","_cancelIdleTimeout","_restartIdleTimeout","_restartChildSpanTimeout","_pushActivity","_popActivity","cleanup","spanJSON","startTimestamp","discardedSpans","childSpanJSON","childEndTimestamp","childStartTimestamp","spanStartedBeforeIdleSpanEnd","timeoutWithMarginOfError","spanEndedBeforeFinalTimeout","stringifiedSpan","startedSpan","endedSpan","spanToAllowAutoFinish","notifyEventProcessors","processors","processor","final","parsedStackResults","lastKeysCount","cachedFilenameDebugIds","getFilenameToDebugIdMap","debugIdMap","debugIdKeys","stackKey","parsedStack","stackFrame","filename","debugId","getDebugImagesForResources","resource_paths","filenameDebugIdMap","images","applyScopeDataToEvent","sdkProcessingMetadata","applyDataToEvent","applySpanToEvent","applyFingerprintToEvent","applyBreadcrumbsToEvent","applySdkMetadataToEvent","mergeScopeData","mergeData","eventProcessors","attachments","transactionName","mergeAndOverwriteScopeData","mergeVal","cleanedExtra","cleanedTags","cleanedUser","cleanedContexts","mergedBreadcrumbs","prepareEvent","normalizeDepth","normalizeMaxBreadth","integrations","applyClientOptions","applyIntegrationsMetadata","applyDebugIds","finalScope","getFinalScope","clientEventProcessors","isolationData","finalScopeData","evt","applyDebugMeta","normalizeEvent","environment","release","dist","maxValueLength","request","debug_id","integrationNames","maxBreadth","captureException","captureEvent","setContext","setUser","isEnabled","addEventProcessor","startSession","userAgent","currentSession","endSession","_sendSessionUpdate","captureSession","end","SENTRY_API_VERSION","getBaseApiEndpoint","_getIngestEndpoint","_encodedAuth","params","getEnvelopeEndpointWithUrlEncodedAuth","installedIntegrations","filterDuplicates","integrationsByName","currentInstance","existingInstance","getIntegrationsToSetup","defaultIntegrations","userIntegrations","integration","resolvedUserIntegrations","finalIntegrations","debugIndex","debugInstance","setupIntegrations","integrationIndex","setupIntegration","afterSetupIntegrations","createClientReportEnvelope","discarded_events","clientReportItem","SentryError","logLevel","ALREADY_SEEN_ERROR","BaseClient","undefinedOption","option","hintWithEventId","eventMessage","promisedEvent","transport","clientFinished","transportFlushed","eventProcessor","integrationName","isAlreadyInstalled","env","promise","sendResponse","category","eventOrCount","count","hook","hooks","cbIndex","callbacks","crashed","errored","exceptions","ex","mechanism","sessionNonTerminal","ticked","tick","interval","finalEvent","sentryError","isTransaction","isTransactionEvent","beforeSendLabel","dataCategory","processBeforeSend","_validateBeforeSendResult","processedEvent","spanCount","spanCountBefore","spanCountAfter","droppedSpanCount","transactionInfo","outcomes","quantity","beforeSendResult","invalidValueError","beforeSend","beforeSendTransaction","processedSpans","processedSpan","initAndBind","clientClass","setCurrentClient","makePromiseBuffer","limit","isReady","remove","task","add","taskProducer","drain","counter","capturedSetTimeout","DEFAULT_RETRY_AFTER","parseRetryAfterHeader","now","headerDelay","headerDate","disabledUntil","limits","isRateLimited","updateRateLimits","statusCode","updatedRateLimits","rateLimitHeader","retryAfterHeader","retryAfter","categories","namespaces","delay","DEFAULT_TRANSPORT_BUFFER_SIZE","createTransport","makeRequest","rateLimits","flush","send","filteredEnvelopeItems","getEventForEnvelopeItem","filteredEnvelope","recordEnvelopeLoss","requestTask","response","isSentryRequestUrl","checkDsn","checkTunnel","removeTrailingSlash","applySdkMetadata","names","getTraceData","scopeToTraceHeader","DEFAULT_BREADCRUMBS","addBreadcrumb","beforeBreadcrumb","finalBreadcrumb","originalFunctionToString","INTEGRATION_NAME","SETUP_CLIENTS","_functionToStringIntegration","originalFunction","functionToStringIntegration","DEFAULT_IGNORE_ERRORS","_inboundFiltersIntegration","_hint","clientOptions","mergedOptions","_mergeOptions","_shouldDropEvent","inboundFiltersIntegration","internalOptions","_isSentryError","_isIgnoredError","_isUselessError","_isIgnoredTransaction","_isDeniedUrl","_getEventFilterUrl","_isAllowedUrl","ignoreErrors","_getPossibleEventMessages","ignoreTransactions","denyUrls","allowUrls","possibleMessages","lastException","_getLastValidUrl","applyAggregateErrorsToEvent","exceptionFromErrorImplementation","maxValueLimit","originalException","truncateAggregateExceptions","aggregateExceptionsFromError","prevExceptions","exceptionId","newExceptions","applyExceptionGroupFieldsForParentException","newException","newExceptionId","applyExceptionGroupFieldsForChildException","childError","parentId","parseUrl","query","fragment","addConsoleInstrumentationHandler","instrumentConsole","log","severityLevelFromString","_dedupeIntegration","previousEvent","currentEvent","dedupeIntegration","_isSameMessageEvent","_isSameExceptionEvent","currentMessage","previousMessage","_isSameFingerprint","_isSameStacktrace","previousException","_getExceptionFromEvent","currentException","currentFrames","previousFrames","frameA","frameB","currentFingerprint","previousFingerprint","instrumentFetchRequest","handlerData","shouldCreateSpan","shouldAttachHeaders","spanOrigin","shouldCreateSpanResult","endSpan","method","fullUrl","getFullURL","hasParent","_addTracingHeadersToFetchRequest","fetchOptionsObj","traceHeaders","isRequest","isHeaders","newHeaders","prevBaggageHeader","prevHeaderStrippedFromSentryBaggage","stripBaggageHeaderOfSentryBaggageValues","headerName","headerValue","existingBaggageHeader","newBaggageHeaders","headerItem","contentLength","contentLengthNum","getBreadcrumbLogLevelFromHttpStatusCode","supportsFetch","isNativeFunction","supportsNativeFetch","doc","sandbox","addFetchInstrumentationHandler","skipNativeFetchCheck","instrumentFetch","addFetchEndInstrumentationHandler","streamHandler","onFetchResolved","originalFetch","virtualError","parseFetchArgs","resolveResponse","onFinishedResolving","body","responseReader","maxFetchDurationTimeout","readingActive","chunkTimeout","done","clonedResponseForResolving","hasProp","getUrlFromResource","resource","fetchArgs","isBrowserBundle","getSDKSource","isNodeEnv","isBrowser","isElectronNodeRenderer","process","supportsHistory","chromeVar","isChromePackagedApp","hasHistoryApi","_nullishCoalesce","lhs","rhsFn","_optionalChain","ops","lastAccessLHS","ignoreOnError","shouldIgnoreOnError","ignoreNextOnError","wrap","isFunction","sentryWrapped","wrappedArguments","exceptionFromError","parseStackFrames","extractType","extractMessage","eventFromPlainObject","isUnhandledRejection","errorFromProp","getErrorPropertyFromObject","getNonErrorObjectExceptionValue","eventFromError","stacktrace","skipLines","getSkipFirstStackStringLines","getPopFirstTopFrames","reactMinifiedRegexp","isWebAssemblyException","eventFromException","attachStacktrace","eventFromUnknownInput","eventFromMessage","eventFromString","domException","__sentry_template_string__","__sentry_template_values__","captureType","getObjectClassName","createUserFeedbackEnvelope","feedback","createUserFeedbackEnvelopeItem","BrowserClient","opts","sdkSource","getRating","thresholds","bindReporter","metric","reportAllChanges","prevValue","delta","forceReport","generateUniqueID","getNavigationEntry","checkResponseStart","navigationEntry","getActivationStart","navEntry","initMetric","navigationType","observe","po","list","onHidden","cb","onHiddenOrPageHide","runOnce","called","firstHiddenTime","initHiddenTime","onVisibilityUpdate","removeChangeListeners","addChangeListeners","getVisibilityWatcher","whenActivated","FCPThresholds","onFCP","onReport","visibilityWatcher","report","entries","CLSThresholds","onCLS","sessionValue","sessionEntries","handleEntries","firstSessionEntry","lastSessionEntry","FIDThresholds","onFID","handleEntry","interactionCountEstimate","minKnownInteractionId","maxKnownInteractionId","updateEstimate","getInteractionCount","initInteractionCountPolyfill","longestInteractionList","longestInteractionMap","DEFAULT_DURATION_THRESHOLD","prevInteractionCount","getInteractionCountForNavigation","estimateP98LongestInteraction","candidateInteractionIndex","MAX_INTERACTIONS_TO_CONSIDER","entryPreProcessingCallbacks","processInteractionEntry","minLongestInteraction","existingInteraction","interaction","whenIdle","rIC","handle","INPThresholds","onINP","inp","LCPThresholds","reportedMetricIDs","onLCP","stopListening","TTFBThresholds","whenReady","onTTFB","_previousCls","_previousFid","_previousLcp","_previousTtfb","_previousInp","addClsInstrumentationHandler","stopOnCallback","addMetricObserver","instrumentCls","addLcpInstrumentationHandler","instrumentLcp","addFidInstrumentationHandler","instrumentFid","addTtfbInstrumentationHandler","instrumentTtfb","addInpInstrumentationHandler","instrumentInp","addPerformanceInstrumentationHandler","instrumentPerformanceObserver","getCleanupCallback","previousValue","isPerformanceEventTiming","isMeasurementValue","startAndEndSpan","startTimeInSeconds","parentStartTime","startStandaloneWebVitalSpan","passedAttributes","replay","replayId","userDisplay","profileId","getBrowserPerformanceAPI","msToSec","trackClsAsStandaloneSpan","standaloneCLsValue","standaloneClsEntry","pageloadSpanId","supportsLayoutShift","sentSpan","_collectClsOnce","sendStandaloneClsSpan","cleanupClsHandler","unsubscribeStartNavigation","clsValue","routeName","MAX_INT_AS_BYTES","_performanceCursor","_measurements","_lcpEntry","_clsEntry","startTrackingWebVitals","recordClsStandaloneSpans","fidCleanupCallback","_trackFID","lcpCleanupCallback","_trackLCP","ttfbCleanupCallback","_trackTtfb","clsCleanupCallback","_trackCLS","startTrackingLongTasks","parentOp","parentStartTimestamp","startTrackingLongAnimationFrames","initialScript","invoker","invokerType","sourceURL","sourceFunctionName","sourceCharPosition","startTrackingInteractions","spanOptions","componentName","addPerformanceEntries","performanceEntries","transactionStartTime","_addNavigationSpans","_addMeasureSpans","firstHidden","shouldRecord","_addResourceSpans","_trackNavigator","_addTtfbRequestTimeToMeasurements","fidMark","measurementName","measurement","_setWebVitalAttributes","requestTime","measureStartTimestamp","startTimeStamp","measureEndTimestamp","_addPerformanceNavigationTiming","_addRequest","eventEnd","_getEndPropertyNameForNavigationTiming","start","requestStartTimestamp","responseEndTimestamp","responseStartTimestamp","resourceUrl","parsedUrl","setResourceEntrySizeData","deliveryType","renderBlockingStatus","navigator","connection","dataKey","entryVal","responseStart","requestStart","DEBOUNCE_DURATION","debounceTimerID","lastCapturedEventType","lastCapturedEventTargetId","addClickKeypressInstrumentationHandler","instrumentDOM","triggerDOMHandler","globalDOMEventHandler","makeDOMEventHandler","targetObj","originalAddEventListener","handlerForType","originalRemoveEventListener","isSimilarToLastCapturedEvent","shouldSkipDOMEvent","globalListener","getEventTarget","lastHref","addHistoryInstrumentationHandler","instrumentHistory","oldOnPopState","to","historyReplacementFunction","originalHistoryFunction","cachedImplementations","getNativeImplementation","cached","impl","document","contentWindow","clearCachedImplementation","setTimeout","SENTRY_XHR_DATA_KEY","addXhrInstrumentationHandler","instrumentXHR","xhrproto","originalOpen","xhrOpenThisArg","xhrOpenArgArray","onreadystatechangeHandler","xhrInfo","originalOnreadystatechange","onreadystatechangeThisArg","onreadystatechangeArgArray","originalSetRequestHeader","setRequestHeaderThisArg","setRequestHeaderArgArray","originalSend","sendThisArg","sendArgArray","sentryXhrData","LAST_INTERACTIONS","INTERACTIONS_SPAN_MAP","startTrackingINP","inpCallback","_trackINP","INP_ENTRY_MAP","interactionId","interactionType","spanToUse","registerInpInteractionListener","_latestRoute","activeRootSpan","makeFetchTransport","nativeFetch","pendingBodySize","pendingCount","requestSize","requestOptions","CHROME_PRIORITY","GECKO_PRIORITY","createFrame","lineno","colno","chromeRegexNoFnName","chromeRegex","chromeEvalRegex","chromeStackParserFn","noFnParts","col","subMatch","extractSafariExtensionDetails","chromeStackLineParser","geckoREgex","geckoEvalRegex","gecko","geckoStackLineParser","defaultStackLineParsers","defaultStackParser","isSafariExtension","isSafariWebExtension","MAX_ALLOWED_STRING_LENGTH","_breadcrumbsIntegration","_options","_getConsoleBreadcrumbHandler","_getDomBreadcrumbHandler","_getXhrBreadcrumbHandler","_getFetchBreadcrumbHandler","_getHistoryBreadcrumbHandler","_getSentryBreadcrumbHandler","breadcrumbsIntegration","dom","element","_isEvent","status_code","parsedLoc","parsedFrom","parsedTo","DEFAULT_EVENT_TARGET","_browserApiErrorsIntegration","_wrapTimeFunction","_wrapRAF","_wrapXHR","eventTargetOption","_wrapEventTarget","browserApiErrorsIntegration","originalCallback","xhr","wrapOptions","eventName","isEventListenerObject","originalEventHandler","browserSessionIntegration","_globalHandlersIntegration","_installGlobalOnErrorHandler","globalHandlerLog","_installGlobalOnUnhandledRejectionHandler","globalHandlersIntegration","getOptions","_enhanceEventWithInitialFrame","_getUnhandledRejectionError","_eventFromRejectionWithPrimitive","ev","ev0","ev0s","ev0sf","httpContextIntegration","referrer","DEFAULT_KEY","DEFAULT_LIMIT","_linkedErrorsIntegration","linkedErrorsIntegration","getDefaultIntegrations","applyDefaultOptions","optionsArg","defaultOptions","shouldShowBrowserExtensionError","windowWithMaybeExtension","extensionKey","extensionObject","runtimeId","href","extensionProtocols","isDedicatedExtensionPage","isNWjs","init","browserOptions","REPLAY_SESSION_KEY","REPLAY_EVENT_NAME","UNABLE_TO_SEND_REPLAY","SESSION_IDLE_PAUSE_DURATION","SESSION_IDLE_EXPIRE_DURATION","DEFAULT_FLUSH_MIN_DELAY","DEFAULT_FLUSH_MAX_DELAY","BUFFER_CHECKOUT_TIME","RETRY_BASE_INTERVAL","RETRY_MAX_COUNT","NETWORK_BODY_MAX_SIZE","CONSOLE_ARG_MAX_SIZE","SLOW_CLICK_THRESHOLD","SLOW_CLICK_SCROLL_TIMEOUT","REPLAY_MAX_EVENT_BUFFER_SIZE","MIN_REPLAY_DURATION","MIN_REPLAY_DURATION_LIMIT","MAX_REPLAY_DURATION","_nullishCoalesce$1","_optionalChain$5","NodeType$3","NodeType","isElement$1","isShadowRoot","_2","isNativeShadowDom","shadowRoot","fixBrowserCompatibilityIssuesInCSS","cssText","escapeImportStatement","rule","statement","stringifyStylesheet","s","rules","stringifyRule","fixAllCssProperty","styles","styleDeclaration","attribute","isImportant","importStringified","isCSSImportRule","isCSSStyleRule","needsSafariColonFix","needsAllFix","fixSafariColons","cssStringified","regex","Mirror","_3","_4","_5","childNode","node","meta","oldNode","createMirror","shouldMaskInput","maskInputOptions","tagName","maskInputValue","isMasked","maskInputFn","text","toLowerCase","toUpperCase","ORIGINAL_ATTRIBUTE_NAME","is2DCanvasBlank","canvas","chunkSize","getImageData","originalGetImageData","pixel","getInputType","getInputValue","extractFileExtension","baseURL","_6","cachedImplementations$1","getImplementation$1","setTimeout$2","clearTimeout$2","getIframeContentDocument","iframe","_id","tagNameRegex","IGNORED_NODE","genId","getValidTagName","processedTagName","extractOrigin","canvasService","canvasCtx","URL_IN_CSS_REF","URL_PROTOCOL_MATCH","URL_WWW_MATCH","DATA_URI","absoluteToStylesheet","quote1","path1","quote2","path2","path3","filePath","maybeQuote","part","SRCSET_NOT_SPACES","SRCSET_COMMAS_OR_SPACES","getAbsoluteSrcsetString","attributeValue","pos","collectCharacters","regEx","chars","absoluteToDoc","descriptorsStr","inParens","cachedDocument","getHref","isSVGElement","customHref","transformAttribute","maskAttributeFn","ignoreAttribute","_isBlockedElement","blockClass","blockSelector","unblockSelector","eIndex","elementClassMatchesRegex","distanceToMatch","matchPredicate","distance","createMatchPredicate","needMaskingText","maskTextClass","maskTextSelector","unmaskTextClass","unmaskTextSelector","maskAllText","autocomplete","maskDistance","unmaskDistance","onceIframeLoaded","iframeEl","iframeLoadTimeout","win","fired","readyState","timer","blankUrl","onceStylesheetLoaded","link","styleSheetLoadTimeout","styleSheetLoaded","serializeNode","mirror","inlineStylesheet","maskTextFn","dataURLOptions","inlineImages","recordCanvas","keepIframeSrcFn","newlyAddedElement","rootId","getRootId","serializeElementNode","serializeTextNode","docId","parentTagName","textContent","isStyle","isScript","isTextarea","_7","_8","_9","forceMask","isInputMasked","needBlock","stylesheet","checked","canvasDataURL","blankCanvas","blankCanvasDataURL","image","imageSrc","priorCrossOrigin","recordInlineImage","width","isCustomElement","lowerIfExists","maybeAttr","slimDOMExcluded","sn","slimDOMOptions","serializeNodeWithId","skipChild","onSerialize","onIframeLoad","onStylesheetLoad","stylesheetLoadTimeout","preserveWhiteSpace","_serializedNode","serializedNode","recordChild","bypassOptions","childN","serializedChildNode","iframeDoc","serializedIframeNode","serializedLinkNode","snapshot","maskAllInputs","slimDOM","_optionalChain$4","on","DEPARTED_MIRROR_ACCESS_WARNING","_mirror","receiver","throttle$1","wait","previous","remaining","clearTimeout$1","setTimeout$1","hookSetter","isRevoked","replacement","nowTimestamp","getWindowScroll","_10","_11","_12","_13","_14","getWindowHeight","getWindowWidth","closestElementOfNode","isBlocked","checkAncestors","blockedPredicate","isUnblocked","blockDistance","unblockDistance","isSerialized","isIgnored","isAncestorRemoved","legacy_isTouchEvent","polyfill","isSerializedIframe","isSerializedStylesheet","hasShadowRoot","_18","StyleSheetMirror","newId","getShadowHost","shadowHost","_19","_20","_21","getRootShadowHost","rootShadowHost","shadowHostInDom","inDom","getImplementation","onRequestAnimationFrame","EventType","EventType2","IncrementalSource","IncrementalSource2","MouseInteractions","MouseInteractions2","PointerTypes","PointerTypes2","NodeType$1","NodeType$2","getIFrameContentDocument","getIFrameContentWindow","_optionalChain$3","isNodeInLinkedList","DoubleLinkedList","position","moveKey","MutationBuffer","mutations","adds","addedIds","addList","getNextId","ns","nextId","pushAdd","currentN","childSn","isParentRemoved","isAncestorInSet","candidate","tailNode","_node","unhandledNode","diffAsStr","unchangedAsStr","attributeName","old","pname","newValue","newPriority","nodeId","deepDelete","targetId","addsSet","removes","_isParentRemoved","_isAncestorInSet","parentNode","errorHandler","registerErrorHandler","unregisterErrorHandler","callbackWrapper","_optionalChain$2","mutationBuffers","initMutationObserver","rootEl","mutationBuffer","mutationObserverCtor","angularZoneSymbol","initMoveObserver","mousemoveCb","sampling","callbackThreshold","positions","timeBaseline","wrappedCb","totalOffset","updatePosition","clientX","clientY","initMouseInteractionObserver","mouseInteractionCb","disableMap","currentPointerType","getHandler","eventKey","pointerType","thisEventKey","initScrollObserver","scrollCb","scrollLeftTop","initViewportResizeObserver","viewportResizeCb","lastH","lastW","updateDimension","INPUT_TAGS","lastInputValueMap","initInputObserver","inputCb","ignoreClass","ignoreSelector","userTriggeredOnInput","eventHandler","userTriggered","isChecked","cbWithDedup","lastInputValue","currentWindow","propertyDescriptor","hookProperties","getNestedCSSRulePositions","recurse","childRule","hasNestedCSSRule","getIdAndStyleId","sheet","styleMirror","styleId","initStyleSheetObserver","styleSheetRuleCb","stylesheetManager","insertRule","argumentsList","deleteRule","replace","replaceSync","supportedNestedCSSRuleTypes","canMonkeyPatchNestedCSSRule","unmodifiedFunctions","typeKey","initAdoptedStyleSheetObserver","hostId","patchTarget","originalPropertyDescriptor","sheets","_15","_16","initStyleDeclarationObserver","styleDeclarationCb","ignoreCSSAttributes","setProperty","priority","_17","removeProperty","initMediaInteractionObserver","mediaInteractionCb","currentTime","volume","muted","playbackRate","initFontObserver","fontCb","fontMap","originalFontFace","family","fontFace","restoreHandler","initSelectionObserver","param","selectionCb","collapsed","updateSelection","selection","ranges","range","startContainer","startOffset","endContainer","endOffset","initCustomElementObserver","customElementCb","constructor","initObservers","o","_hooks","mutationObserver","mousemoveHandler","mouseInteractionHandler","scrollHandler","viewportResizeHandler","inputHandler","mediaInteractionHandler","styleSheetObserver","adoptedStyleSheetObserver","styleDeclarationObserver","fontObserver","selectionObserver","customElementObserver","pluginHandlers","_22","_23","CrossOriginIframeMirror","generateIdFn","remoteId","idToRemoteMap","remoteToIdMap","idToRemoteIdMap","remoteIdToIdMap","ids","_optionalChain$1","IframeManagerNoop","IframeManager","crossOriginMessageEvent","transformedEvent","style","iframeMirror","ShadowDomManagerNoop","ShadowDomManager","iframeElement","iframeWindow","manager","CanvasManagerNoop","StylesheetManager","linkEl","adoptedStyleSheetData","ProcessedNodeManager","thisBuffer","wrappedEmit","_takeFullSnapshot","cleanFrame","record","emit","checkoutEveryNms","checkoutEveryNth","_maskInputOptions","_slimDOMOptions","maxCanvasSize","packFn","mousemoveWait","recordDOM","recordCrossOriginIframes","recordAfter","collectFonts","onMutation","getCanvasManager","inEmittingFrame","passEmitsToParent","lastFullSnapshotEvent","incrementalSnapshotCount","isCheckout","exceedCount","exceedTime","takeFullSnapshot","wrappedMutationEmit","wrappedScrollEmit","wrappedCanvasMutationEmit","wrappedAdoptedStyleSheetEmit","iframeManager","processedNodeManager","canvasManager","_getCanvasManager","shadowDomManager","getCanvasManagerFn","ReplayEventTypeIncrementalSnapshot","ReplayEventTypeCustom","timestampToMs","timestampToS","addBreadcrumbEvent","INTERACTIVE_SELECTOR","getClosestInteractive","getClickTargetNode","getTargetNode","isEventWithTarget","onWindowOpen","monkeyPatchWindowOpen","originalWindowOpen","IncrementalMutationSources","handleClick","clickDetector","clickBreadcrumb","ClickDetector","slowClickConfig","_addBreadcrumbEvent","cleanupWindowOpen","nowInSeconds","ignoreElement","isClickBreadcrumb","newClick","click","timedOutClicks","hadScroll","hadMutation","isSlowClick","clickCount","timeAfterClickMs","endReason","setTimeout$3","SLOW_CLICK_TAGS","updateClickDetectorForRecordingEvent","isIncrementalEvent","isIncrementalMouseInteraction","createBreadcrumb","ATTRIBUTES_TO_RECORD","getAttributesToRecord","normalizedKey","handleDomListener","handleDom","isClick","getBaseDomBreadcrumb","getDomTarget","handleKeyboardEvent","getKeyboardBreadcrumb","metaKey","shiftKey","ctrlKey","altKey","isInputElement","hasModifierKey","isCharacterKey","baseBreadcrumb","ENTRY_TYPES","createResourceEntry","createPaintEntry","createNavigationEntry","webVitalHandler","getter","createPerformanceEntries","createPerformanceEntry","entryType","getAbsoluteTime","decodedBodySize","domComplete","encodedBodySize","domContentLoadedEventStart","domContentLoadedEventEnd","domInteractive","loadEventStart","loadEventEnd","redirectCount","transferSize","initiatorType","responseEnd","responseStatus","getLargestContentfulPaint","lastEntry","getWebVital","isLayoutShift","getCumulativeLayoutShift","layoutShifts","nodes","nodeIds","getFirstInputDelay","getInteractionToNextPaint","attributions","rating","setupPerformanceObserver","addPerformanceEntry","onEntries","clearCallbacks","clearCallback","_addBreadcrumb","makeReplayLogger","_capture","_trace","_logger","logger$1","EventBufferSizeExceededError","EventBufferArray","eventSize","eventsRet","WorkerHandler","worker","EventBufferCompressionWorker","EventBufferProxy","hasCheckout","waitForCheckout","addEventPromises","createEventBuffer","useCompression","customWorkerUrl","_loadWorker","workerUrl","_getWorkerUrl","hasSessionStorage","clearSession","deleteSession","isSampled","started","lastActivity","segmentId","previousSessionId","saveSession","getSessionSampleType","sessionSampleRate","allowBuffering","createSession","stickySession","fetchSession","sessionStringFromStorage","sessionObj","isExpired","initialTime","expiry","targetTime","isSessionExpired","maxReplayDuration","sessionIdleExpire","shouldRefreshSession","loadOrCreateSession","sessionOptions","existingSession","isCustomEvent","addEventSync","shouldAddEvent","_addEvent","addEvent","eventBuffer","isBufferMode","replayOptions","eventAfterPossibleCallback","maybeApplyCallback","isExceeded","timestampInMs","isReplayEvent","isFeedbackEvent","handleAfterSendEvent","handleTransactionEvent","handleErrorEvent","replayContext","beforeErrorSampling","handleBeforeSendEvent","handleHydrationError","exceptionValue","handleBreadcrumbs","beforeAddBreadcrumb","isBreadcrumbWithCategory","normalizeBreadcrumb","normalizeConsoleBreadcrumb","isTruncated","normalizedArgs","normalizedArg","isRrwebError","resetReplayIdOnDynamicSamplingContext","addFeedbackBreadcrumb","shouldSampleForBufferEvent","handleGlobalEventListener","createPerformanceSpans","handleHistory","handleHistorySpanListener","shouldFilterRequest","addNetworkBreadcrumb","getBodySize","textEncoder","formDataStr","_serializeFormData","parseContentLengthHeader","getBodyString","mergeWarning","info","warning","newMeta","existingWarnings","makeNetworkReplayBreadcrumb","buildSkippedNetworkRequestOrResponse","bodySize","buildNetworkRequestOrResponse","normalizedBody","warnings","normalizeNetworkBody","getAllowedHeaders","allowedHeaders","filteredHeaders","formData","exceedsSizeLimit","isProbablyJson","_strIsProbablyJson","truncatedBody","urlMatches","urls","getFullUrl","baseURI","fixedUrl","captureFetchBreadcrumbToReplay","_prepareFetchData","enrichFetchBreadcrumb","_getFetchRequestArgBody","reqSize","resSize","requestBodySize","responseBodySize","captureDetails","_getRequestInfo","_getResponseInfo","networkCaptureBodies","networkRequestHeaders","getRequestHeaders","requestBody","bodyStr","networkResponseHeaders","getAllHeaders","bodyText","_parseFetchResponseBody","getResponseData","_tryCloneResponse","_tryGetResponseText","allHeaders","getHeadersFromOptions","_getResponseText","txt","captureXhrBreadcrumbToReplay","_prepareXhrData","enrichXhrBreadcrumb","_getBodySize","getResponseHeaders","requestWarning","responseBody","responseWarning","_getXhrResponseBody","errors","_parseXhrResponse","responseType","handleNetworkBreadcrumbs","networkDetailAllowUrls","networkDetailDenyUrls","beforeAddNetworkBreadcrumb","_isXhrBreadcrumb","_isXhrHint","_isFetchBreadcrumb","_isFetchHint","addGlobalListeners","feedbackEvent","addMemoryEntry","createMemoryEntry","memoryEntry","jsHeapSizeLimit","totalJSHeapSize","usedJSHeapSize","debounce","callbackReturnValue","timerId","maxTimerId","maxWait","invokeFunc","cancelTimers","debounced","getHandleRecordingEmit","hadFirstEvent","_isCheckout","addSettingsEvent","earliestEvent","createOptionsEvent","createReplayEnvelope","replayEvent","recordingData","prepareRecordingData","payloadWithSequence","replayHeaders","sequence","prepareReplayEvent","event_id","eventHint","preparedEvent","sendReplayRequest","segment_id","eventContext","preparedRecordingData","errorIds","traceIds","initialTimestamp","baseEvent","TransportStatusCodeError","RateLimitError","sendReplay","replayData","retryConfig","onError","THROTTLED","SKIPPED","throttle","maxCount","durationSeconds","_cleanup","_getTotalCount","isThrottled","wasThrottled","ReplayContainer","recordingOptions","slowClickTimeout","slowClickIgnoreSelectors","experiments","errorSampleRate","requiresManualStart","canvasOptions","forceFlush","continueRecording","activityTime","hasStoppedRecording","cbResult","urlPath","lastActiveSpan","lastRootSpan","_lastActivity","initialTimestampInSeconds","_context","dropReason","force","tooShort","tooLong","_flushInProgress","mutationLimit","mutationBreadcrumbLimit","overMutationLimit","getOption","selectors","defaultSelectors","getPrivacyOptions","mask","unmask","block","unblock","ignore","defaultBlockedElements","maskSelector","unmaskSelector","maskAttribute","maskAttributes","privacyOptions","MEDIA_SELECTORS","DEFAULT_NETWORK_HEADERS","_initialized","replayIntegration","Replay","flushMinDelay","flushMaxDelay","minReplayDuration","_experiments","blockAllMedia","maskFn","beforeAddRecordingEvent","_getMergedNetworkHeaders","finalOptions","loadReplayOptionsFromClient","canvasIntegration","initialOptions","opt","replaysSessionSampleRate","replaysOnErrorSampleRate","responseToSpanId","spanIdToEndTimestamp","defaultRequestInstrumentationOptions","instrumentOutgoingRequests","traceFetch","traceXHR","trackFetchStreamPerformance","shouldCreateSpanForRequest","enableHTTPTimings","tracePropagationTargets","shouldAttachHeadersWithTargets","updatedTimestamp","createdSpan","addHTTPTimings","xhrCallback","isPerformanceResourceTiming","resourceTimingEntryToSpanData","extractNetworkProtocol","nextHopProtocol","char","resourceTiming","timingSpanData","targetUrl","resolvedUrl","currentOrigin","isSameOriginRequest","isRelativeSameOriginRequest","addTracingHeadersToXhrRequest","setHeaderOnXhr","sentryTraceHeader","sentryBaggageHeader","registerBackgroundTabDetection","cancelledStatus","BROWSER_TRACING_INTEGRATION_ID","DEFAULT_BROWSER_TRACING_OPTIONS","browserTracingIntegration","enableInp","enableLongTask","enableLongAnimationFrame","enableInteractions","enableStandaloneClsSpans","beforeStartSpan","markBackgroundSpan","instrumentPageLoad","instrumentNavigation","_collectWebVitals","latestRoute","_createRouteSpan","isPageloadTransaction","finalStartSpanOptions","idleSpan","emitFinish","startingUrl","maybeEndActiveSpan","traceOptions","getMetaContent","oldPropagationContext","startBrowserTracingPageLoadSpan","startBrowserTracingNavigationSpan","registerInteractionListener","metaName","metaTag","inflightInteractionSpan","registerInteractionTransaction","currentRootSpanOp","MS_TO_NS","THREAD_ID_STRING","THREAD_NAME","OS_PLATFORM","OS_PLATFORM_VERSION","OS_ARCH","OS_BROWSER","OS_MODEL","OS_LOCALE","isUserAgentData","userAgentData","ua","firstUa","isProcessedJSSelfProfile","profile","enrichWithThreadInformation","convertJSSelfProfileToSampledFormat","getTraceId","createProfilePayload","profile_id","start_timestamp","processed_profile","enrichedThreadProfile","transactionStartMs","transactionEndMs","applyDebugMetadata","isAutomatedPageLoadSpan","EMPTY_STACK_ID","STACK_ID","firstSample","adjustForOriginChange","jsSample","stackTop","sample","addProfilesToEnvelope","profiles","findProfiledTransactionsFromEnvelope","j","isValidSampleRate","isValidProfile","PROFILING_CONSTRUCTOR_FAILED","MAX_PROFILE_DURATION_MS","isJSProfilerSupported","maybeProfiler","startJSSelfProfile","JSProfilerConstructor","samplingIntervalMS","maxSamples","shouldProfileSpan","profilesSampleRate","createProfilingEvent","PROFILE_MAP","getActiveProfilesCount","takeProfileFromGlobalCache","addProfileToGlobalCache","startProfileForSpan","profiler","onProfileHandler","maxDurationTimeoutID","originalEnd","profilingWrappedSpanEnd","_browserProfilingIntegration","profiledTransactionEvents","profilesToAddToEnvelope","profiledTransaction","profileEvent","browserProfilingIntegration","init$1","CLIENTS_WITH_INSTRUMENT_NAVIGATION","createReactRouterV6CompatibleTracingIntegration","useEffect","useNavigationType","createRoutesFromChildren","matchRoutes","stripBasename","initPathName","reactRouterV6BrowserTracingIntegration","sentryConfig","Sentry.reactRouterV6BrowserTracingIntegration","Sentry.replayIntegration","Sentry.browserTracingIntegration","Sentry.browserProfilingIntegration","Sentry.init","exports","gtag","_len","_window","_default","format","smallWords","toTitleCase","string","title","mightBeEmail","redacted","redactEmail","titleCase","redactingEmail","_str","_gtag","_interopRequireDefault","_format","require$$1","_excluded","_excluded2","_excluded3","_objectWithoutProperties","excluded","_objectWithoutPropertiesLoose","sourceSymbolKeys","sourceKeys","_typeof","_toConsumableArray","_arrayWithoutHoles","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","_arrayLikeToArray","ownKeys","enumerableOnly","symbols","sym","_objectSpread","_defineProperty","_slicedToArray","_arrayWithHoles","_iterableToArrayLimit","_nonIterableRest","minLen","arr2","_i","_s","_e","_x","_r","_arr","_n","_d","_classCallCheck","instance","Constructor","_defineProperties","props","descriptor","_toPropertyKey","_createClass","protoProps","staticProps","_toPrimitive","prim","GA4","_this","GA_MEASUREMENT_ID","nonce","gtagUrl","script","gaOptions","mapFields","gtagOptions","prev","_ref","_ref2","initConfigs","_options$testMode","testMode","mergedGtagOptions","queues","queue","fieldsObject","eventCategory","eventAction","eventLabel","eventValue","_len2","_key2","_args$","timingCategory","timingVar","timingValue","timingLabel","page","_this$_toGtagOptions","location","_len3","_key3","_args$2","_len4","_key4","hitType","_len5","_key5","command","_len6","_key6","_len7","_key7","readyCallback","clientId","optionsOrName","label","nonInteraction","fieldObject","_ga","_interopRequireWildcard","_getRequireWildcardCache","nodeInterop","cacheBabelInterop","cacheNodeInterop","cache","hasPropertyDescriptor","ReactGAImplementation","getHomeRouteForLoggedInUser","DefaultRoute","PublicRoute","route","restrictedRoute","Navigate","jsx","Suspense","PropTypes","Redirect","useParams","Dashboard","lazy","Home","AppLayout","Error","Brand","MembershipCart","CustomMembershipCart","LeaseMembershipCart","CheckoutResult","CheckoutSuccess","CheckoutFailure","Terms","__vitePreload","Faqs","Refunds","Privacy","About","ScanQrCode","Routes","Router","useRoutes","GET_USER","SEND_OTP","VERIFY_OTP","GET_ACCOUNT","GET_CLAIMED_COLLECTIBLES","GET_SETTINGS","accountId","CHECK_TOKEN","GET_COLLECTION_WITH_ID","collectionId","PAY_COLLECTION","MINT_COLLECTION","COLLECTION_PRIVILEGES","GET_AIRDROP_WITH_ID","airdropId","PAY_AIRDROP","MINT_AIRDROP","GET_COLLECTIBLE_WITH_ID","collectibleId","RENEW_COLLECTIBLE_WITH_ID","GET_CHECKINS","PRESIGN_UPLOAD_URL","LEASE_COLLECTIBLE_PURCHASE","tokenId","LEASE_COLLECTIBLE","GET_BRAND_DETAILS","ADD_USER_TO_WAITLIST","GET_WALLET_HISTORY","GET_WALLET_BALANCE","ADD_PAN","ADD_BANK","GET_ACCOUNTS_BY_ID","GET_ACCOUNTS_BY_PHONE","CREATE_PAYOUT_TRANSFER","SEARCH_USER","API_URL","axiosApi","axios","token","Sentry.captureException","handleError","toast","get","post","put","url.GET_USER","checkToken","url.CHECK_TOKEN","getRefreshToken","setIdentity","url.GET_ACCOUNT","sendOTPService","url.SEND_OTP","verifyOTPService","url.VERIFY_OTP","findAccount","url.GET_ACCOUNTS_BY_PHONE","stringToByteArray$1","byteArrayToString","bytes","c1","c2","c3","c4","base64","webSafe","byteToCharMap","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","charToByteMap","byte4","DecodeBase64StringError","base64Encode","utf8Bytes","base64urlEncodeWithoutPadding","base64Decode","getGlobal","getDefaultsFromGlobal","getDefaultsFromEnvVariable","define_process_env_default","defaultsJsonString","getDefaultsFromCookie","decoded","getDefaults","getDefaultEmulatorHost","productName","_b","getDefaultAppConfig","getExperimentalSetting","Deferred","getUA","isMobileCordova","isBrowserExtension","runtime","isIE","isIndexedDBAvailable","validateIndexedDBOpenable","preExist","DB_CHECK_NAME","ERROR_NAME","FirebaseError","customData","ErrorFactory","service","serviceName","fullCode","template","replaceTemplate","fullMessage","PATTERN","isEmpty","deepEqual","aKeys","bKeys","aProp","bProp","isObject","querystring","querystringParams","arrayVal","querystringDecode","extractQuerystring","queryStart","fragmentStart","createSubscribe","onNoObservers","ObserverProxy","nextOrObserver","complete","implementsAnyMethods","unsub","methods","getModularInstance","Component","instanceFactory","mode","multipleInstances","DEFAULT_ENTRY_NAME","container","identifier","normalizedIdentifier","deferred","optional","isComponentEager","instanceIdentifier","instanceDeferred","services","normalizedDeferredIdentifier","existingCallbacks","normalizeIdentifierForFactory","ComponentContainer","provider","LogLevel","levelStringToEnum","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","Logger","instanceOfAny","constructors","idbProxyableTypes","cursorAdvanceMethods","getIdbProxyableTypes","getCursorAdvanceMethods","cursorRequestMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","promisifyRequest","unlisten","success","cacheDonePromiseForTransaction","tx","idbProxyTraps","replaceTraps","wrapFunction","storeNames","unwrap","transformCachableValue","openDB","blocked","upgrade","blocking","terminated","openPromise","db","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","storeName","oldTraps","PlatformLoggerServiceImpl","isVersionServiceProvider","logString","name$p","version$1","name$o","name$n","name$m","name$l","name$k","name$j","name$i","name$h","name$g","name$f","name$e","name$d","name$c","name$b","name$a","name$9","name$8","name$7","name$6","name$5","name$4","name$3","name$2","name$1","PLATFORM_LOG_STRING","_apps","_serverApps","_components","_addComponent","app","_registerComponent","serverApp","_getProvider","heartbeatController","_isFirebaseServerApp","ERRORS","ERROR_FACTORY","FirebaseAppImpl","initializeApp","rawConfig","existingApp","newApp","getApp","registerVersion","libraryKeyOrName","variant","library","libraryMismatch","versionMismatch","DB_NAME","DB_VERSION","STORE_NAME","dbPromise","getDbPromise","oldVersion","readHeartbeatsFromIndexedDB","computeKey","idbGetError","writeHeartbeatsToIndexedDB","heartbeatObject","MAX_HEADER_BYTES","STORED_HEARTBEAT_RETENTION_MAX_MILLIS","HeartbeatServiceImpl","HeartbeatStorageImpl","agent","date","getUTCDateString","singleDateHeartbeat","hbTimestamp","heartbeatsToSend","unsentEntries","extractHeartbeatsForHeader","headerString","heartbeatsCache","heartbeatEntry","hb","countBytes","idbHeartbeatObject","heartbeatsObject","existingHeartbeatsObject","registerCoreComponents","_prodErrorMap","prodErrorMap","_DEFAULT_AUTH_ERROR_FACTORY","logClient","_logWarn","_logError","_fail","authOrCode","createErrorInternal","_createError","_errorWithCustomMessage","errorMap","_serverAppCurrentUserOperationNotSupportedError","fullParams","_assert","assertion","debugFail","failure","debugAssert","_getCurrentUrl","_isHttpOrHttps","_getCurrentScheme","_isOnline","_getUserLanguage","navigatorLanguage","Delay","shortDelay","longDelay","_emulatorUrl","FetchProvider","fetchImpl","headersImpl","responseImpl","SERVER_ERROR_MAP","DEFAULT_API_TIMEOUT_MS","_addTidIfNecessary","_performApiRequest","customErrorMap","_performFetchWithErrorHandling","_getFinalTarget","fetchFn","networkTimeout","NetworkTimeout","json","_makeTaggedError","serverErrorCode","serverErrorMessage","authError","_performSignInRequest","serverResponse","_parseEnforcementState","enforcementStateStr","errorParams","isV2","grecaptcha","isEnterprise","RecaptchaConfig","providerStr","recaptchaEnforcementState","getRecaptchaParams","getRecaptchaConfig","deleteAccount","getAccountInfo","utcTimestampToDateString","utcTimestamp","getIdTokenResult","forceRefresh","userInternal","claims","_parseToken","firebase","signInProvider","secondsStringToMilliseconds","seconds","algorithm","signature","_tokenExpiresIn","parsedToken","_logoutIfInvalidated","bypassAuthState","isUserInvalidated","ProactiveRefresh","wasError","UserMetadata","createdAt","lastLoginAt","_reloadWithoutSaving","idToken","coreAccount","newProviderData","extractProviderData","providerData","mergeProviderData","oldIsAnonymous","newIsAnonymous","isAnonymous","updates","reload","providers","providerId","__rest","requestStsToken","refreshToken","tokenApiHost","apiKey","revokeToken","StsTokenManager","expiresIn","oldToken","accessToken","expiresInSec","appName","expirationTime","stsTokenManager","assertStringOrUndefined","UserImpl","uid","userInfo","newUser","tokensRefreshed","_c","_f","_g","_h","displayName","email","phoneNumber","photoURL","tenantId","_redirectEventId","emailVerified","plainObjectTokenManager","idTokenResponse","instanceCache","_getInstance","cls","InMemoryPersistence","_listener","inMemoryPersistence","_persistenceKeyName","PersistenceUserManager","persistence","userKey","blob","newPersistence","currentUser","persistenceHierarchy","availablePersistences","selectedPersistence","userToMigrate","migrationHierarchy","_getBrowserName","_isIEMobile","_isFirefox","_isBlackBerry","_isWebOS","_isSafari","_isChromeIOS","_isAndroid","re","_isIOS","_isIOSStandalone","_isIE10","_isMobileBrowser","_isIframe","_getClientVersion","clientPlatform","frameworks","reportedPlatform","reportedFrameworks","AuthMiddlewareQueue","onAbort","wrappedCallback","nextUser","onAbortStack","beforeStateCallback","_getPasswordPolicy","MINIMUM_MIN_PASSWORD_LENGTH","PasswordPolicyImpl","responseOptions","password","minPasswordLength","maxPasswordLength","passwordChar","containsLowercaseCharacter","containsUppercaseCharacter","containsNumericCharacter","containsNonAlphanumericCharacter","AuthImpl","heartbeatServiceProvider","appCheckServiceProvider","Subscription","popupRedirectResolver","previouslyStoredUser","futureCurrentUser","needsTocheckMiddleware","redirectUserEventId","storedUserEventId","redirectResolver","userExtern","skipBeforeStateCallbacks","passwordPolicy","completed","redirectManager","resolver","currentUid","isUnsubscribed","framework","heartbeatsHeader","appCheckToken","appCheckTokenResult","_castAuth","externalJSProvider","_setExternalJSProvider","_loadJS","_recaptchaV2ScriptUrl","_recaptchaEnterpriseScriptUrl","_gapiScriptUrl","_generateCallbackName","prefix","RECAPTCHA_ENTERPRISE_VERIFIER_TYPE","FAKE_TOKEN","RecaptchaEnterpriseVerifier","authExtern","retrieveSiteKey","retrieveRecaptchaToken","siteKey","injectRecaptchaFields","captchaResp","verifier","captchaResponse","newRequest","handleRecaptchaFlow","authInstance","actionName","actionMethod","requestWithRecaptcha","initializeAuth","deps","_initializeAuthInstance","hierarchy","connectAuthEmulator","authInternal","disableWarnings","extractProtocol","extractHostAndPort","portStr","emitEmulatorWarning","protocolEnd","authority","hostAndPort","bracketedIPv6","parsePort","attachBanner","sty","AuthCredential","signInMethod","_auth","_idToken","linkEmailPassword","signInWithPassword","sendOobCode","sendEmailVerification$1","sendPasswordResetEmail$1","signInWithEmailLink$1","signInWithEmailLinkForLinking","EmailAuthCredential","_email","_password","_tenantId","oobCode","signInWithIdp","IDP_REQUEST_URI$1","OAuthCredential","cred","postBody","sendPhoneVerificationCode","signInWithPhoneNumber$1","linkWithPhoneNumber$1","VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_","verifyPhoneNumberForExisting","apiRequest","PhoneAuthCredential","verificationId","verificationCode","temporaryProof","parseMode","parseDeepLink","doubleDeepLink","iOSDeepLink","ActionCodeURL","actionLink","searchParams","operation","EmailAuthProvider","emailLink","actionCodeUrl","FederatedAuthProvider","languageCode","customOAuthParameters","BaseOAuthProvider","FacebookAuthProvider","userCredential","tokenResponse","GoogleAuthProvider","oauthIdToken","oauthAccessToken","GithubAuthProvider","TwitterAuthProvider","secret","oauthTokenSecret","signUp","UserCredentialImpl","operationType","providerIdForResponse","MultiFactorError","_processCredentialSavingMfaContextIfNecessary","credential","_link$1","_reauthenticate","parsed","localId","_signInWithCredential","signInWithCredential","signInWithCustomToken$1","signInWithCustomToken","customToken","_setActionCodeSettingsOnRequest","actionCodeSettings","recachePasswordPolicy","sendPasswordResetEmail","createUserWithEmailAndPassword","signInWithEmailAndPassword","sendEmailVerification","updateProfile$1","updateProfile","photoUrl","profileRequest","passwordProvider","onIdTokenChanged","beforeAuthStateChanged","onAuthStateChanged","signOut","startEnrollPhoneMfa","STORAGE_AVAILABLE_KEY","BrowserPersistenceClass","storageRetriever","_iframeCannotSyncWebStorage","_POLLING_INTERVAL_MS$1","IE10_LOCAL_STORAGE_SYNC_DELAY","BrowserLocalPersistence","poll","oldValue","_oldValue","storedValue","triggerListeners","browserLocalPersistence","BrowserSessionPersistence","browserSessionPersistence","_allSettled","promises","Receiver","eventTarget","newInstance","messageEvent","_generateEventId","digits","random","Sender","messageChannel","completionTimer","ackTimer","_setWindowLocation","_isWorker","_getActiveServiceWorker","_getServiceWorkerController","_getWorkerGlobalScope","DB_OBJECTSTORE_NAME","DB_DATA_KEYPATH","DBPromise","getObjectStore","isReadWrite","_deleteDatabase","_openDatabase","_putObject","getObject","_deleteObject","_POLLING_INTERVAL_MS","_TRANSACTION_RETRY_COUNT","IndexedDBLocalPersistence","numAttempts","_origin","_data","results","write","getAllRequest","keysInResult","localKey","indexedDBLocalPersistence","startSignInPhoneMfa","_SOLVE_TIME_MS","_EXPIRATION_TIME_MS","_WIDGET_ID_START","MockReCaptcha","parameters","MockWidget","optWidgetId","containerOrId","generateRandomAlphaNumericString","expiredCallback","allowedChars","_JSLOAD_CALLBACK","NETWORK_TIMEOUT_DELAY","ReCaptchaLoaderImpl","hl","isHostLanguageValid","recaptcha","render","widgetId","MockReCaptchaLoaderImpl","RECAPTCHA_VERIFIER_TYPE","DEFAULT_PARAMS","RecaptchaVerifier","tokenChange","existing","globalFunc","guaranteedEmpty","domReady","ConfirmationResultImpl","onConfirmation","authCredential","signInWithPhoneNumber","appVerifier","_verifyPhoneNumber","recaptchaToken","phoneInfoOptions","mfaEnrollmentId","sessionInfo","_withDefaultResolver","resolverOverride","IdpCredential","_signIn","_reauth","AbstractPopupRedirectOperation","urlResponse","sessionId","_POLL_WINDOW_CLOSE_TIMEOUT","PopupOperation","isSupported","PENDING_REDIRECT_KEY","redirectOutcomeMap","RedirectAction","readyOutcome","_getAndClearPendingRedirectStatus","pendingRedirectKey","resolverPersistence","hasPendingRedirect","_overrideRedirectResult","_getRedirectResult","resolverExtern","EVENT_DUPLICATION_CACHE_DURATION_MS","AuthEventManager","authEventConsumer","handled","consumer","isRedirectEvent","isNullRedirectEvent","eventIdMatches","eventUid","_getProjectConfig","IP_ADDRESS_REGEX","HTTP_REGEX","_validateOrigin","authorizedDomains","domain","matchDomain","currentUrl","hostname","ceUrl","escapedDomainPattern","NETWORK_TIMEOUT","resetUnloadedGapiModules","beacon","loadGapi","loadGapiIframe","cbName","cachedGApiLoader","_loadGapi","PING_TIMEOUT","IFRAME_PATH","EMULATED_IFRAME_PATH","IFRAME_ATTRIBUTES","EID_FROM_APIHOST","getIframeUrl","eid","_openIframe","gapi","networkError","networkErrorTimer","clearTimerAndResolve","BASE_POPUP_OPTIONS","DEFAULT_WIDTH","DEFAULT_HEIGHT","TARGET_BLANK","FIREFOX_EMPTY_URL","AuthPopup","window","_open","top","left","optionsString","accum","openAsNewWindowIOS","newWin","WIDGET_PATH","EMULATOR_WIDGET_PATH","FIREBASE_APP_CHECK_FRAGMENT_ID","_getRedirectUrl","authType","redirectUrl","additionalParams","scopes","paramsDict","appCheckTokenFragment","getHandlerBase","WEB_STORAGE_SUPPORT_KEY","BrowserPopupRedirectResolver","iframeEvent","browserPopupRedirectResolver","AuthInterop","getVersionForPlatform","registerAuth","authDomain","_instanceIdentifier","_instance","DEFAULT_ID_TOKEN_MAX_AGE","authIdTokenMaxAge","lastPostedIdToken","mintCookieFactory","idTokenResult","idTokenAge","getAuth","authTokenSyncPath","authTokenSyncUrl","mintCookie","authEmulatorHost","getScriptParentElement","FirebaseAuthBackend","firebaseConfig","setFirebaseAuthSuccess","__publicField","confirmationResult","signInButton","_fireBaseBackend","initFirebaseBackend","getFirebaseBackend","Fonts","Global","definePartsStyle","defineMultiStyleConfig","createMultiStyleConfigHelpers","inputAnatomy","baseStyle","inputTheme","modalTheme","menuAnatomy","menuTheme","Theme","extendTheme","TRACKING_ID","ROUTES_WHICH_DO_NOT_NEED_LOGIN","App","firebaseAuthSuccess","useState","navigate","useNavigate","useToast","useSearchParams","fireBaseBackend","logoutUser","useCallback","checkAndRefreshToken","tokenQuery","useQuery","Sentry.setUser","ReactGA","found","search","collection_id","airdrop_id","collectible_id","redirectTo","jsxs","ChakraProvider","Center","Spinner","queryClient","QueryClient","root","BrowserRouter","QueryClientProvider"],"ignoreList":[0,1,2,3,4,5,11,12,13,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,155,156,157,158,167,168,169,170,171,172,173,174],"sources":["../../../../web/node_modules/react-dom/client.js","../../../../web/node_modules/redux/dist/redux.mjs","../../../../web/node_modules/immer/dist/immer.mjs","../../../../web/node_modules/reselect/dist/reselect.mjs","../../../../web/node_modules/redux-thunk/dist/redux-thunk.mjs","../../../../web/node_modules/@reduxjs/toolkit/dist/redux-toolkit.modern.mjs","../../../../web/src/utility/UserHelper.jsx","../../../../web/src/redux/auth.jsx","../../../../web/src/redux/transactionFilters.jsx","../../../../web/src/redux/rootReducer.jsx","../../../../web/src/redux/store.jsx","../../../../web/node_modules/use-sync-external-store/cjs/use-sync-external-store-with-selector.production.min.js","../../../../web/node_modules/use-sync-external-store/with-selector.js","../../../../web/node_modules/react-redux/dist/react-redux.mjs","../../../../web/src/components/layout/ScrollToTop.jsx","../../../../web/node_modules/@sentry/core/build/esm/debug-build.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/version.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/worldwide.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/debug-build.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/logger.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/stacktrace.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/instrument/handlers.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/instrument/globalError.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/instrument/globalUnhandledRejection.js","../../../../web/node_modules/@sentry/core/build/esm/carrier.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/is.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/browser.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/string.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/object.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/time.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/misc.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/syncpromise.js","../../../../web/node_modules/@sentry/core/build/esm/session.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/propagationContext.js","../../../../web/node_modules/@sentry/core/build/esm/utils/merge.js","../../../../web/node_modules/@sentry/core/build/esm/utils/spanOnScope.js","../../../../web/node_modules/@sentry/core/build/esm/scope.js","../../../../web/node_modules/@sentry/core/build/esm/defaultScopes.js","../../../../web/node_modules/@sentry/core/build/esm/asyncContext/stackStrategy.js","../../../../web/node_modules/@sentry/core/build/esm/asyncContext/index.js","../../../../web/node_modules/@sentry/core/build/esm/currentScopes.js","../../../../web/node_modules/@sentry/core/build/esm/metrics/metric-summary.js","../../../../web/node_modules/@sentry/core/build/esm/semanticAttributes.js","../../../../web/node_modules/@sentry/core/build/esm/tracing/spanstatus.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/baggage.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/tracing.js","../../../../web/node_modules/@sentry/core/build/esm/utils/spanUtils.js","../../../../web/node_modules/@sentry/core/build/esm/tracing/errors.js","../../../../web/node_modules/@sentry/core/build/esm/tracing/utils.js","../../../../web/node_modules/@sentry/core/build/esm/utils/hasTracingEnabled.js","../../../../web/node_modules/@sentry/core/build/esm/tracing/sentryNonRecordingSpan.js","../../../../web/node_modules/@sentry/core/build/esm/constants.js","../../../../web/node_modules/@sentry/core/build/esm/tracing/dynamicSamplingContext.js","../../../../web/node_modules/@sentry/core/build/esm/tracing/logSpans.js","../../../../web/node_modules/@sentry/core/build/esm/utils/parseSampleRate.js","../../../../web/node_modules/@sentry/core/build/esm/tracing/sampling.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/dsn.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/memo.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/normalize.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/envelope.js","../../../../web/node_modules/@sentry/core/build/esm/envelope.js","../../../../web/node_modules/@sentry/core/build/esm/tracing/measurement.js","../../../../web/node_modules/@sentry/core/build/esm/tracing/sentrySpan.js","../../../../web/node_modules/@sentry/core/build/esm/tracing/trace.js","../../../../web/node_modules/@sentry/core/build/esm/tracing/idleSpan.js","../../../../web/node_modules/@sentry/core/build/esm/eventProcessors.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/debug-ids.js","../../../../web/node_modules/@sentry/core/build/esm/utils/applyScopeDataToEvent.js","../../../../web/node_modules/@sentry/core/build/esm/utils/prepareEvent.js","../../../../web/node_modules/@sentry/core/build/esm/exports.js","../../../../web/node_modules/@sentry/core/build/esm/api.js","../../../../web/node_modules/@sentry/core/build/esm/integration.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/clientreport.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/error.js","../../../../web/node_modules/@sentry/core/build/esm/baseclient.js","../../../../web/node_modules/@sentry/core/build/esm/sdk.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/promisebuffer.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/ratelimit.js","../../../../web/node_modules/@sentry/core/build/esm/transports/base.js","../../../../web/node_modules/@sentry/core/build/esm/utils/isSentryRequestUrl.js","../../../../web/node_modules/@sentry/core/build/esm/utils/sdkMetadata.js","../../../../web/node_modules/@sentry/core/build/esm/utils/traceData.js","../../../../web/node_modules/@sentry/core/build/esm/breadcrumbs.js","../../../../web/node_modules/@sentry/core/build/esm/integrations/functiontostring.js","../../../../web/node_modules/@sentry/core/build/esm/integrations/inboundfilters.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/aggregate-errors.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/url.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/instrument/console.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/severity.js","../../../../web/node_modules/@sentry/core/build/esm/integrations/dedupe.js","../../../../web/node_modules/@sentry/core/build/esm/fetch.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/breadcrumb-log-level.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/supports.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/instrument/fetch.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/env.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/node.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/isBrowser.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/vendor/supportsHistory.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/buildPolyfills/_nullishCoalesce.js","../../../../web/node_modules/@sentry/core/build/esm/utils-hoist/buildPolyfills/_optionalChain.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/helpers.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/debug-build.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/eventbuilder.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/userfeedback.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/client.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/debug-build.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/bindReporter.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/types.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/generateUniqueID.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/getNavigationEntry.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/getActivationStart.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/initMetric.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/observe.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/onHidden.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/runOnce.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/getVisibilityWatcher.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/whenActivated.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/onFCP.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getCLS.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getFID.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/polyfills/interactionCountPolyfill.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/interactions.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/whenIdle.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getINP.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getLCP.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/onTTFB.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/instrument.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/utils.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/cls.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/browserMetrics.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/instrument/dom.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/instrument/history.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/getNativeImplementation.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/instrument/xhr.js","../../../../web/node_modules/@sentry-internal/browser-utils/build/esm/metrics/inp.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/transports/fetch.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/stack-parsers.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/integrations/breadcrumbs.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/integrations/browserapierrors.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/integrations/browsersession.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/integrations/globalhandlers.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/integrations/httpcontext.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/integrations/linkederrors.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/sdk.js","../../../../web/node_modules/@sentry-internal/replay/build/npm/esm/index.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/tracing/request.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/tracing/backgroundtab.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/tracing/browserTracingIntegration.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/profiling/utils.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/profiling/startProfileForSpan.js","../../../../web/node_modules/@sentry/browser/build/npm/esm/profiling/integration.js","../../../../web/node_modules/@sentry/react/build/esm/sdk.js","../../../../web/node_modules/@sentry/react/build/esm/reactrouterv6-compat-utils.js","../../../../web/node_modules/@sentry/react/build/esm/reactrouterv6.js","../../../../web/src/instrument.js","../../../../web/node_modules/react-ga4/dist/gtag.js","../../../../web/node_modules/react-ga4/dist/format.js","../../../../web/node_modules/react-ga4/dist/ga4.js","../../../../web/node_modules/react-ga4/dist/index.js","../../../../web/src/utility/Utils.jsx","../../../../web/src/components/routes/PublicRoute.jsx","../../../../web/src/components/routes/Redirect.jsx","../../../../web/src/router/routes/index.jsx","../../../../web/src/router/Router.jsx","../../../../web/src/utility/URLHelper.jsx","../../../../web/src/utility/APIHelper.jsx","../../../../web/src/services/AuthenticationService.jsx","../../../../web/node_modules/@firebase/util/dist/index.esm2017.js","../../../../web/node_modules/@firebase/component/dist/esm/index.esm2017.js","../../../../web/node_modules/@firebase/logger/dist/esm/index.esm2017.js","../../../../web/node_modules/idb/build/wrap-idb-value.js","../../../../web/node_modules/idb/build/index.js","../../../../web/node_modules/@firebase/app/dist/esm/index.esm2017.js","../../../../web/node_modules/firebase/app/dist/esm/index.esm.js","../../../../web/node_modules/firebase/node_modules/@firebase/auth/dist/esm2017/index-d0d29856.js","../../../../web/src/utility/FirebaseHelper.jsx","../../../../web/src/components/theme/fonts.jsx","../../../../web/src/components/theme/Input.jsx","../../../../web/src/components/theme/modal.jsx","../../../../web/src/components/theme/menu.jsx","../../../../web/src/components/theme/theme.jsx","../../../../web/src/App.jsx","../../../../web/src/main.jsx"],"sourcesContent":["'use strict';\n\nvar m = require('react-dom');\nif (process.env.NODE_ENV === 'production') {\n exports.createRoot = m.createRoot;\n exports.hydrateRoot = m.hydrateRoot;\n} else {\n var i = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n exports.createRoot = function(c, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.createRoot(c, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n exports.hydrateRoot = function(c, h, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.hydrateRoot(c, h, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n}\n","// src/utils/formatProdErrorMessage.ts\nfunction formatProdErrorMessage(code) {\n return `Minified Redux error #${code}; visit https://redux.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;\n}\n\n// src/utils/symbol-observable.ts\nvar $$observable = /* @__PURE__ */ (() => typeof Symbol === \"function\" && Symbol.observable || \"@@observable\")();\nvar symbol_observable_default = $$observable;\n\n// src/utils/actionTypes.ts\nvar randomString = () => Math.random().toString(36).substring(7).split(\"\").join(\".\");\nvar ActionTypes = {\n INIT: `@@redux/INIT${/* @__PURE__ */ randomString()}`,\n REPLACE: `@@redux/REPLACE${/* @__PURE__ */ randomString()}`,\n PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`\n};\nvar actionTypes_default = ActionTypes;\n\n// src/utils/isPlainObject.ts\nfunction isPlainObject(obj) {\n if (typeof obj !== \"object\" || obj === null)\n return false;\n let proto = obj;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(obj) === proto || Object.getPrototypeOf(obj) === null;\n}\n\n// src/utils/kindOf.ts\nfunction miniKindOf(val) {\n if (val === void 0)\n return \"undefined\";\n if (val === null)\n return \"null\";\n const type = typeof val;\n switch (type) {\n case \"boolean\":\n case \"string\":\n case \"number\":\n case \"symbol\":\n case \"function\": {\n return type;\n }\n }\n if (Array.isArray(val))\n return \"array\";\n if (isDate(val))\n return \"date\";\n if (isError(val))\n return \"error\";\n const constructorName = ctorName(val);\n switch (constructorName) {\n case \"Symbol\":\n case \"Promise\":\n case \"WeakMap\":\n case \"WeakSet\":\n case \"Map\":\n case \"Set\":\n return constructorName;\n }\n return Object.prototype.toString.call(val).slice(8, -1).toLowerCase().replace(/\\s/g, \"\");\n}\nfunction ctorName(val) {\n return typeof val.constructor === \"function\" ? val.constructor.name : null;\n}\nfunction isError(val) {\n return val instanceof Error || typeof val.message === \"string\" && val.constructor && typeof val.constructor.stackTraceLimit === \"number\";\n}\nfunction isDate(val) {\n if (val instanceof Date)\n return true;\n return typeof val.toDateString === \"function\" && typeof val.getDate === \"function\" && typeof val.setDate === \"function\";\n}\nfunction kindOf(val) {\n let typeOfVal = typeof val;\n if (process.env.NODE_ENV !== \"production\") {\n typeOfVal = miniKindOf(val);\n }\n return typeOfVal;\n}\n\n// src/createStore.ts\nfunction createStore(reducer, preloadedState, enhancer) {\n if (typeof reducer !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(2) : `Expected the root reducer to be a function. Instead, received: '${kindOf(reducer)}'`);\n }\n if (typeof preloadedState === \"function\" && typeof enhancer === \"function\" || typeof enhancer === \"function\" && typeof arguments[3] === \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(0) : \"It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.\");\n }\n if (typeof preloadedState === \"function\" && typeof enhancer === \"undefined\") {\n enhancer = preloadedState;\n preloadedState = void 0;\n }\n if (typeof enhancer !== \"undefined\") {\n if (typeof enhancer !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(1) : `Expected the enhancer to be a function. Instead, received: '${kindOf(enhancer)}'`);\n }\n return enhancer(createStore)(reducer, preloadedState);\n }\n let currentReducer = reducer;\n let currentState = preloadedState;\n let currentListeners = /* @__PURE__ */ new Map();\n let nextListeners = currentListeners;\n let listenerIdCounter = 0;\n let isDispatching = false;\n function ensureCanMutateNextListeners() {\n if (nextListeners === currentListeners) {\n nextListeners = /* @__PURE__ */ new Map();\n currentListeners.forEach((listener, key) => {\n nextListeners.set(key, listener);\n });\n }\n }\n function getState() {\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(3) : \"You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.\");\n }\n return currentState;\n }\n function subscribe(listener) {\n if (typeof listener !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(4) : `Expected the listener to be a function. Instead, received: '${kindOf(listener)}'`);\n }\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(5) : \"You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.\");\n }\n let isSubscribed = true;\n ensureCanMutateNextListeners();\n const listenerId = listenerIdCounter++;\n nextListeners.set(listenerId, listener);\n return function unsubscribe() {\n if (!isSubscribed) {\n return;\n }\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(6) : \"You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.\");\n }\n isSubscribed = false;\n ensureCanMutateNextListeners();\n nextListeners.delete(listenerId);\n currentListeners = null;\n };\n }\n function dispatch(action) {\n if (!isPlainObject(action)) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(7) : `Actions must be plain objects. Instead, the actual type was: '${kindOf(action)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`);\n }\n if (typeof action.type === \"undefined\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(8) : 'Actions may not have an undefined \"type\" property. You may have misspelled an action type string constant.');\n }\n if (typeof action.type !== \"string\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(17) : `Action \"type\" property must be a string. Instead, the actual type was: '${kindOf(action.type)}'. Value was: '${action.type}' (stringified)`);\n }\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(9) : \"Reducers may not dispatch actions.\");\n }\n try {\n isDispatching = true;\n currentState = currentReducer(currentState, action);\n } finally {\n isDispatching = false;\n }\n const listeners = currentListeners = nextListeners;\n listeners.forEach((listener) => {\n listener();\n });\n return action;\n }\n function replaceReducer(nextReducer) {\n if (typeof nextReducer !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(10) : `Expected the nextReducer to be a function. Instead, received: '${kindOf(nextReducer)}`);\n }\n currentReducer = nextReducer;\n dispatch({\n type: actionTypes_default.REPLACE\n });\n }\n function observable() {\n const outerSubscribe = subscribe;\n return {\n /**\n * The minimal observable subscription method.\n * @param observer Any object that can be used as an observer.\n * The observer object should have a `next` method.\n * @returns An object with an `unsubscribe` method that can\n * be used to unsubscribe the observable from the store, and prevent further\n * emission of values from the observable.\n */\n subscribe(observer) {\n if (typeof observer !== \"object\" || observer === null) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(11) : `Expected the observer to be an object. Instead, received: '${kindOf(observer)}'`);\n }\n function observeState() {\n const observerAsObserver = observer;\n if (observerAsObserver.next) {\n observerAsObserver.next(getState());\n }\n }\n observeState();\n const unsubscribe = outerSubscribe(observeState);\n return {\n unsubscribe\n };\n },\n [symbol_observable_default]() {\n return this;\n }\n };\n }\n dispatch({\n type: actionTypes_default.INIT\n });\n const store = {\n dispatch,\n subscribe,\n getState,\n replaceReducer,\n [symbol_observable_default]: observable\n };\n return store;\n}\nfunction legacy_createStore(reducer, preloadedState, enhancer) {\n return createStore(reducer, preloadedState, enhancer);\n}\n\n// src/utils/warning.ts\nfunction warning(message) {\n if (typeof console !== \"undefined\" && typeof console.error === \"function\") {\n console.error(message);\n }\n try {\n throw new Error(message);\n } catch (e) {\n }\n}\n\n// src/combineReducers.ts\nfunction getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {\n const reducerKeys = Object.keys(reducers);\n const argumentName = action && action.type === actionTypes_default.INIT ? \"preloadedState argument passed to createStore\" : \"previous state received by the reducer\";\n if (reducerKeys.length === 0) {\n return \"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.\";\n }\n if (!isPlainObject(inputState)) {\n return `The ${argumentName} has unexpected type of \"${kindOf(inputState)}\". Expected argument to be an object with the following keys: \"${reducerKeys.join('\", \"')}\"`;\n }\n const unexpectedKeys = Object.keys(inputState).filter((key) => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]);\n unexpectedKeys.forEach((key) => {\n unexpectedKeyCache[key] = true;\n });\n if (action && action.type === actionTypes_default.REPLACE)\n return;\n if (unexpectedKeys.length > 0) {\n return `Unexpected ${unexpectedKeys.length > 1 ? \"keys\" : \"key\"} \"${unexpectedKeys.join('\", \"')}\" found in ${argumentName}. Expected to find one of the known reducer keys instead: \"${reducerKeys.join('\", \"')}\". Unexpected keys will be ignored.`;\n }\n}\nfunction assertReducerShape(reducers) {\n Object.keys(reducers).forEach((key) => {\n const reducer = reducers[key];\n const initialState = reducer(void 0, {\n type: actionTypes_default.INIT\n });\n if (typeof initialState === \"undefined\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(12) : `The slice reducer for key \"${key}\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);\n }\n if (typeof reducer(void 0, {\n type: actionTypes_default.PROBE_UNKNOWN_ACTION()\n }) === \"undefined\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(13) : `The slice reducer for key \"${key}\" returned undefined when probed with a random type. Don't try to handle '${actionTypes_default.INIT}' or other actions in \"redux/*\" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`);\n }\n });\n}\nfunction combineReducers(reducers) {\n const reducerKeys = Object.keys(reducers);\n const finalReducers = {};\n for (let i = 0; i < reducerKeys.length; i++) {\n const key = reducerKeys[i];\n if (process.env.NODE_ENV !== \"production\") {\n if (typeof reducers[key] === \"undefined\") {\n warning(`No reducer provided for key \"${key}\"`);\n }\n }\n if (typeof reducers[key] === \"function\") {\n finalReducers[key] = reducers[key];\n }\n }\n const finalReducerKeys = Object.keys(finalReducers);\n let unexpectedKeyCache;\n if (process.env.NODE_ENV !== \"production\") {\n unexpectedKeyCache = {};\n }\n let shapeAssertionError;\n try {\n assertReducerShape(finalReducers);\n } catch (e) {\n shapeAssertionError = e;\n }\n return function combination(state = {}, action) {\n if (shapeAssertionError) {\n throw shapeAssertionError;\n }\n if (process.env.NODE_ENV !== \"production\") {\n const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);\n if (warningMessage) {\n warning(warningMessage);\n }\n }\n let hasChanged = false;\n const nextState = {};\n for (let i = 0; i < finalReducerKeys.length; i++) {\n const key = finalReducerKeys[i];\n const reducer = finalReducers[key];\n const previousStateForKey = state[key];\n const nextStateForKey = reducer(previousStateForKey, action);\n if (typeof nextStateForKey === \"undefined\") {\n const actionType = action && action.type;\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(14) : `When called with an action of type ${actionType ? `\"${String(actionType)}\"` : \"(unknown type)\"}, the slice reducer for key \"${key}\" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`);\n }\n nextState[key] = nextStateForKey;\n hasChanged = hasChanged || nextStateForKey !== previousStateForKey;\n }\n hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;\n return hasChanged ? nextState : state;\n };\n}\n\n// src/bindActionCreators.ts\nfunction bindActionCreator(actionCreator, dispatch) {\n return function(...args) {\n return dispatch(actionCreator.apply(this, args));\n };\n}\nfunction bindActionCreators(actionCreators, dispatch) {\n if (typeof actionCreators === \"function\") {\n return bindActionCreator(actionCreators, dispatch);\n }\n if (typeof actionCreators !== \"object\" || actionCreators === null) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(16) : `bindActionCreators expected an object or a function, but instead received: '${kindOf(actionCreators)}'. Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?`);\n }\n const boundActionCreators = {};\n for (const key in actionCreators) {\n const actionCreator = actionCreators[key];\n if (typeof actionCreator === \"function\") {\n boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);\n }\n }\n return boundActionCreators;\n}\n\n// src/compose.ts\nfunction compose(...funcs) {\n if (funcs.length === 0) {\n return (arg) => arg;\n }\n if (funcs.length === 1) {\n return funcs[0];\n }\n return funcs.reduce((a, b) => (...args) => a(b(...args)));\n}\n\n// src/applyMiddleware.ts\nfunction applyMiddleware(...middlewares) {\n return (createStore2) => (reducer, preloadedState) => {\n const store = createStore2(reducer, preloadedState);\n let dispatch = () => {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(15) : \"Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.\");\n };\n const middlewareAPI = {\n getState: store.getState,\n dispatch: (action, ...args) => dispatch(action, ...args)\n };\n const chain = middlewares.map((middleware) => middleware(middlewareAPI));\n dispatch = compose(...chain)(store.dispatch);\n return {\n ...store,\n dispatch\n };\n };\n}\n\n// src/utils/isAction.ts\nfunction isAction(action) {\n return isPlainObject(action) && \"type\" in action && typeof action.type === \"string\";\n}\nexport {\n actionTypes_default as __DO_NOT_USE__ActionTypes,\n applyMiddleware,\n bindActionCreators,\n combineReducers,\n compose,\n createStore,\n isAction,\n isPlainObject,\n legacy_createStore\n};\n//# sourceMappingURL=redux.mjs.map","// src/utils/env.ts\nvar NOTHING = Symbol.for(\"immer-nothing\");\nvar DRAFTABLE = Symbol.for(\"immer-draftable\");\nvar DRAFT_STATE = Symbol.for(\"immer-state\");\n\n// src/utils/errors.ts\nvar errors = process.env.NODE_ENV !== \"production\" ? [\n // All error codes, starting by 0:\n function(plugin) {\n return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`;\n },\n function(thing) {\n return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;\n },\n \"This object has been frozen and should not be mutated\",\n function(data) {\n return \"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" + data;\n },\n \"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n \"Immer forbids circular references\",\n \"The first or second argument to `produce` must be a function\",\n \"The third argument to `produce` must be a function or undefined\",\n \"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n \"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n function(thing) {\n return `'current' expects a draft, got: ${thing}`;\n },\n \"Object.defineProperty() cannot be used on an Immer draft\",\n \"Object.setPrototypeOf() cannot be used on an Immer draft\",\n \"Immer only supports deleting array indices\",\n \"Immer only supports setting array indices and the 'length' property\",\n function(thing) {\n return `'original' expects a draft, got: ${thing}`;\n }\n // Note: if more errors are added, the errorOffset in Patches.ts should be increased\n // See Patches.ts for additional errors\n] : [];\nfunction die(error, ...args) {\n if (process.env.NODE_ENV !== \"production\") {\n const e = errors[error];\n const msg = typeof e === \"function\" ? e.apply(null, args) : e;\n throw new Error(`[Immer] ${msg}`);\n }\n throw new Error(\n `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`\n );\n}\n\n// src/utils/common.ts\nvar getPrototypeOf = Object.getPrototypeOf;\nfunction isDraft(value) {\n return !!value && !!value[DRAFT_STATE];\n}\nfunction isDraftable(value) {\n if (!value)\n return false;\n return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap(value) || isSet(value);\n}\nvar objectCtorString = Object.prototype.constructor.toString();\nfunction isPlainObject(value) {\n if (!value || typeof value !== \"object\")\n return false;\n const proto = getPrototypeOf(value);\n if (proto === null) {\n return true;\n }\n const Ctor = Object.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n if (Ctor === Object)\n return true;\n return typeof Ctor == \"function\" && Function.toString.call(Ctor) === objectCtorString;\n}\nfunction original(value) {\n if (!isDraft(value))\n die(15, value);\n return value[DRAFT_STATE].base_;\n}\nfunction each(obj, iter) {\n if (getArchtype(obj) === 0 /* Object */) {\n Reflect.ownKeys(obj).forEach((key) => {\n iter(key, obj[key], obj);\n });\n } else {\n obj.forEach((entry, index) => iter(index, entry, obj));\n }\n}\nfunction getArchtype(thing) {\n const state = thing[DRAFT_STATE];\n return state ? state.type_ : Array.isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;\n}\nfunction has(thing, prop) {\n return getArchtype(thing) === 2 /* Map */ ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);\n}\nfunction get(thing, prop) {\n return getArchtype(thing) === 2 /* Map */ ? thing.get(prop) : thing[prop];\n}\nfunction set(thing, propOrOldValue, value) {\n const t = getArchtype(thing);\n if (t === 2 /* Map */)\n thing.set(propOrOldValue, value);\n else if (t === 3 /* Set */) {\n thing.add(value);\n } else\n thing[propOrOldValue] = value;\n}\nfunction is(x, y) {\n if (x === y) {\n return x !== 0 || 1 / x === 1 / y;\n } else {\n return x !== x && y !== y;\n }\n}\nfunction isMap(target) {\n return target instanceof Map;\n}\nfunction isSet(target) {\n return target instanceof Set;\n}\nfunction latest(state) {\n return state.copy_ || state.base_;\n}\nfunction shallowCopy(base, strict) {\n if (isMap(base)) {\n return new Map(base);\n }\n if (isSet(base)) {\n return new Set(base);\n }\n if (Array.isArray(base))\n return Array.prototype.slice.call(base);\n const isPlain = isPlainObject(base);\n if (strict === true || strict === \"class_only\" && !isPlain) {\n const descriptors = Object.getOwnPropertyDescriptors(base);\n delete descriptors[DRAFT_STATE];\n let keys = Reflect.ownKeys(descriptors);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n const desc = descriptors[key];\n if (desc.writable === false) {\n desc.writable = true;\n desc.configurable = true;\n }\n if (desc.get || desc.set)\n descriptors[key] = {\n configurable: true,\n writable: true,\n // could live with !!desc.set as well here...\n enumerable: desc.enumerable,\n value: base[key]\n };\n }\n return Object.create(getPrototypeOf(base), descriptors);\n } else {\n const proto = getPrototypeOf(base);\n if (proto !== null && isPlain) {\n return { ...base };\n }\n const obj = Object.create(proto);\n return Object.assign(obj, base);\n }\n}\nfunction freeze(obj, deep = false) {\n if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))\n return obj;\n if (getArchtype(obj) > 1) {\n obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;\n }\n Object.freeze(obj);\n if (deep)\n Object.entries(obj).forEach(([key, value]) => freeze(value, true));\n return obj;\n}\nfunction dontMutateFrozenCollections() {\n die(2);\n}\nfunction isFrozen(obj) {\n return Object.isFrozen(obj);\n}\n\n// src/utils/plugins.ts\nvar plugins = {};\nfunction getPlugin(pluginKey) {\n const plugin = plugins[pluginKey];\n if (!plugin) {\n die(0, pluginKey);\n }\n return plugin;\n}\nfunction loadPlugin(pluginKey, implementation) {\n if (!plugins[pluginKey])\n plugins[pluginKey] = implementation;\n}\n\n// src/core/scope.ts\nvar currentScope;\nfunction getCurrentScope() {\n return currentScope;\n}\nfunction createScope(parent_, immer_) {\n return {\n drafts_: [],\n parent_,\n immer_,\n // Whenever the modified draft contains a draft from another scope, we\n // need to prevent auto-freezing so the unowned draft can be finalized.\n canAutoFreeze_: true,\n unfinalizedDrafts_: 0\n };\n}\nfunction usePatchesInScope(scope, patchListener) {\n if (patchListener) {\n getPlugin(\"Patches\");\n scope.patches_ = [];\n scope.inversePatches_ = [];\n scope.patchListener_ = patchListener;\n }\n}\nfunction revokeScope(scope) {\n leaveScope(scope);\n scope.drafts_.forEach(revokeDraft);\n scope.drafts_ = null;\n}\nfunction leaveScope(scope) {\n if (scope === currentScope) {\n currentScope = scope.parent_;\n }\n}\nfunction enterScope(immer2) {\n return currentScope = createScope(currentScope, immer2);\n}\nfunction revokeDraft(draft) {\n const state = draft[DRAFT_STATE];\n if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)\n state.revoke_();\n else\n state.revoked_ = true;\n}\n\n// src/core/finalize.ts\nfunction processResult(result, scope) {\n scope.unfinalizedDrafts_ = scope.drafts_.length;\n const baseDraft = scope.drafts_[0];\n const isReplaced = result !== void 0 && result !== baseDraft;\n if (isReplaced) {\n if (baseDraft[DRAFT_STATE].modified_) {\n revokeScope(scope);\n die(4);\n }\n if (isDraftable(result)) {\n result = finalize(scope, result);\n if (!scope.parent_)\n maybeFreeze(scope, result);\n }\n if (scope.patches_) {\n getPlugin(\"Patches\").generateReplacementPatches_(\n baseDraft[DRAFT_STATE].base_,\n result,\n scope.patches_,\n scope.inversePatches_\n );\n }\n } else {\n result = finalize(scope, baseDraft, []);\n }\n revokeScope(scope);\n if (scope.patches_) {\n scope.patchListener_(scope.patches_, scope.inversePatches_);\n }\n return result !== NOTHING ? result : void 0;\n}\nfunction finalize(rootScope, value, path) {\n if (isFrozen(value))\n return value;\n const state = value[DRAFT_STATE];\n if (!state) {\n each(\n value,\n (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path)\n );\n return value;\n }\n if (state.scope_ !== rootScope)\n return value;\n if (!state.modified_) {\n maybeFreeze(rootScope, state.base_, true);\n return state.base_;\n }\n if (!state.finalized_) {\n state.finalized_ = true;\n state.scope_.unfinalizedDrafts_--;\n const result = state.copy_;\n let resultEach = result;\n let isSet2 = false;\n if (state.type_ === 3 /* Set */) {\n resultEach = new Set(result);\n result.clear();\n isSet2 = true;\n }\n each(\n resultEach,\n (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path, isSet2)\n );\n maybeFreeze(rootScope, result, false);\n if (path && rootScope.patches_) {\n getPlugin(\"Patches\").generatePatches_(\n state,\n path,\n rootScope.patches_,\n rootScope.inversePatches_\n );\n }\n }\n return state.copy_;\n}\nfunction finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {\n if (process.env.NODE_ENV !== \"production\" && childValue === targetObject)\n die(5);\n if (isDraft(childValue)) {\n const path = rootPath && parentState && parentState.type_ !== 3 /* Set */ && // Set objects are atomic since they have no keys.\n !has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0;\n const res = finalize(rootScope, childValue, path);\n set(targetObject, prop, res);\n if (isDraft(res)) {\n rootScope.canAutoFreeze_ = false;\n } else\n return;\n } else if (targetIsSet) {\n targetObject.add(childValue);\n }\n if (isDraftable(childValue) && !isFrozen(childValue)) {\n if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n return;\n }\n finalize(rootScope, childValue);\n if ((!parentState || !parentState.scope_.parent_) && typeof prop !== \"symbol\" && Object.prototype.propertyIsEnumerable.call(targetObject, prop))\n maybeFreeze(rootScope, childValue);\n }\n}\nfunction maybeFreeze(scope, value, deep = false) {\n if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n freeze(value, deep);\n }\n}\n\n// src/core/proxy.ts\nfunction createProxyProxy(base, parent) {\n const isArray = Array.isArray(base);\n const state = {\n type_: isArray ? 1 /* Array */ : 0 /* Object */,\n // Track which produce call this is associated with.\n scope_: parent ? parent.scope_ : getCurrentScope(),\n // True for both shallow and deep changes.\n modified_: false,\n // Used during finalization.\n finalized_: false,\n // Track which properties have been assigned (true) or deleted (false).\n assigned_: {},\n // The parent draft state.\n parent_: parent,\n // The base state.\n base_: base,\n // The base proxy.\n draft_: null,\n // set below\n // The base copy with any updated values.\n copy_: null,\n // Called by the `produce` function.\n revoke_: null,\n isManual_: false\n };\n let target = state;\n let traps = objectTraps;\n if (isArray) {\n target = [state];\n traps = arrayTraps;\n }\n const { revoke, proxy } = Proxy.revocable(target, traps);\n state.draft_ = proxy;\n state.revoke_ = revoke;\n return proxy;\n}\nvar objectTraps = {\n get(state, prop) {\n if (prop === DRAFT_STATE)\n return state;\n const source = latest(state);\n if (!has(source, prop)) {\n return readPropFromProto(state, source, prop);\n }\n const value = source[prop];\n if (state.finalized_ || !isDraftable(value)) {\n return value;\n }\n if (value === peek(state.base_, prop)) {\n prepareCopy(state);\n return state.copy_[prop] = createProxy(value, state);\n }\n return value;\n },\n has(state, prop) {\n return prop in latest(state);\n },\n ownKeys(state) {\n return Reflect.ownKeys(latest(state));\n },\n set(state, prop, value) {\n const desc = getDescriptorFromProto(latest(state), prop);\n if (desc?.set) {\n desc.set.call(state.draft_, value);\n return true;\n }\n if (!state.modified_) {\n const current2 = peek(latest(state), prop);\n const currentState = current2?.[DRAFT_STATE];\n if (currentState && currentState.base_ === value) {\n state.copy_[prop] = value;\n state.assigned_[prop] = false;\n return true;\n }\n if (is(value, current2) && (value !== void 0 || has(state.base_, prop)))\n return true;\n prepareCopy(state);\n markChanged(state);\n }\n if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'\n (value !== void 0 || prop in state.copy_) || // special case: NaN\n Number.isNaN(value) && Number.isNaN(state.copy_[prop]))\n return true;\n state.copy_[prop] = value;\n state.assigned_[prop] = true;\n return true;\n },\n deleteProperty(state, prop) {\n if (peek(state.base_, prop) !== void 0 || prop in state.base_) {\n state.assigned_[prop] = false;\n prepareCopy(state);\n markChanged(state);\n } else {\n delete state.assigned_[prop];\n }\n if (state.copy_) {\n delete state.copy_[prop];\n }\n return true;\n },\n // Note: We never coerce `desc.value` into an Immer draft, because we can't make\n // the same guarantee in ES5 mode.\n getOwnPropertyDescriptor(state, prop) {\n const owner = latest(state);\n const desc = Reflect.getOwnPropertyDescriptor(owner, prop);\n if (!desc)\n return desc;\n return {\n writable: true,\n configurable: state.type_ !== 1 /* Array */ || prop !== \"length\",\n enumerable: desc.enumerable,\n value: owner[prop]\n };\n },\n defineProperty() {\n die(11);\n },\n getPrototypeOf(state) {\n return getPrototypeOf(state.base_);\n },\n setPrototypeOf() {\n die(12);\n }\n};\nvar arrayTraps = {};\neach(objectTraps, (key, fn) => {\n arrayTraps[key] = function() {\n arguments[0] = arguments[0][0];\n return fn.apply(this, arguments);\n };\n});\narrayTraps.deleteProperty = function(state, prop) {\n if (process.env.NODE_ENV !== \"production\" && isNaN(parseInt(prop)))\n die(13);\n return arrayTraps.set.call(this, state, prop, void 0);\n};\narrayTraps.set = function(state, prop, value) {\n if (process.env.NODE_ENV !== \"production\" && prop !== \"length\" && isNaN(parseInt(prop)))\n die(14);\n return objectTraps.set.call(this, state[0], prop, value, state[0]);\n};\nfunction peek(draft, prop) {\n const state = draft[DRAFT_STATE];\n const source = state ? latest(state) : draft;\n return source[prop];\n}\nfunction readPropFromProto(state, source, prop) {\n const desc = getDescriptorFromProto(source, prop);\n return desc ? `value` in desc ? desc.value : (\n // This is a very special case, if the prop is a getter defined by the\n // prototype, we should invoke it with the draft as context!\n desc.get?.call(state.draft_)\n ) : void 0;\n}\nfunction getDescriptorFromProto(source, prop) {\n if (!(prop in source))\n return void 0;\n let proto = getPrototypeOf(source);\n while (proto) {\n const desc = Object.getOwnPropertyDescriptor(proto, prop);\n if (desc)\n return desc;\n proto = getPrototypeOf(proto);\n }\n return void 0;\n}\nfunction markChanged(state) {\n if (!state.modified_) {\n state.modified_ = true;\n if (state.parent_) {\n markChanged(state.parent_);\n }\n }\n}\nfunction prepareCopy(state) {\n if (!state.copy_) {\n state.copy_ = shallowCopy(\n state.base_,\n state.scope_.immer_.useStrictShallowCopy_\n );\n }\n}\n\n// src/core/immerClass.ts\nvar Immer2 = class {\n constructor(config) {\n this.autoFreeze_ = true;\n this.useStrictShallowCopy_ = false;\n /**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\n this.produce = (base, recipe, patchListener) => {\n if (typeof base === \"function\" && typeof recipe !== \"function\") {\n const defaultBase = recipe;\n recipe = base;\n const self = this;\n return function curriedProduce(base2 = defaultBase, ...args) {\n return self.produce(base2, (draft) => recipe.call(this, draft, ...args));\n };\n }\n if (typeof recipe !== \"function\")\n die(6);\n if (patchListener !== void 0 && typeof patchListener !== \"function\")\n die(7);\n let result;\n if (isDraftable(base)) {\n const scope = enterScope(this);\n const proxy = createProxy(base, void 0);\n let hasError = true;\n try {\n result = recipe(proxy);\n hasError = false;\n } finally {\n if (hasError)\n revokeScope(scope);\n else\n leaveScope(scope);\n }\n usePatchesInScope(scope, patchListener);\n return processResult(result, scope);\n } else if (!base || typeof base !== \"object\") {\n result = recipe(base);\n if (result === void 0)\n result = base;\n if (result === NOTHING)\n result = void 0;\n if (this.autoFreeze_)\n freeze(result, true);\n if (patchListener) {\n const p = [];\n const ip = [];\n getPlugin(\"Patches\").generateReplacementPatches_(base, result, p, ip);\n patchListener(p, ip);\n }\n return result;\n } else\n die(1, base);\n };\n this.produceWithPatches = (base, recipe) => {\n if (typeof base === \"function\") {\n return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));\n }\n let patches, inversePatches;\n const result = this.produce(base, recipe, (p, ip) => {\n patches = p;\n inversePatches = ip;\n });\n return [result, patches, inversePatches];\n };\n if (typeof config?.autoFreeze === \"boolean\")\n this.setAutoFreeze(config.autoFreeze);\n if (typeof config?.useStrictShallowCopy === \"boolean\")\n this.setUseStrictShallowCopy(config.useStrictShallowCopy);\n }\n createDraft(base) {\n if (!isDraftable(base))\n die(8);\n if (isDraft(base))\n base = current(base);\n const scope = enterScope(this);\n const proxy = createProxy(base, void 0);\n proxy[DRAFT_STATE].isManual_ = true;\n leaveScope(scope);\n return proxy;\n }\n finishDraft(draft, patchListener) {\n const state = draft && draft[DRAFT_STATE];\n if (!state || !state.isManual_)\n die(9);\n const { scope_: scope } = state;\n usePatchesInScope(scope, patchListener);\n return processResult(void 0, scope);\n }\n /**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * By default, auto-freezing is enabled.\n */\n setAutoFreeze(value) {\n this.autoFreeze_ = value;\n }\n /**\n * Pass true to enable strict shallow copy.\n *\n * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n */\n setUseStrictShallowCopy(value) {\n this.useStrictShallowCopy_ = value;\n }\n applyPatches(base, patches) {\n let i;\n for (i = patches.length - 1; i >= 0; i--) {\n const patch = patches[i];\n if (patch.path.length === 0 && patch.op === \"replace\") {\n base = patch.value;\n break;\n }\n }\n if (i > -1) {\n patches = patches.slice(i + 1);\n }\n const applyPatchesImpl = getPlugin(\"Patches\").applyPatches_;\n if (isDraft(base)) {\n return applyPatchesImpl(base, patches);\n }\n return this.produce(\n base,\n (draft) => applyPatchesImpl(draft, patches)\n );\n }\n};\nfunction createProxy(value, parent) {\n const draft = isMap(value) ? getPlugin(\"MapSet\").proxyMap_(value, parent) : isSet(value) ? getPlugin(\"MapSet\").proxySet_(value, parent) : createProxyProxy(value, parent);\n const scope = parent ? parent.scope_ : getCurrentScope();\n scope.drafts_.push(draft);\n return draft;\n}\n\n// src/core/current.ts\nfunction current(value) {\n if (!isDraft(value))\n die(10, value);\n return currentImpl(value);\n}\nfunction currentImpl(value) {\n if (!isDraftable(value) || isFrozen(value))\n return value;\n const state = value[DRAFT_STATE];\n let copy;\n if (state) {\n if (!state.modified_)\n return state.base_;\n state.finalized_ = true;\n copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);\n } else {\n copy = shallowCopy(value, true);\n }\n each(copy, (key, childValue) => {\n set(copy, key, currentImpl(childValue));\n });\n if (state) {\n state.finalized_ = false;\n }\n return copy;\n}\n\n// src/plugins/patches.ts\nfunction enablePatches() {\n const errorOffset = 16;\n if (process.env.NODE_ENV !== \"production\") {\n errors.push(\n 'Sets cannot have \"replace\" patches.',\n function(op) {\n return \"Unsupported patch operation: \" + op;\n },\n function(path) {\n return \"Cannot apply patch, path doesn't resolve: \" + path;\n },\n \"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n );\n }\n const REPLACE = \"replace\";\n const ADD = \"add\";\n const REMOVE = \"remove\";\n function generatePatches_(state, basePath, patches, inversePatches) {\n switch (state.type_) {\n case 0 /* Object */:\n case 2 /* Map */:\n return generatePatchesFromAssigned(\n state,\n basePath,\n patches,\n inversePatches\n );\n case 1 /* Array */:\n return generateArrayPatches(state, basePath, patches, inversePatches);\n case 3 /* Set */:\n return generateSetPatches(\n state,\n basePath,\n patches,\n inversePatches\n );\n }\n }\n function generateArrayPatches(state, basePath, patches, inversePatches) {\n let { base_, assigned_ } = state;\n let copy_ = state.copy_;\n if (copy_.length < base_.length) {\n ;\n [base_, copy_] = [copy_, base_];\n [patches, inversePatches] = [inversePatches, patches];\n }\n for (let i = 0; i < base_.length; i++) {\n if (assigned_[i] && copy_[i] !== base_[i]) {\n const path = basePath.concat([i]);\n patches.push({\n op: REPLACE,\n path,\n // Need to maybe clone it, as it can in fact be the original value\n // due to the base/copy inversion at the start of this function\n value: clonePatchValueIfNeeded(copy_[i])\n });\n inversePatches.push({\n op: REPLACE,\n path,\n value: clonePatchValueIfNeeded(base_[i])\n });\n }\n }\n for (let i = base_.length; i < copy_.length; i++) {\n const path = basePath.concat([i]);\n patches.push({\n op: ADD,\n path,\n // Need to maybe clone it, as it can in fact be the original value\n // due to the base/copy inversion at the start of this function\n value: clonePatchValueIfNeeded(copy_[i])\n });\n }\n for (let i = copy_.length - 1; base_.length <= i; --i) {\n const path = basePath.concat([i]);\n inversePatches.push({\n op: REMOVE,\n path\n });\n }\n }\n function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {\n const { base_, copy_ } = state;\n each(state.assigned_, (key, assignedValue) => {\n const origValue = get(base_, key);\n const value = get(copy_, key);\n const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;\n if (origValue === value && op === REPLACE)\n return;\n const path = basePath.concat(key);\n patches.push(op === REMOVE ? { op, path } : { op, path, value });\n inversePatches.push(\n op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) }\n );\n });\n }\n function generateSetPatches(state, basePath, patches, inversePatches) {\n let { base_, copy_ } = state;\n let i = 0;\n base_.forEach((value) => {\n if (!copy_.has(value)) {\n const path = basePath.concat([i]);\n patches.push({\n op: REMOVE,\n path,\n value\n });\n inversePatches.unshift({\n op: ADD,\n path,\n value\n });\n }\n i++;\n });\n i = 0;\n copy_.forEach((value) => {\n if (!base_.has(value)) {\n const path = basePath.concat([i]);\n patches.push({\n op: ADD,\n path,\n value\n });\n inversePatches.unshift({\n op: REMOVE,\n path,\n value\n });\n }\n i++;\n });\n }\n function generateReplacementPatches_(baseValue, replacement, patches, inversePatches) {\n patches.push({\n op: REPLACE,\n path: [],\n value: replacement === NOTHING ? void 0 : replacement\n });\n inversePatches.push({\n op: REPLACE,\n path: [],\n value: baseValue\n });\n }\n function applyPatches_(draft, patches) {\n patches.forEach((patch) => {\n const { path, op } = patch;\n let base = draft;\n for (let i = 0; i < path.length - 1; i++) {\n const parentType = getArchtype(base);\n let p = path[i];\n if (typeof p !== \"string\" && typeof p !== \"number\") {\n p = \"\" + p;\n }\n if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === \"__proto__\" || p === \"constructor\"))\n die(errorOffset + 3);\n if (typeof base === \"function\" && p === \"prototype\")\n die(errorOffset + 3);\n base = get(base, p);\n if (typeof base !== \"object\")\n die(errorOffset + 2, path.join(\"/\"));\n }\n const type = getArchtype(base);\n const value = deepClonePatchValue(patch.value);\n const key = path[path.length - 1];\n switch (op) {\n case REPLACE:\n switch (type) {\n case 2 /* Map */:\n return base.set(key, value);\n case 3 /* Set */:\n die(errorOffset);\n default:\n return base[key] = value;\n }\n case ADD:\n switch (type) {\n case 1 /* Array */:\n return key === \"-\" ? base.push(value) : base.splice(key, 0, value);\n case 2 /* Map */:\n return base.set(key, value);\n case 3 /* Set */:\n return base.add(value);\n default:\n return base[key] = value;\n }\n case REMOVE:\n switch (type) {\n case 1 /* Array */:\n return base.splice(key, 1);\n case 2 /* Map */:\n return base.delete(key);\n case 3 /* Set */:\n return base.delete(patch.value);\n default:\n return delete base[key];\n }\n default:\n die(errorOffset + 1, op);\n }\n });\n return draft;\n }\n function deepClonePatchValue(obj) {\n if (!isDraftable(obj))\n return obj;\n if (Array.isArray(obj))\n return obj.map(deepClonePatchValue);\n if (isMap(obj))\n return new Map(\n Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n );\n if (isSet(obj))\n return new Set(Array.from(obj).map(deepClonePatchValue));\n const cloned = Object.create(getPrototypeOf(obj));\n for (const key in obj)\n cloned[key] = deepClonePatchValue(obj[key]);\n if (has(obj, DRAFTABLE))\n cloned[DRAFTABLE] = obj[DRAFTABLE];\n return cloned;\n }\n function clonePatchValueIfNeeded(obj) {\n if (isDraft(obj)) {\n return deepClonePatchValue(obj);\n } else\n return obj;\n }\n loadPlugin(\"Patches\", {\n applyPatches_,\n generatePatches_,\n generateReplacementPatches_\n });\n}\n\n// src/plugins/mapset.ts\nfunction enableMapSet() {\n class DraftMap extends Map {\n constructor(target, parent) {\n super();\n this[DRAFT_STATE] = {\n type_: 2 /* Map */,\n parent_: parent,\n scope_: parent ? parent.scope_ : getCurrentScope(),\n modified_: false,\n finalized_: false,\n copy_: void 0,\n assigned_: void 0,\n base_: target,\n draft_: this,\n isManual_: false,\n revoked_: false\n };\n }\n get size() {\n return latest(this[DRAFT_STATE]).size;\n }\n has(key) {\n return latest(this[DRAFT_STATE]).has(key);\n }\n set(key, value) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (!latest(state).has(key) || latest(state).get(key) !== value) {\n prepareMapCopy(state);\n markChanged(state);\n state.assigned_.set(key, true);\n state.copy_.set(key, value);\n state.assigned_.set(key, true);\n }\n return this;\n }\n delete(key) {\n if (!this.has(key)) {\n return false;\n }\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareMapCopy(state);\n markChanged(state);\n if (state.base_.has(key)) {\n state.assigned_.set(key, false);\n } else {\n state.assigned_.delete(key);\n }\n state.copy_.delete(key);\n return true;\n }\n clear() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (latest(state).size) {\n prepareMapCopy(state);\n markChanged(state);\n state.assigned_ = /* @__PURE__ */ new Map();\n each(state.base_, (key) => {\n state.assigned_.set(key, false);\n });\n state.copy_.clear();\n }\n }\n forEach(cb, thisArg) {\n const state = this[DRAFT_STATE];\n latest(state).forEach((_value, key, _map) => {\n cb.call(thisArg, this.get(key), key, this);\n });\n }\n get(key) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n const value = latest(state).get(key);\n if (state.finalized_ || !isDraftable(value)) {\n return value;\n }\n if (value !== state.base_.get(key)) {\n return value;\n }\n const draft = createProxy(value, state);\n prepareMapCopy(state);\n state.copy_.set(key, draft);\n return draft;\n }\n keys() {\n return latest(this[DRAFT_STATE]).keys();\n }\n values() {\n const iterator = this.keys();\n return {\n [Symbol.iterator]: () => this.values(),\n next: () => {\n const r = iterator.next();\n if (r.done)\n return r;\n const value = this.get(r.value);\n return {\n done: false,\n value\n };\n }\n };\n }\n entries() {\n const iterator = this.keys();\n return {\n [Symbol.iterator]: () => this.entries(),\n next: () => {\n const r = iterator.next();\n if (r.done)\n return r;\n const value = this.get(r.value);\n return {\n done: false,\n value: [r.value, value]\n };\n }\n };\n }\n [(DRAFT_STATE, Symbol.iterator)]() {\n return this.entries();\n }\n }\n function proxyMap_(target, parent) {\n return new DraftMap(target, parent);\n }\n function prepareMapCopy(state) {\n if (!state.copy_) {\n state.assigned_ = /* @__PURE__ */ new Map();\n state.copy_ = new Map(state.base_);\n }\n }\n class DraftSet extends Set {\n constructor(target, parent) {\n super();\n this[DRAFT_STATE] = {\n type_: 3 /* Set */,\n parent_: parent,\n scope_: parent ? parent.scope_ : getCurrentScope(),\n modified_: false,\n finalized_: false,\n copy_: void 0,\n base_: target,\n draft_: this,\n drafts_: /* @__PURE__ */ new Map(),\n revoked_: false,\n isManual_: false\n };\n }\n get size() {\n return latest(this[DRAFT_STATE]).size;\n }\n has(value) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (!state.copy_) {\n return state.base_.has(value);\n }\n if (state.copy_.has(value))\n return true;\n if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n return true;\n return false;\n }\n add(value) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (!this.has(value)) {\n prepareSetCopy(state);\n markChanged(state);\n state.copy_.add(value);\n }\n return this;\n }\n delete(value) {\n if (!this.has(value)) {\n return false;\n }\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareSetCopy(state);\n markChanged(state);\n return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) : (\n /* istanbul ignore next */\n false\n ));\n }\n clear() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (latest(state).size) {\n prepareSetCopy(state);\n markChanged(state);\n state.copy_.clear();\n }\n }\n values() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareSetCopy(state);\n return state.copy_.values();\n }\n entries() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareSetCopy(state);\n return state.copy_.entries();\n }\n keys() {\n return this.values();\n }\n [(DRAFT_STATE, Symbol.iterator)]() {\n return this.values();\n }\n forEach(cb, thisArg) {\n const iterator = this.values();\n let result = iterator.next();\n while (!result.done) {\n cb.call(thisArg, result.value, result.value, this);\n result = iterator.next();\n }\n }\n }\n function proxySet_(target, parent) {\n return new DraftSet(target, parent);\n }\n function prepareSetCopy(state) {\n if (!state.copy_) {\n state.copy_ = /* @__PURE__ */ new Set();\n state.base_.forEach((value) => {\n if (isDraftable(value)) {\n const draft = createProxy(value, state);\n state.drafts_.set(value, draft);\n state.copy_.add(draft);\n } else {\n state.copy_.add(value);\n }\n });\n }\n }\n function assertUnrevoked(state) {\n if (state.revoked_)\n die(3, JSON.stringify(latest(state)));\n }\n loadPlugin(\"MapSet\", { proxyMap_, proxySet_ });\n}\n\n// src/immer.ts\nvar immer = new Immer2();\nvar produce = immer.produce;\nvar produceWithPatches = immer.produceWithPatches.bind(\n immer\n);\nvar setAutoFreeze = immer.setAutoFreeze.bind(immer);\nvar setUseStrictShallowCopy = immer.setUseStrictShallowCopy.bind(immer);\nvar applyPatches = immer.applyPatches.bind(immer);\nvar createDraft = immer.createDraft.bind(immer);\nvar finishDraft = immer.finishDraft.bind(immer);\nfunction castDraft(value) {\n return value;\n}\nfunction castImmutable(value) {\n return value;\n}\nexport {\n Immer2 as Immer,\n applyPatches,\n castDraft,\n castImmutable,\n createDraft,\n current,\n enableMapSet,\n enablePatches,\n finishDraft,\n freeze,\n DRAFTABLE as immerable,\n isDraft,\n isDraftable,\n NOTHING as nothing,\n original,\n produce,\n produceWithPatches,\n setAutoFreeze,\n setUseStrictShallowCopy\n};\n//# sourceMappingURL=immer.mjs.map","// src/devModeChecks/identityFunctionCheck.ts\nvar runIdentityFunctionCheck = (resultFunc, inputSelectorsResults, outputSelectorResult) => {\n if (inputSelectorsResults.length === 1 && inputSelectorsResults[0] === outputSelectorResult) {\n let isInputSameAsOutput = false;\n try {\n const emptyObject = {};\n if (resultFunc(emptyObject) === emptyObject)\n isInputSameAsOutput = true;\n } catch {\n }\n if (isInputSameAsOutput) {\n let stack = void 0;\n try {\n throw new Error();\n } catch (e) {\n ;\n ({ stack } = e);\n }\n console.warn(\n \"The result function returned its own inputs without modification. e.g\\n`createSelector([state => state.todos], todos => todos)`\\nThis could lead to inefficient memoization and unnecessary re-renders.\\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.\",\n { stack }\n );\n }\n }\n};\n\n// src/devModeChecks/inputStabilityCheck.ts\nvar runInputStabilityCheck = (inputSelectorResultsObject, options, inputSelectorArgs) => {\n const { memoize, memoizeOptions } = options;\n const { inputSelectorResults, inputSelectorResultsCopy } = inputSelectorResultsObject;\n const createAnEmptyObject = memoize(() => ({}), ...memoizeOptions);\n const areInputSelectorResultsEqual = createAnEmptyObject.apply(null, inputSelectorResults) === createAnEmptyObject.apply(null, inputSelectorResultsCopy);\n if (!areInputSelectorResultsEqual) {\n let stack = void 0;\n try {\n throw new Error();\n } catch (e) {\n ;\n ({ stack } = e);\n }\n console.warn(\n \"An input selector returned a different result when passed same arguments.\\nThis means your output selector will likely run more frequently than intended.\\nAvoid returning a new reference inside your input selector, e.g.\\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`\",\n {\n arguments: inputSelectorArgs,\n firstInputs: inputSelectorResults,\n secondInputs: inputSelectorResultsCopy,\n stack\n }\n );\n }\n};\n\n// src/devModeChecks/setGlobalDevModeChecks.ts\nvar globalDevModeChecks = {\n inputStabilityCheck: \"once\",\n identityFunctionCheck: \"once\"\n};\nvar setGlobalDevModeChecks = (devModeChecks) => {\n Object.assign(globalDevModeChecks, devModeChecks);\n};\n\n// src/utils.ts\nvar NOT_FOUND = \"NOT_FOUND\";\nfunction assertIsFunction(func, errorMessage = `expected a function, instead received ${typeof func}`) {\n if (typeof func !== \"function\") {\n throw new TypeError(errorMessage);\n }\n}\nfunction assertIsObject(object, errorMessage = `expected an object, instead received ${typeof object}`) {\n if (typeof object !== \"object\") {\n throw new TypeError(errorMessage);\n }\n}\nfunction assertIsArrayOfFunctions(array, errorMessage = `expected all items to be functions, instead received the following types: `) {\n if (!array.every((item) => typeof item === \"function\")) {\n const itemTypes = array.map(\n (item) => typeof item === \"function\" ? `function ${item.name || \"unnamed\"}()` : typeof item\n ).join(\", \");\n throw new TypeError(`${errorMessage}[${itemTypes}]`);\n }\n}\nvar ensureIsArray = (item) => {\n return Array.isArray(item) ? item : [item];\n};\nfunction getDependencies(createSelectorArgs) {\n const dependencies = Array.isArray(createSelectorArgs[0]) ? createSelectorArgs[0] : createSelectorArgs;\n assertIsArrayOfFunctions(\n dependencies,\n `createSelector expects all input-selectors to be functions, but received the following types: `\n );\n return dependencies;\n}\nfunction collectInputSelectorResults(dependencies, inputSelectorArgs) {\n const inputSelectorResults = [];\n const { length } = dependencies;\n for (let i = 0; i < length; i++) {\n inputSelectorResults.push(dependencies[i].apply(null, inputSelectorArgs));\n }\n return inputSelectorResults;\n}\nvar getDevModeChecksExecutionInfo = (firstRun, devModeChecks) => {\n const { identityFunctionCheck, inputStabilityCheck } = {\n ...globalDevModeChecks,\n ...devModeChecks\n };\n return {\n identityFunctionCheck: {\n shouldRun: identityFunctionCheck === \"always\" || identityFunctionCheck === \"once\" && firstRun,\n run: runIdentityFunctionCheck\n },\n inputStabilityCheck: {\n shouldRun: inputStabilityCheck === \"always\" || inputStabilityCheck === \"once\" && firstRun,\n run: runInputStabilityCheck\n }\n };\n};\n\n// src/autotrackMemoize/autotracking.ts\nvar $REVISION = 0;\nvar CURRENT_TRACKER = null;\nvar Cell = class {\n revision = $REVISION;\n _value;\n _lastValue;\n _isEqual = tripleEq;\n constructor(initialValue, isEqual = tripleEq) {\n this._value = this._lastValue = initialValue;\n this._isEqual = isEqual;\n }\n // Whenever a storage value is read, it'll add itself to the current tracker if\n // one exists, entangling its state with that cache.\n get value() {\n CURRENT_TRACKER?.add(this);\n return this._value;\n }\n // Whenever a storage value is updated, we bump the global revision clock,\n // assign the revision for this storage to the new value, _and_ we schedule a\n // rerender. This is important, and it's what makes autotracking _pull_\n // based. We don't actively tell the caches which depend on the storage that\n // anything has happened. Instead, we recompute the caches when needed.\n set value(newValue) {\n if (this.value === newValue)\n return;\n this._value = newValue;\n this.revision = ++$REVISION;\n }\n};\nfunction tripleEq(a, b) {\n return a === b;\n}\nvar TrackingCache = class {\n _cachedValue;\n _cachedRevision = -1;\n _deps = [];\n hits = 0;\n fn;\n constructor(fn) {\n this.fn = fn;\n }\n clear() {\n this._cachedValue = void 0;\n this._cachedRevision = -1;\n this._deps = [];\n this.hits = 0;\n }\n get value() {\n if (this.revision > this._cachedRevision) {\n const { fn } = this;\n const currentTracker = /* @__PURE__ */ new Set();\n const prevTracker = CURRENT_TRACKER;\n CURRENT_TRACKER = currentTracker;\n this._cachedValue = fn();\n CURRENT_TRACKER = prevTracker;\n this.hits++;\n this._deps = Array.from(currentTracker);\n this._cachedRevision = this.revision;\n }\n CURRENT_TRACKER?.add(this);\n return this._cachedValue;\n }\n get revision() {\n return Math.max(...this._deps.map((d) => d.revision), 0);\n }\n};\nfunction getValue(cell) {\n if (!(cell instanceof Cell)) {\n console.warn(\"Not a valid cell! \", cell);\n }\n return cell.value;\n}\nfunction setValue(storage, value) {\n if (!(storage instanceof Cell)) {\n throw new TypeError(\n \"setValue must be passed a tracked store created with `createStorage`.\"\n );\n }\n storage.value = storage._lastValue = value;\n}\nfunction createCell(initialValue, isEqual = tripleEq) {\n return new Cell(initialValue, isEqual);\n}\nfunction createCache(fn) {\n assertIsFunction(\n fn,\n \"the first parameter to `createCache` must be a function\"\n );\n return new TrackingCache(fn);\n}\n\n// src/autotrackMemoize/tracking.ts\nvar neverEq = (a, b) => false;\nfunction createTag() {\n return createCell(null, neverEq);\n}\nfunction dirtyTag(tag, value) {\n setValue(tag, value);\n}\nvar consumeCollection = (node) => {\n let tag = node.collectionTag;\n if (tag === null) {\n tag = node.collectionTag = createTag();\n }\n getValue(tag);\n};\nvar dirtyCollection = (node) => {\n const tag = node.collectionTag;\n if (tag !== null) {\n dirtyTag(tag, null);\n }\n};\n\n// src/autotrackMemoize/proxy.ts\nvar REDUX_PROXY_LABEL = Symbol();\nvar nextId = 0;\nvar proto = Object.getPrototypeOf({});\nvar ObjectTreeNode = class {\n constructor(value) {\n this.value = value;\n this.value = value;\n this.tag.value = value;\n }\n proxy = new Proxy(this, objectProxyHandler);\n tag = createTag();\n tags = {};\n children = {};\n collectionTag = null;\n id = nextId++;\n};\nvar objectProxyHandler = {\n get(node, key) {\n function calculateResult() {\n const { value } = node;\n const childValue = Reflect.get(value, key);\n if (typeof key === \"symbol\") {\n return childValue;\n }\n if (key in proto) {\n return childValue;\n }\n if (typeof childValue === \"object\" && childValue !== null) {\n let childNode = node.children[key];\n if (childNode === void 0) {\n childNode = node.children[key] = createNode(childValue);\n }\n if (childNode.tag) {\n getValue(childNode.tag);\n }\n return childNode.proxy;\n } else {\n let tag = node.tags[key];\n if (tag === void 0) {\n tag = node.tags[key] = createTag();\n tag.value = childValue;\n }\n getValue(tag);\n return childValue;\n }\n }\n const res = calculateResult();\n return res;\n },\n ownKeys(node) {\n consumeCollection(node);\n return Reflect.ownKeys(node.value);\n },\n getOwnPropertyDescriptor(node, prop) {\n return Reflect.getOwnPropertyDescriptor(node.value, prop);\n },\n has(node, prop) {\n return Reflect.has(node.value, prop);\n }\n};\nvar ArrayTreeNode = class {\n constructor(value) {\n this.value = value;\n this.value = value;\n this.tag.value = value;\n }\n proxy = new Proxy([this], arrayProxyHandler);\n tag = createTag();\n tags = {};\n children = {};\n collectionTag = null;\n id = nextId++;\n};\nvar arrayProxyHandler = {\n get([node], key) {\n if (key === \"length\") {\n consumeCollection(node);\n }\n return objectProxyHandler.get(node, key);\n },\n ownKeys([node]) {\n return objectProxyHandler.ownKeys(node);\n },\n getOwnPropertyDescriptor([node], prop) {\n return objectProxyHandler.getOwnPropertyDescriptor(node, prop);\n },\n has([node], prop) {\n return objectProxyHandler.has(node, prop);\n }\n};\nfunction createNode(value) {\n if (Array.isArray(value)) {\n return new ArrayTreeNode(value);\n }\n return new ObjectTreeNode(value);\n}\nfunction updateNode(node, newValue) {\n const { value, tags, children } = node;\n node.value = newValue;\n if (Array.isArray(value) && Array.isArray(newValue) && value.length !== newValue.length) {\n dirtyCollection(node);\n } else {\n if (value !== newValue) {\n let oldKeysSize = 0;\n let newKeysSize = 0;\n let anyKeysAdded = false;\n for (const _key in value) {\n oldKeysSize++;\n }\n for (const key in newValue) {\n newKeysSize++;\n if (!(key in value)) {\n anyKeysAdded = true;\n break;\n }\n }\n const isDifferent = anyKeysAdded || oldKeysSize !== newKeysSize;\n if (isDifferent) {\n dirtyCollection(node);\n }\n }\n }\n for (const key in tags) {\n const childValue = value[key];\n const newChildValue = newValue[key];\n if (childValue !== newChildValue) {\n dirtyCollection(node);\n dirtyTag(tags[key], newChildValue);\n }\n if (typeof newChildValue === \"object\" && newChildValue !== null) {\n delete tags[key];\n }\n }\n for (const key in children) {\n const childNode = children[key];\n const newChildValue = newValue[key];\n const childValue = childNode.value;\n if (childValue === newChildValue) {\n continue;\n } else if (typeof newChildValue === \"object\" && newChildValue !== null) {\n updateNode(childNode, newChildValue);\n } else {\n deleteNode(childNode);\n delete children[key];\n }\n }\n}\nfunction deleteNode(node) {\n if (node.tag) {\n dirtyTag(node.tag, null);\n }\n dirtyCollection(node);\n for (const key in node.tags) {\n dirtyTag(node.tags[key], null);\n }\n for (const key in node.children) {\n deleteNode(node.children[key]);\n }\n}\n\n// src/lruMemoize.ts\nfunction createSingletonCache(equals) {\n let entry;\n return {\n get(key) {\n if (entry && equals(entry.key, key)) {\n return entry.value;\n }\n return NOT_FOUND;\n },\n put(key, value) {\n entry = { key, value };\n },\n getEntries() {\n return entry ? [entry] : [];\n },\n clear() {\n entry = void 0;\n }\n };\n}\nfunction createLruCache(maxSize, equals) {\n let entries = [];\n function get(key) {\n const cacheIndex = entries.findIndex((entry) => equals(key, entry.key));\n if (cacheIndex > -1) {\n const entry = entries[cacheIndex];\n if (cacheIndex > 0) {\n entries.splice(cacheIndex, 1);\n entries.unshift(entry);\n }\n return entry.value;\n }\n return NOT_FOUND;\n }\n function put(key, value) {\n if (get(key) === NOT_FOUND) {\n entries.unshift({ key, value });\n if (entries.length > maxSize) {\n entries.pop();\n }\n }\n }\n function getEntries() {\n return entries;\n }\n function clear() {\n entries = [];\n }\n return { get, put, getEntries, clear };\n}\nvar referenceEqualityCheck = (a, b) => a === b;\nfunction createCacheKeyComparator(equalityCheck) {\n return function areArgumentsShallowlyEqual(prev, next) {\n if (prev === null || next === null || prev.length !== next.length) {\n return false;\n }\n const { length } = prev;\n for (let i = 0; i < length; i++) {\n if (!equalityCheck(prev[i], next[i])) {\n return false;\n }\n }\n return true;\n };\n}\nfunction lruMemoize(func, equalityCheckOrOptions) {\n const providedOptions = typeof equalityCheckOrOptions === \"object\" ? equalityCheckOrOptions : { equalityCheck: equalityCheckOrOptions };\n const {\n equalityCheck = referenceEqualityCheck,\n maxSize = 1,\n resultEqualityCheck\n } = providedOptions;\n const comparator = createCacheKeyComparator(equalityCheck);\n let resultsCount = 0;\n const cache = maxSize === 1 ? createSingletonCache(comparator) : createLruCache(maxSize, comparator);\n function memoized() {\n let value = cache.get(arguments);\n if (value === NOT_FOUND) {\n value = func.apply(null, arguments);\n resultsCount++;\n if (resultEqualityCheck) {\n const entries = cache.getEntries();\n const matchingEntry = entries.find(\n (entry) => resultEqualityCheck(entry.value, value)\n );\n if (matchingEntry) {\n value = matchingEntry.value;\n resultsCount !== 0 && resultsCount--;\n }\n }\n cache.put(arguments, value);\n }\n return value;\n }\n memoized.clearCache = () => {\n cache.clear();\n memoized.resetResultsCount();\n };\n memoized.resultsCount = () => resultsCount;\n memoized.resetResultsCount = () => {\n resultsCount = 0;\n };\n return memoized;\n}\n\n// src/autotrackMemoize/autotrackMemoize.ts\nfunction autotrackMemoize(func) {\n const node = createNode(\n []\n );\n let lastArgs = null;\n const shallowEqual = createCacheKeyComparator(referenceEqualityCheck);\n const cache = createCache(() => {\n const res = func.apply(null, node.proxy);\n return res;\n });\n function memoized() {\n if (!shallowEqual(lastArgs, arguments)) {\n updateNode(node, arguments);\n lastArgs = arguments;\n }\n return cache.value;\n }\n memoized.clearCache = () => {\n return cache.clear();\n };\n return memoized;\n}\n\n// src/weakMapMemoize.ts\nvar StrongRef = class {\n constructor(value) {\n this.value = value;\n }\n deref() {\n return this.value;\n }\n};\nvar Ref = typeof WeakRef !== \"undefined\" ? WeakRef : StrongRef;\nvar UNTERMINATED = 0;\nvar TERMINATED = 1;\nfunction createCacheNode() {\n return {\n s: UNTERMINATED,\n v: void 0,\n o: null,\n p: null\n };\n}\nfunction weakMapMemoize(func, options = {}) {\n let fnNode = createCacheNode();\n const { resultEqualityCheck } = options;\n let lastResult;\n let resultsCount = 0;\n function memoized() {\n let cacheNode = fnNode;\n const { length } = arguments;\n for (let i = 0, l = length; i < l; i++) {\n const arg = arguments[i];\n if (typeof arg === \"function\" || typeof arg === \"object\" && arg !== null) {\n let objectCache = cacheNode.o;\n if (objectCache === null) {\n cacheNode.o = objectCache = /* @__PURE__ */ new WeakMap();\n }\n const objectNode = objectCache.get(arg);\n if (objectNode === void 0) {\n cacheNode = createCacheNode();\n objectCache.set(arg, cacheNode);\n } else {\n cacheNode = objectNode;\n }\n } else {\n let primitiveCache = cacheNode.p;\n if (primitiveCache === null) {\n cacheNode.p = primitiveCache = /* @__PURE__ */ new Map();\n }\n const primitiveNode = primitiveCache.get(arg);\n if (primitiveNode === void 0) {\n cacheNode = createCacheNode();\n primitiveCache.set(arg, cacheNode);\n } else {\n cacheNode = primitiveNode;\n }\n }\n }\n const terminatedNode = cacheNode;\n let result;\n if (cacheNode.s === TERMINATED) {\n result = cacheNode.v;\n } else {\n result = func.apply(null, arguments);\n resultsCount++;\n }\n terminatedNode.s = TERMINATED;\n if (resultEqualityCheck) {\n const lastResultValue = lastResult?.deref?.() ?? lastResult;\n if (lastResultValue != null && resultEqualityCheck(lastResultValue, result)) {\n result = lastResultValue;\n resultsCount !== 0 && resultsCount--;\n }\n const needsWeakRef = typeof result === \"object\" && result !== null || typeof result === \"function\";\n lastResult = needsWeakRef ? new Ref(result) : result;\n }\n terminatedNode.v = result;\n return result;\n }\n memoized.clearCache = () => {\n fnNode = createCacheNode();\n memoized.resetResultsCount();\n };\n memoized.resultsCount = () => resultsCount;\n memoized.resetResultsCount = () => {\n resultsCount = 0;\n };\n return memoized;\n}\n\n// src/createSelectorCreator.ts\nfunction createSelectorCreator(memoizeOrOptions, ...memoizeOptionsFromArgs) {\n const createSelectorCreatorOptions = typeof memoizeOrOptions === \"function\" ? {\n memoize: memoizeOrOptions,\n memoizeOptions: memoizeOptionsFromArgs\n } : memoizeOrOptions;\n const createSelector2 = (...createSelectorArgs) => {\n let recomputations = 0;\n let dependencyRecomputations = 0;\n let lastResult;\n let directlyPassedOptions = {};\n let resultFunc = createSelectorArgs.pop();\n if (typeof resultFunc === \"object\") {\n directlyPassedOptions = resultFunc;\n resultFunc = createSelectorArgs.pop();\n }\n assertIsFunction(\n resultFunc,\n `createSelector expects an output function after the inputs, but received: [${typeof resultFunc}]`\n );\n const combinedOptions = {\n ...createSelectorCreatorOptions,\n ...directlyPassedOptions\n };\n const {\n memoize,\n memoizeOptions = [],\n argsMemoize = weakMapMemoize,\n argsMemoizeOptions = [],\n devModeChecks = {}\n } = combinedOptions;\n const finalMemoizeOptions = ensureIsArray(memoizeOptions);\n const finalArgsMemoizeOptions = ensureIsArray(argsMemoizeOptions);\n const dependencies = getDependencies(createSelectorArgs);\n const memoizedResultFunc = memoize(function recomputationWrapper() {\n recomputations++;\n return resultFunc.apply(\n null,\n arguments\n );\n }, ...finalMemoizeOptions);\n let firstRun = true;\n const selector = argsMemoize(function dependenciesChecker() {\n dependencyRecomputations++;\n const inputSelectorResults = collectInputSelectorResults(\n dependencies,\n arguments\n );\n lastResult = memoizedResultFunc.apply(null, inputSelectorResults);\n if (process.env.NODE_ENV !== \"production\") {\n const { identityFunctionCheck, inputStabilityCheck } = getDevModeChecksExecutionInfo(firstRun, devModeChecks);\n if (identityFunctionCheck.shouldRun) {\n identityFunctionCheck.run(\n resultFunc,\n inputSelectorResults,\n lastResult\n );\n }\n if (inputStabilityCheck.shouldRun) {\n const inputSelectorResultsCopy = collectInputSelectorResults(\n dependencies,\n arguments\n );\n inputStabilityCheck.run(\n { inputSelectorResults, inputSelectorResultsCopy },\n { memoize, memoizeOptions: finalMemoizeOptions },\n arguments\n );\n }\n if (firstRun)\n firstRun = false;\n }\n return lastResult;\n }, ...finalArgsMemoizeOptions);\n return Object.assign(selector, {\n resultFunc,\n memoizedResultFunc,\n dependencies,\n dependencyRecomputations: () => dependencyRecomputations,\n resetDependencyRecomputations: () => {\n dependencyRecomputations = 0;\n },\n lastResult: () => lastResult,\n recomputations: () => recomputations,\n resetRecomputations: () => {\n recomputations = 0;\n },\n memoize,\n argsMemoize\n });\n };\n Object.assign(createSelector2, {\n withTypes: () => createSelector2\n });\n return createSelector2;\n}\nvar createSelector = /* @__PURE__ */ createSelectorCreator(weakMapMemoize);\n\n// src/createStructuredSelector.ts\nvar createStructuredSelector = Object.assign(\n (inputSelectorsObject, selectorCreator = createSelector) => {\n assertIsObject(\n inputSelectorsObject,\n `createStructuredSelector expects first argument to be an object where each property is a selector, instead received a ${typeof inputSelectorsObject}`\n );\n const inputSelectorKeys = Object.keys(inputSelectorsObject);\n const dependencies = inputSelectorKeys.map(\n (key) => inputSelectorsObject[key]\n );\n const structuredSelector = selectorCreator(\n dependencies,\n (...inputSelectorResults) => {\n return inputSelectorResults.reduce((composition, value, index) => {\n composition[inputSelectorKeys[index]] = value;\n return composition;\n }, {});\n }\n );\n return structuredSelector;\n },\n { withTypes: () => createStructuredSelector }\n);\nexport {\n createSelector,\n createSelectorCreator,\n createStructuredSelector,\n lruMemoize,\n referenceEqualityCheck,\n setGlobalDevModeChecks,\n autotrackMemoize as unstable_autotrackMemoize,\n weakMapMemoize\n};\n//# sourceMappingURL=reselect.mjs.map","// src/index.ts\nfunction createThunkMiddleware(extraArgument) {\n const middleware = ({ dispatch, getState }) => (next) => (action) => {\n if (typeof action === \"function\") {\n return action(dispatch, getState, extraArgument);\n }\n return next(action);\n };\n return middleware;\n}\nvar thunk = createThunkMiddleware();\nvar withExtraArgument = createThunkMiddleware;\nexport {\n thunk,\n withExtraArgument\n};\n","// src/index.ts\nexport * from \"redux\";\nimport { produce, current as current4, freeze, original as original2, isDraft as isDraft6 } from \"immer\";\nimport { createSelector, createSelectorCreator as createSelectorCreator2, lruMemoize, weakMapMemoize as weakMapMemoize2 } from \"reselect\";\n\n// src/createDraftSafeSelector.ts\nimport { current, isDraft } from \"immer\";\nimport { createSelectorCreator, weakMapMemoize } from \"reselect\";\nvar createDraftSafeSelectorCreator = (...args) => {\n const createSelector2 = createSelectorCreator(...args);\n const createDraftSafeSelector2 = Object.assign((...args2) => {\n const selector = createSelector2(...args2);\n const wrappedSelector = (value, ...rest) => selector(isDraft(value) ? current(value) : value, ...rest);\n Object.assign(wrappedSelector, selector);\n return wrappedSelector;\n }, {\n withTypes: () => createDraftSafeSelector2\n });\n return createDraftSafeSelector2;\n};\nvar createDraftSafeSelector = createDraftSafeSelectorCreator(weakMapMemoize);\n\n// src/configureStore.ts\nimport { applyMiddleware, createStore, compose as compose2, combineReducers, isPlainObject as isPlainObject2 } from \"redux\";\n\n// src/devtoolsExtension.ts\nimport { compose } from \"redux\";\nvar composeWithDevTools = typeof window !== \"undefined\" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() {\n if (arguments.length === 0)\n return void 0;\n if (typeof arguments[0] === \"object\")\n return compose;\n return compose.apply(null, arguments);\n};\nvar devToolsEnhancer = typeof window !== \"undefined\" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function() {\n return function(noop3) {\n return noop3;\n };\n};\n\n// src/getDefaultMiddleware.ts\nimport { thunk as thunkMiddleware, withExtraArgument } from \"redux-thunk\";\n\n// src/createAction.ts\nimport { isAction } from \"redux\";\n\n// src/tsHelpers.ts\nvar hasMatchFunction = (v) => {\n return v && typeof v.match === \"function\";\n};\n\n// src/createAction.ts\nfunction createAction(type, prepareAction) {\n function actionCreator(...args) {\n if (prepareAction) {\n let prepared = prepareAction(...args);\n if (!prepared) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(0) : \"prepareAction did not return an object\");\n }\n return {\n type,\n payload: prepared.payload,\n ...\"meta\" in prepared && {\n meta: prepared.meta\n },\n ...\"error\" in prepared && {\n error: prepared.error\n }\n };\n }\n return {\n type,\n payload: args[0]\n };\n }\n actionCreator.toString = () => `${type}`;\n actionCreator.type = type;\n actionCreator.match = (action) => isAction(action) && action.type === type;\n return actionCreator;\n}\nfunction isActionCreator(action) {\n return typeof action === \"function\" && \"type\" in action && // hasMatchFunction only wants Matchers but I don't see the point in rewriting it\n hasMatchFunction(action);\n}\nfunction isFSA(action) {\n return isAction(action) && Object.keys(action).every(isValidKey);\n}\nfunction isValidKey(key) {\n return [\"type\", \"payload\", \"error\", \"meta\"].indexOf(key) > -1;\n}\n\n// src/actionCreatorInvariantMiddleware.ts\nfunction getMessage(type) {\n const splitType = type ? `${type}`.split(\"/\") : [];\n const actionName = splitType[splitType.length - 1] || \"actionCreator\";\n return `Detected an action creator with type \"${type || \"unknown\"}\" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \\`dispatch(${actionName}())\\` instead of \\`dispatch(${actionName})\\`. This is necessary even if the action has no payload.`;\n}\nfunction createActionCreatorInvariantMiddleware(options = {}) {\n if (process.env.NODE_ENV === \"production\") {\n return () => (next) => (action) => next(action);\n }\n const {\n isActionCreator: isActionCreator2 = isActionCreator\n } = options;\n return () => (next) => (action) => {\n if (isActionCreator2(action)) {\n console.warn(getMessage(action.type));\n }\n return next(action);\n };\n}\n\n// src/utils.ts\nimport { produce as createNextState, isDraftable } from \"immer\";\nfunction getTimeMeasureUtils(maxDelay, fnName) {\n let elapsed = 0;\n return {\n measureTime(fn) {\n const started = Date.now();\n try {\n return fn();\n } finally {\n const finished = Date.now();\n elapsed += finished - started;\n }\n },\n warnIfExceeded() {\n if (elapsed > maxDelay) {\n console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`);\n }\n }\n };\n}\nfunction find(iterable, comparator) {\n for (const entry of iterable) {\n if (comparator(entry)) {\n return entry;\n }\n }\n return void 0;\n}\nvar Tuple = class _Tuple extends Array {\n constructor(...items) {\n super(...items);\n Object.setPrototypeOf(this, _Tuple.prototype);\n }\n static get [Symbol.species]() {\n return _Tuple;\n }\n concat(...arr) {\n return super.concat.apply(this, arr);\n }\n prepend(...arr) {\n if (arr.length === 1 && Array.isArray(arr[0])) {\n return new _Tuple(...arr[0].concat(this));\n }\n return new _Tuple(...arr.concat(this));\n }\n};\nfunction freezeDraftable(val) {\n return isDraftable(val) ? createNextState(val, () => {\n }) : val;\n}\nfunction emplace(map, key, handler) {\n if (map.has(key)) {\n let value = map.get(key);\n if (handler.update) {\n value = handler.update(value, key, map);\n map.set(key, value);\n }\n return value;\n }\n if (!handler.insert)\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(10) : \"No insert provided for key not already in map\");\n const inserted = handler.insert(key, map);\n map.set(key, inserted);\n return inserted;\n}\n\n// src/immutableStateInvariantMiddleware.ts\nfunction isImmutableDefault(value) {\n return typeof value !== \"object\" || value == null || Object.isFrozen(value);\n}\nfunction trackForMutations(isImmutable, ignorePaths, obj) {\n const trackedProperties = trackProperties(isImmutable, ignorePaths, obj);\n return {\n detectMutations() {\n return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);\n }\n };\n}\nfunction trackProperties(isImmutable, ignorePaths = [], obj, path = \"\", checkedObjects = /* @__PURE__ */ new Set()) {\n const tracked = {\n value: obj\n };\n if (!isImmutable(obj) && !checkedObjects.has(obj)) {\n checkedObjects.add(obj);\n tracked.children = {};\n for (const key in obj) {\n const childPath = path ? path + \".\" + key : key;\n if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {\n continue;\n }\n tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);\n }\n }\n return tracked;\n}\nfunction detectMutations(isImmutable, ignoredPaths = [], trackedProperty, obj, sameParentRef = false, path = \"\") {\n const prevObj = trackedProperty ? trackedProperty.value : void 0;\n const sameRef = prevObj === obj;\n if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\n return {\n wasMutated: true,\n path\n };\n }\n if (isImmutable(prevObj) || isImmutable(obj)) {\n return {\n wasMutated: false\n };\n }\n const keysToDetect = {};\n for (let key in trackedProperty.children) {\n keysToDetect[key] = true;\n }\n for (let key in obj) {\n keysToDetect[key] = true;\n }\n const hasIgnoredPaths = ignoredPaths.length > 0;\n for (let key in keysToDetect) {\n const nestedPath = path ? path + \".\" + key : key;\n if (hasIgnoredPaths) {\n const hasMatches = ignoredPaths.some((ignored) => {\n if (ignored instanceof RegExp) {\n return ignored.test(nestedPath);\n }\n return nestedPath === ignored;\n });\n if (hasMatches) {\n continue;\n }\n }\n const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);\n if (result.wasMutated) {\n return result;\n }\n }\n return {\n wasMutated: false\n };\n}\nfunction createImmutableStateInvariantMiddleware(options = {}) {\n if (process.env.NODE_ENV === \"production\") {\n return () => (next) => (action) => next(action);\n } else {\n let stringify2 = function(obj, serializer, indent, decycler) {\n return JSON.stringify(obj, getSerialize2(serializer, decycler), indent);\n }, getSerialize2 = function(serializer, decycler) {\n let stack = [], keys = [];\n if (!decycler)\n decycler = function(_, value) {\n if (stack[0] === value)\n return \"[Circular ~]\";\n return \"[Circular ~.\" + keys.slice(0, stack.indexOf(value)).join(\".\") + \"]\";\n };\n return function(key, value) {\n if (stack.length > 0) {\n var thisPos = stack.indexOf(this);\n ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\n ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\n if (~stack.indexOf(value))\n value = decycler.call(this, key, value);\n } else\n stack.push(value);\n return serializer == null ? value : serializer.call(this, key, value);\n };\n };\n var stringify = stringify2, getSerialize = getSerialize2;\n let {\n isImmutable = isImmutableDefault,\n ignoredPaths,\n warnAfter = 32\n } = options;\n const track = trackForMutations.bind(null, isImmutable, ignoredPaths);\n return ({\n getState\n }) => {\n let state = getState();\n let tracker = track(state);\n let result;\n return (next) => (action) => {\n const measureUtils = getTimeMeasureUtils(warnAfter, \"ImmutableStateInvariantMiddleware\");\n measureUtils.measureTime(() => {\n state = getState();\n result = tracker.detectMutations();\n tracker = track(state);\n if (result.wasMutated) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || \"\"}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n }\n });\n const dispatchedAction = next(action);\n measureUtils.measureTime(() => {\n state = getState();\n result = tracker.detectMutations();\n tracker = track(state);\n if (result.wasMutated) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || \"\"}. Take a look at the reducer(s) handling the action ${stringify2(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n }\n });\n measureUtils.warnIfExceeded();\n return dispatchedAction;\n };\n };\n }\n}\n\n// src/serializableStateInvariantMiddleware.ts\nimport { isAction as isAction2, isPlainObject } from \"redux\";\nfunction isPlain(val) {\n const type = typeof val;\n return val == null || type === \"string\" || type === \"boolean\" || type === \"number\" || Array.isArray(val) || isPlainObject(val);\n}\nfunction findNonSerializableValue(value, path = \"\", isSerializable = isPlain, getEntries, ignoredPaths = [], cache) {\n let foundNestedSerializable;\n if (!isSerializable(value)) {\n return {\n keyPath: path || \"\",\n value\n };\n }\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n if (cache?.has(value))\n return false;\n const entries = getEntries != null ? getEntries(value) : Object.entries(value);\n const hasIgnoredPaths = ignoredPaths.length > 0;\n for (const [key, nestedValue] of entries) {\n const nestedPath = path ? path + \".\" + key : key;\n if (hasIgnoredPaths) {\n const hasMatches = ignoredPaths.some((ignored) => {\n if (ignored instanceof RegExp) {\n return ignored.test(nestedPath);\n }\n return nestedPath === ignored;\n });\n if (hasMatches) {\n continue;\n }\n }\n if (!isSerializable(nestedValue)) {\n return {\n keyPath: nestedPath,\n value: nestedValue\n };\n }\n if (typeof nestedValue === \"object\") {\n foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);\n if (foundNestedSerializable) {\n return foundNestedSerializable;\n }\n }\n }\n if (cache && isNestedFrozen(value))\n cache.add(value);\n return false;\n}\nfunction isNestedFrozen(value) {\n if (!Object.isFrozen(value))\n return false;\n for (const nestedValue of Object.values(value)) {\n if (typeof nestedValue !== \"object\" || nestedValue === null)\n continue;\n if (!isNestedFrozen(nestedValue))\n return false;\n }\n return true;\n}\nfunction createSerializableStateInvariantMiddleware(options = {}) {\n if (process.env.NODE_ENV === \"production\") {\n return () => (next) => (action) => next(action);\n } else {\n const {\n isSerializable = isPlain,\n getEntries,\n ignoredActions = [],\n ignoredActionPaths = [\"meta.arg\", \"meta.baseQueryMeta\"],\n ignoredPaths = [],\n warnAfter = 32,\n ignoreState = false,\n ignoreActions = false,\n disableCache = false\n } = options;\n const cache = !disableCache && WeakSet ? /* @__PURE__ */ new WeakSet() : void 0;\n return (storeAPI) => (next) => (action) => {\n if (!isAction2(action)) {\n return next(action);\n }\n const result = next(action);\n const measureUtils = getTimeMeasureUtils(warnAfter, \"SerializableStateInvariantMiddleware\");\n if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {\n measureUtils.measureTime(() => {\n const foundActionNonSerializableValue = findNonSerializableValue(action, \"\", isSerializable, getEntries, ignoredActionPaths, cache);\n if (foundActionNonSerializableValue) {\n const {\n keyPath,\n value\n } = foundActionNonSerializableValue;\n console.error(`A non-serializable value was detected in an action, in the path: \\`${keyPath}\\`. Value:`, value, \"\\nTake a look at the logic that dispatched this action: \", action, \"\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)\", \"\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)\");\n }\n });\n }\n if (!ignoreState) {\n measureUtils.measureTime(() => {\n const state = storeAPI.getState();\n const foundStateNonSerializableValue = findNonSerializableValue(state, \"\", isSerializable, getEntries, ignoredPaths, cache);\n if (foundStateNonSerializableValue) {\n const {\n keyPath,\n value\n } = foundStateNonSerializableValue;\n console.error(`A non-serializable value was detected in the state, in the path: \\`${keyPath}\\`. Value:`, value, `\nTake a look at the reducer(s) handling this action type: ${action.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);\n }\n });\n measureUtils.warnIfExceeded();\n }\n return result;\n };\n }\n}\n\n// src/getDefaultMiddleware.ts\nfunction isBoolean(x) {\n return typeof x === \"boolean\";\n}\nvar buildGetDefaultMiddleware = () => function getDefaultMiddleware(options) {\n const {\n thunk = true,\n immutableCheck = true,\n serializableCheck = true,\n actionCreatorCheck = true\n } = options ?? {};\n let middlewareArray = new Tuple();\n if (thunk) {\n if (isBoolean(thunk)) {\n middlewareArray.push(thunkMiddleware);\n } else {\n middlewareArray.push(withExtraArgument(thunk.extraArgument));\n }\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (immutableCheck) {\n let immutableOptions = {};\n if (!isBoolean(immutableCheck)) {\n immutableOptions = immutableCheck;\n }\n middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));\n }\n if (serializableCheck) {\n let serializableOptions = {};\n if (!isBoolean(serializableCheck)) {\n serializableOptions = serializableCheck;\n }\n middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));\n }\n if (actionCreatorCheck) {\n let actionCreatorOptions = {};\n if (!isBoolean(actionCreatorCheck)) {\n actionCreatorOptions = actionCreatorCheck;\n }\n middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));\n }\n }\n return middlewareArray;\n};\n\n// src/autoBatchEnhancer.ts\nvar SHOULD_AUTOBATCH = \"RTK_autoBatch\";\nvar prepareAutoBatched = () => (payload) => ({\n payload,\n meta: {\n [SHOULD_AUTOBATCH]: true\n }\n});\nvar createQueueWithTimer = (timeout) => {\n return (notify) => {\n setTimeout(notify, timeout);\n };\n};\nvar rAF = typeof window !== \"undefined\" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10);\nvar autoBatchEnhancer = (options = {\n type: \"raf\"\n}) => (next) => (...args) => {\n const store = next(...args);\n let notifying = true;\n let shouldNotifyAtEndOfTick = false;\n let notificationQueued = false;\n const listeners = /* @__PURE__ */ new Set();\n const queueCallback = options.type === \"tick\" ? queueMicrotask : options.type === \"raf\" ? rAF : options.type === \"callback\" ? options.queueNotification : createQueueWithTimer(options.timeout);\n const notifyListeners = () => {\n notificationQueued = false;\n if (shouldNotifyAtEndOfTick) {\n shouldNotifyAtEndOfTick = false;\n listeners.forEach((l) => l());\n }\n };\n return Object.assign({}, store, {\n // Override the base `store.subscribe` method to keep original listeners\n // from running if we're delaying notifications\n subscribe(listener2) {\n const wrappedListener = () => notifying && listener2();\n const unsubscribe = store.subscribe(wrappedListener);\n listeners.add(listener2);\n return () => {\n unsubscribe();\n listeners.delete(listener2);\n };\n },\n // Override the base `store.dispatch` method so that we can check actions\n // for the `shouldAutoBatch` flag and determine if batching is active\n dispatch(action) {\n try {\n notifying = !action?.meta?.[SHOULD_AUTOBATCH];\n shouldNotifyAtEndOfTick = !notifying;\n if (shouldNotifyAtEndOfTick) {\n if (!notificationQueued) {\n notificationQueued = true;\n queueCallback(notifyListeners);\n }\n }\n return store.dispatch(action);\n } finally {\n notifying = true;\n }\n }\n });\n};\n\n// src/getDefaultEnhancers.ts\nvar buildGetDefaultEnhancers = (middlewareEnhancer) => function getDefaultEnhancers(options) {\n const {\n autoBatch = true\n } = options ?? {};\n let enhancerArray = new Tuple(middlewareEnhancer);\n if (autoBatch) {\n enhancerArray.push(autoBatchEnhancer(typeof autoBatch === \"object\" ? autoBatch : void 0));\n }\n return enhancerArray;\n};\n\n// src/configureStore.ts\nvar IS_PRODUCTION = process.env.NODE_ENV === \"production\";\nfunction configureStore(options) {\n const getDefaultMiddleware = buildGetDefaultMiddleware();\n const {\n reducer = void 0,\n middleware,\n devTools = true,\n preloadedState = void 0,\n enhancers = void 0\n } = options || {};\n let rootReducer;\n if (typeof reducer === \"function\") {\n rootReducer = reducer;\n } else if (isPlainObject2(reducer)) {\n rootReducer = combineReducers(reducer);\n } else {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(1) : \"`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers\");\n }\n if (!IS_PRODUCTION && middleware && typeof middleware !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(2) : \"`middleware` field must be a callback\");\n }\n let finalMiddleware;\n if (typeof middleware === \"function\") {\n finalMiddleware = middleware(getDefaultMiddleware);\n if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(3) : \"when using a middleware builder function, an array of middleware must be returned\");\n }\n } else {\n finalMiddleware = getDefaultMiddleware();\n }\n if (!IS_PRODUCTION && finalMiddleware.some((item) => typeof item !== \"function\")) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(4) : \"each middleware provided to configureStore must be a function\");\n }\n let finalCompose = compose2;\n if (devTools) {\n finalCompose = composeWithDevTools({\n // Enable capture of stack traces for dispatched Redux actions\n trace: !IS_PRODUCTION,\n ...typeof devTools === \"object\" && devTools\n });\n }\n const middlewareEnhancer = applyMiddleware(...finalMiddleware);\n const getDefaultEnhancers = buildGetDefaultEnhancers(middlewareEnhancer);\n if (!IS_PRODUCTION && enhancers && typeof enhancers !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(5) : \"`enhancers` field must be a callback\");\n }\n let storeEnhancers = typeof enhancers === \"function\" ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();\n if (!IS_PRODUCTION && !Array.isArray(storeEnhancers)) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(6) : \"`enhancers` callback must return an array\");\n }\n if (!IS_PRODUCTION && storeEnhancers.some((item) => typeof item !== \"function\")) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(7) : \"each enhancer provided to configureStore must be a function\");\n }\n if (!IS_PRODUCTION && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {\n console.error(\"middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`\");\n }\n const composedEnhancer = finalCompose(...storeEnhancers);\n return createStore(rootReducer, preloadedState, composedEnhancer);\n}\n\n// src/createReducer.ts\nimport { produce as createNextState2, isDraft as isDraft2, isDraftable as isDraftable2 } from \"immer\";\n\n// src/mapBuilders.ts\nfunction executeReducerBuilderCallback(builderCallback) {\n const actionsMap = {};\n const actionMatchers = [];\n let defaultCaseReducer;\n const builder = {\n addCase(typeOrActionCreator, reducer) {\n if (process.env.NODE_ENV !== \"production\") {\n if (actionMatchers.length > 0) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(26) : \"`builder.addCase` should only be called before calling `builder.addMatcher`\");\n }\n if (defaultCaseReducer) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(27) : \"`builder.addCase` should only be called before calling `builder.addDefaultCase`\");\n }\n }\n const type = typeof typeOrActionCreator === \"string\" ? typeOrActionCreator : typeOrActionCreator.type;\n if (!type) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(28) : \"`builder.addCase` cannot be called with an empty action type\");\n }\n if (type in actionsMap) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(29) : `\\`builder.addCase\\` cannot be called with two reducers for the same action type '${type}'`);\n }\n actionsMap[type] = reducer;\n return builder;\n },\n addMatcher(matcher, reducer) {\n if (process.env.NODE_ENV !== \"production\") {\n if (defaultCaseReducer) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(30) : \"`builder.addMatcher` should only be called before calling `builder.addDefaultCase`\");\n }\n }\n actionMatchers.push({\n matcher,\n reducer\n });\n return builder;\n },\n addDefaultCase(reducer) {\n if (process.env.NODE_ENV !== \"production\") {\n if (defaultCaseReducer) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(31) : \"`builder.addDefaultCase` can only be called once\");\n }\n }\n defaultCaseReducer = reducer;\n return builder;\n }\n };\n builderCallback(builder);\n return [actionsMap, actionMatchers, defaultCaseReducer];\n}\n\n// src/createReducer.ts\nfunction isStateFunction(x) {\n return typeof x === \"function\";\n}\nfunction createReducer(initialState, mapOrBuilderCallback) {\n if (process.env.NODE_ENV !== \"production\") {\n if (typeof mapOrBuilderCallback === \"object\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(8) : \"The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer\");\n }\n }\n let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);\n let getInitialState;\n if (isStateFunction(initialState)) {\n getInitialState = () => freezeDraftable(initialState());\n } else {\n const frozenInitialState = freezeDraftable(initialState);\n getInitialState = () => frozenInitialState;\n }\n function reducer(state = getInitialState(), action) {\n let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({\n matcher\n }) => matcher(action)).map(({\n reducer: reducer2\n }) => reducer2)];\n if (caseReducers.filter((cr) => !!cr).length === 0) {\n caseReducers = [finalDefaultCaseReducer];\n }\n return caseReducers.reduce((previousState, caseReducer) => {\n if (caseReducer) {\n if (isDraft2(previousState)) {\n const draft = previousState;\n const result = caseReducer(draft, action);\n if (result === void 0) {\n return previousState;\n }\n return result;\n } else if (!isDraftable2(previousState)) {\n const result = caseReducer(previousState, action);\n if (result === void 0) {\n if (previousState === null) {\n return previousState;\n }\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(9) : \"A case reducer on a non-draftable value must not return undefined\");\n }\n return result;\n } else {\n return createNextState2(previousState, (draft) => {\n return caseReducer(draft, action);\n });\n }\n }\n return previousState;\n }, state);\n }\n reducer.getInitialState = getInitialState;\n return reducer;\n}\n\n// src/nanoid.ts\nvar urlAlphabet = \"ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW\";\nvar nanoid = (size = 21) => {\n let id = \"\";\n let i = size;\n while (i--) {\n id += urlAlphabet[Math.random() * 64 | 0];\n }\n return id;\n};\n\n// src/matchers.ts\nvar matches = (matcher, action) => {\n if (hasMatchFunction(matcher)) {\n return matcher.match(action);\n } else {\n return matcher(action);\n }\n};\nfunction isAnyOf(...matchers) {\n return (action) => {\n return matchers.some((matcher) => matches(matcher, action));\n };\n}\nfunction isAllOf(...matchers) {\n return (action) => {\n return matchers.every((matcher) => matches(matcher, action));\n };\n}\nfunction hasExpectedRequestMetadata(action, validStatus) {\n if (!action || !action.meta)\n return false;\n const hasValidRequestId = typeof action.meta.requestId === \"string\";\n const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;\n return hasValidRequestId && hasValidRequestStatus;\n}\nfunction isAsyncThunkArray(a) {\n return typeof a[0] === \"function\" && \"pending\" in a[0] && \"fulfilled\" in a[0] && \"rejected\" in a[0];\n}\nfunction isPending(...asyncThunks) {\n if (asyncThunks.length === 0) {\n return (action) => hasExpectedRequestMetadata(action, [\"pending\"]);\n }\n if (!isAsyncThunkArray(asyncThunks)) {\n return isPending()(asyncThunks[0]);\n }\n return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.pending));\n}\nfunction isRejected(...asyncThunks) {\n if (asyncThunks.length === 0) {\n return (action) => hasExpectedRequestMetadata(action, [\"rejected\"]);\n }\n if (!isAsyncThunkArray(asyncThunks)) {\n return isRejected()(asyncThunks[0]);\n }\n return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.rejected));\n}\nfunction isRejectedWithValue(...asyncThunks) {\n const hasFlag = (action) => {\n return action && action.meta && action.meta.rejectedWithValue;\n };\n if (asyncThunks.length === 0) {\n return isAllOf(isRejected(...asyncThunks), hasFlag);\n }\n if (!isAsyncThunkArray(asyncThunks)) {\n return isRejectedWithValue()(asyncThunks[0]);\n }\n return isAllOf(isRejected(...asyncThunks), hasFlag);\n}\nfunction isFulfilled(...asyncThunks) {\n if (asyncThunks.length === 0) {\n return (action) => hasExpectedRequestMetadata(action, [\"fulfilled\"]);\n }\n if (!isAsyncThunkArray(asyncThunks)) {\n return isFulfilled()(asyncThunks[0]);\n }\n return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.fulfilled));\n}\nfunction isAsyncThunkAction(...asyncThunks) {\n if (asyncThunks.length === 0) {\n return (action) => hasExpectedRequestMetadata(action, [\"pending\", \"fulfilled\", \"rejected\"]);\n }\n if (!isAsyncThunkArray(asyncThunks)) {\n return isAsyncThunkAction()(asyncThunks[0]);\n }\n return isAnyOf(...asyncThunks.flatMap((asyncThunk) => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));\n}\n\n// src/createAsyncThunk.ts\nvar commonProperties = [\"name\", \"message\", \"stack\", \"code\"];\nvar RejectWithValue = class {\n constructor(payload, meta) {\n this.payload = payload;\n this.meta = meta;\n }\n /*\n type-only property to distinguish between RejectWithValue and FulfillWithMeta\n does not exist at runtime\n */\n _type;\n};\nvar FulfillWithMeta = class {\n constructor(payload, meta) {\n this.payload = payload;\n this.meta = meta;\n }\n /*\n type-only property to distinguish between RejectWithValue and FulfillWithMeta\n does not exist at runtime\n */\n _type;\n};\nvar miniSerializeError = (value) => {\n if (typeof value === \"object\" && value !== null) {\n const simpleError = {};\n for (const property of commonProperties) {\n if (typeof value[property] === \"string\") {\n simpleError[property] = value[property];\n }\n }\n return simpleError;\n }\n return {\n message: String(value)\n };\n};\nvar createAsyncThunk = /* @__PURE__ */ (() => {\n function createAsyncThunk2(typePrefix, payloadCreator, options) {\n const fulfilled = createAction(typePrefix + \"/fulfilled\", (payload, requestId, arg, meta) => ({\n payload,\n meta: {\n ...meta || {},\n arg,\n requestId,\n requestStatus: \"fulfilled\"\n }\n }));\n const pending = createAction(typePrefix + \"/pending\", (requestId, arg, meta) => ({\n payload: void 0,\n meta: {\n ...meta || {},\n arg,\n requestId,\n requestStatus: \"pending\"\n }\n }));\n const rejected = createAction(typePrefix + \"/rejected\", (error, requestId, arg, payload, meta) => ({\n payload,\n error: (options && options.serializeError || miniSerializeError)(error || \"Rejected\"),\n meta: {\n ...meta || {},\n arg,\n requestId,\n rejectedWithValue: !!payload,\n requestStatus: \"rejected\",\n aborted: error?.name === \"AbortError\",\n condition: error?.name === \"ConditionError\"\n }\n }));\n function actionCreator(arg) {\n return (dispatch, getState, extra) => {\n const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();\n const abortController = new AbortController();\n let abortHandler;\n let abortReason;\n function abort(reason) {\n abortReason = reason;\n abortController.abort();\n }\n const promise = async function() {\n let finalAction;\n try {\n let conditionResult = options?.condition?.(arg, {\n getState,\n extra\n });\n if (isThenable(conditionResult)) {\n conditionResult = await conditionResult;\n }\n if (conditionResult === false || abortController.signal.aborted) {\n throw {\n name: \"ConditionError\",\n message: \"Aborted due to condition callback returning false.\"\n };\n }\n const abortedPromise = new Promise((_, reject) => {\n abortHandler = () => {\n reject({\n name: \"AbortError\",\n message: abortReason || \"Aborted\"\n });\n };\n abortController.signal.addEventListener(\"abort\", abortHandler);\n });\n dispatch(pending(requestId, arg, options?.getPendingMeta?.({\n requestId,\n arg\n }, {\n getState,\n extra\n })));\n finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {\n dispatch,\n getState,\n extra,\n requestId,\n signal: abortController.signal,\n abort,\n rejectWithValue: (value, meta) => {\n return new RejectWithValue(value, meta);\n },\n fulfillWithValue: (value, meta) => {\n return new FulfillWithMeta(value, meta);\n }\n })).then((result) => {\n if (result instanceof RejectWithValue) {\n throw result;\n }\n if (result instanceof FulfillWithMeta) {\n return fulfilled(result.payload, requestId, arg, result.meta);\n }\n return fulfilled(result, requestId, arg);\n })]);\n } catch (err) {\n finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);\n } finally {\n if (abortHandler) {\n abortController.signal.removeEventListener(\"abort\", abortHandler);\n }\n }\n const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;\n if (!skipDispatch) {\n dispatch(finalAction);\n }\n return finalAction;\n }();\n return Object.assign(promise, {\n abort,\n requestId,\n arg,\n unwrap() {\n return promise.then(unwrapResult);\n }\n });\n };\n }\n return Object.assign(actionCreator, {\n pending,\n rejected,\n fulfilled,\n settled: isAnyOf(rejected, fulfilled),\n typePrefix\n });\n }\n createAsyncThunk2.withTypes = () => createAsyncThunk2;\n return createAsyncThunk2;\n})();\nfunction unwrapResult(action) {\n if (action.meta && action.meta.rejectedWithValue) {\n throw action.payload;\n }\n if (action.error) {\n throw action.error;\n }\n return action.payload;\n}\nfunction isThenable(value) {\n return value !== null && typeof value === \"object\" && typeof value.then === \"function\";\n}\n\n// src/createSlice.ts\nvar asyncThunkSymbol = /* @__PURE__ */ Symbol.for(\"rtk-slice-createasyncthunk\");\nvar asyncThunkCreator = {\n [asyncThunkSymbol]: createAsyncThunk\n};\nvar ReducerType = /* @__PURE__ */ ((ReducerType2) => {\n ReducerType2[\"reducer\"] = \"reducer\";\n ReducerType2[\"reducerWithPrepare\"] = \"reducerWithPrepare\";\n ReducerType2[\"asyncThunk\"] = \"asyncThunk\";\n return ReducerType2;\n})(ReducerType || {});\nfunction getType(slice, actionKey) {\n return `${slice}/${actionKey}`;\n}\nfunction buildCreateSlice({\n creators\n} = {}) {\n const cAT = creators?.asyncThunk?.[asyncThunkSymbol];\n return function createSlice2(options) {\n const {\n name,\n reducerPath = name\n } = options;\n if (!name) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(11) : \"`name` is a required option for createSlice\");\n }\n if (typeof process !== \"undefined\" && process.env.NODE_ENV === \"development\") {\n if (options.initialState === void 0) {\n console.error(\"You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`\");\n }\n }\n const reducers = (typeof options.reducers === \"function\" ? options.reducers(buildReducerCreators()) : options.reducers) || {};\n const reducerNames = Object.keys(reducers);\n const context = {\n sliceCaseReducersByName: {},\n sliceCaseReducersByType: {},\n actionCreators: {},\n sliceMatchers: []\n };\n const contextMethods = {\n addCase(typeOrActionCreator, reducer2) {\n const type = typeof typeOrActionCreator === \"string\" ? typeOrActionCreator : typeOrActionCreator.type;\n if (!type) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(12) : \"`context.addCase` cannot be called with an empty action type\");\n }\n if (type in context.sliceCaseReducersByType) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(13) : \"`context.addCase` cannot be called with two reducers for the same action type: \" + type);\n }\n context.sliceCaseReducersByType[type] = reducer2;\n return contextMethods;\n },\n addMatcher(matcher, reducer2) {\n context.sliceMatchers.push({\n matcher,\n reducer: reducer2\n });\n return contextMethods;\n },\n exposeAction(name2, actionCreator) {\n context.actionCreators[name2] = actionCreator;\n return contextMethods;\n },\n exposeCaseReducer(name2, reducer2) {\n context.sliceCaseReducersByName[name2] = reducer2;\n return contextMethods;\n }\n };\n reducerNames.forEach((reducerName) => {\n const reducerDefinition = reducers[reducerName];\n const reducerDetails = {\n reducerName,\n type: getType(name, reducerName),\n createNotation: typeof options.reducers === \"function\"\n };\n if (isAsyncThunkSliceReducerDefinition(reducerDefinition)) {\n handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);\n } else {\n handleNormalReducerDefinition(reducerDetails, reducerDefinition, contextMethods);\n }\n });\n function buildReducer() {\n if (process.env.NODE_ENV !== \"production\") {\n if (typeof options.extraReducers === \"object\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(14) : \"The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice\");\n }\n }\n const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === \"function\" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];\n const finalCaseReducers = {\n ...extraReducers,\n ...context.sliceCaseReducersByType\n };\n return createReducer(options.initialState, (builder) => {\n for (let key in finalCaseReducers) {\n builder.addCase(key, finalCaseReducers[key]);\n }\n for (let sM of context.sliceMatchers) {\n builder.addMatcher(sM.matcher, sM.reducer);\n }\n for (let m of actionMatchers) {\n builder.addMatcher(m.matcher, m.reducer);\n }\n if (defaultCaseReducer) {\n builder.addDefaultCase(defaultCaseReducer);\n }\n });\n }\n const selectSelf = (state) => state;\n const injectedSelectorCache = /* @__PURE__ */ new Map();\n let _reducer;\n function reducer(state, action) {\n if (!_reducer)\n _reducer = buildReducer();\n return _reducer(state, action);\n }\n function getInitialState() {\n if (!_reducer)\n _reducer = buildReducer();\n return _reducer.getInitialState();\n }\n function makeSelectorProps(reducerPath2, injected = false) {\n function selectSlice(state) {\n let sliceState = state[reducerPath2];\n if (typeof sliceState === \"undefined\") {\n if (injected) {\n sliceState = getInitialState();\n } else if (process.env.NODE_ENV !== \"production\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(15) : \"selectSlice returned undefined for an uninjected slice reducer\");\n }\n }\n return sliceState;\n }\n function getSelectors(selectState = selectSelf) {\n const selectorCache = emplace(injectedSelectorCache, injected, {\n insert: () => /* @__PURE__ */ new WeakMap()\n });\n return emplace(selectorCache, selectState, {\n insert: () => {\n const map = {};\n for (const [name2, selector] of Object.entries(options.selectors ?? {})) {\n map[name2] = wrapSelector(selector, selectState, getInitialState, injected);\n }\n return map;\n }\n });\n }\n return {\n reducerPath: reducerPath2,\n getSelectors,\n get selectors() {\n return getSelectors(selectSlice);\n },\n selectSlice\n };\n }\n const slice = {\n name,\n reducer,\n actions: context.actionCreators,\n caseReducers: context.sliceCaseReducersByName,\n getInitialState,\n ...makeSelectorProps(reducerPath),\n injectInto(injectable, {\n reducerPath: pathOpt,\n ...config\n } = {}) {\n const newReducerPath = pathOpt ?? reducerPath;\n injectable.inject({\n reducerPath: newReducerPath,\n reducer\n }, config);\n return {\n ...slice,\n ...makeSelectorProps(newReducerPath, true)\n };\n }\n };\n return slice;\n };\n}\nfunction wrapSelector(selector, selectState, getInitialState, injected) {\n function wrapper(rootState, ...args) {\n let sliceState = selectState(rootState);\n if (typeof sliceState === \"undefined\") {\n if (injected) {\n sliceState = getInitialState();\n } else if (process.env.NODE_ENV !== \"production\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(16) : \"selectState returned undefined for an uninjected slice reducer\");\n }\n }\n return selector(sliceState, ...args);\n }\n wrapper.unwrapped = selector;\n return wrapper;\n}\nvar createSlice = /* @__PURE__ */ buildCreateSlice();\nfunction buildReducerCreators() {\n function asyncThunk(payloadCreator, config) {\n return {\n _reducerDefinitionType: \"asyncThunk\" /* asyncThunk */,\n payloadCreator,\n ...config\n };\n }\n asyncThunk.withTypes = () => asyncThunk;\n return {\n reducer(caseReducer) {\n return Object.assign({\n // hack so the wrapping function has the same name as the original\n // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original\n [caseReducer.name](...args) {\n return caseReducer(...args);\n }\n }[caseReducer.name], {\n _reducerDefinitionType: \"reducer\" /* reducer */\n });\n },\n preparedReducer(prepare, reducer) {\n return {\n _reducerDefinitionType: \"reducerWithPrepare\" /* reducerWithPrepare */,\n prepare,\n reducer\n };\n },\n asyncThunk\n };\n}\nfunction handleNormalReducerDefinition({\n type,\n reducerName,\n createNotation\n}, maybeReducerWithPrepare, context) {\n let caseReducer;\n let prepareCallback;\n if (\"reducer\" in maybeReducerWithPrepare) {\n if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(17) : \"Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.\");\n }\n caseReducer = maybeReducerWithPrepare.reducer;\n prepareCallback = maybeReducerWithPrepare.prepare;\n } else {\n caseReducer = maybeReducerWithPrepare;\n }\n context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));\n}\nfunction isAsyncThunkSliceReducerDefinition(reducerDefinition) {\n return reducerDefinition._reducerDefinitionType === \"asyncThunk\" /* asyncThunk */;\n}\nfunction isCaseReducerWithPrepareDefinition(reducerDefinition) {\n return reducerDefinition._reducerDefinitionType === \"reducerWithPrepare\" /* reducerWithPrepare */;\n}\nfunction handleThunkCaseReducerDefinition({\n type,\n reducerName\n}, reducerDefinition, context, cAT) {\n if (!cAT) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(18) : \"Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.\");\n }\n const {\n payloadCreator,\n fulfilled,\n pending,\n rejected,\n settled,\n options\n } = reducerDefinition;\n const thunk = cAT(type, payloadCreator, options);\n context.exposeAction(reducerName, thunk);\n if (fulfilled) {\n context.addCase(thunk.fulfilled, fulfilled);\n }\n if (pending) {\n context.addCase(thunk.pending, pending);\n }\n if (rejected) {\n context.addCase(thunk.rejected, rejected);\n }\n if (settled) {\n context.addMatcher(thunk.settled, settled);\n }\n context.exposeCaseReducer(reducerName, {\n fulfilled: fulfilled || noop,\n pending: pending || noop,\n rejected: rejected || noop,\n settled: settled || noop\n });\n}\nfunction noop() {\n}\n\n// src/entities/entity_state.ts\nfunction getInitialEntityState() {\n return {\n ids: [],\n entities: {}\n };\n}\nfunction createInitialStateFactory(stateAdapter) {\n function getInitialState(additionalState = {}, entities) {\n const state = Object.assign(getInitialEntityState(), additionalState);\n return entities ? stateAdapter.setAll(state, entities) : state;\n }\n return {\n getInitialState\n };\n}\n\n// src/entities/state_selectors.ts\nfunction createSelectorsFactory() {\n function getSelectors(selectState, options = {}) {\n const {\n createSelector: createSelector2 = createDraftSafeSelector\n } = options;\n const selectIds = (state) => state.ids;\n const selectEntities = (state) => state.entities;\n const selectAll = createSelector2(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));\n const selectId = (_, id) => id;\n const selectById = (entities, id) => entities[id];\n const selectTotal = createSelector2(selectIds, (ids) => ids.length);\n if (!selectState) {\n return {\n selectIds,\n selectEntities,\n selectAll,\n selectTotal,\n selectById: createSelector2(selectEntities, selectId, selectById)\n };\n }\n const selectGlobalizedEntities = createSelector2(selectState, selectEntities);\n return {\n selectIds: createSelector2(selectState, selectIds),\n selectEntities: selectGlobalizedEntities,\n selectAll: createSelector2(selectState, selectAll),\n selectTotal: createSelector2(selectState, selectTotal),\n selectById: createSelector2(selectGlobalizedEntities, selectId, selectById)\n };\n }\n return {\n getSelectors\n };\n}\n\n// src/entities/sorted_state_adapter.ts\nimport { current as current3 } from \"immer\";\n\n// src/entities/state_adapter.ts\nimport { produce as createNextState3, isDraft as isDraft3 } from \"immer\";\nvar isDraftTyped = isDraft3;\nfunction createSingleArgumentStateOperator(mutator) {\n const operator = createStateOperator((_, state) => mutator(state));\n return function operation(state) {\n return operator(state, void 0);\n };\n}\nfunction createStateOperator(mutator) {\n return function operation(state, arg) {\n function isPayloadActionArgument(arg2) {\n return isFSA(arg2);\n }\n const runMutator = (draft) => {\n if (isPayloadActionArgument(arg)) {\n mutator(arg.payload, draft);\n } else {\n mutator(arg, draft);\n }\n };\n if (isDraftTyped(state)) {\n runMutator(state);\n return state;\n }\n return createNextState3(state, runMutator);\n };\n}\n\n// src/entities/utils.ts\nimport { current as current2, isDraft as isDraft4 } from \"immer\";\nfunction selectIdValue(entity, selectId) {\n const key = selectId(entity);\n if (process.env.NODE_ENV !== \"production\" && key === void 0) {\n console.warn(\"The entity passed to the `selectId` implementation returned undefined.\", \"You should probably provide your own `selectId` implementation.\", \"The entity that was passed:\", entity, \"The `selectId` implementation:\", selectId.toString());\n }\n return key;\n}\nfunction ensureEntitiesArray(entities) {\n if (!Array.isArray(entities)) {\n entities = Object.values(entities);\n }\n return entities;\n}\nfunction getCurrent(value) {\n return isDraft4(value) ? current2(value) : value;\n}\nfunction splitAddedUpdatedEntities(newEntities, selectId, state) {\n newEntities = ensureEntitiesArray(newEntities);\n const existingIdsArray = getCurrent(state.ids);\n const existingIds = new Set(existingIdsArray);\n const added = [];\n const updated = [];\n for (const entity of newEntities) {\n const id = selectIdValue(entity, selectId);\n if (existingIds.has(id)) {\n updated.push({\n id,\n changes: entity\n });\n } else {\n added.push(entity);\n }\n }\n return [added, updated, existingIdsArray];\n}\n\n// src/entities/unsorted_state_adapter.ts\nfunction createUnsortedStateAdapter(selectId) {\n function addOneMutably(entity, state) {\n const key = selectIdValue(entity, selectId);\n if (key in state.entities) {\n return;\n }\n state.ids.push(key);\n state.entities[key] = entity;\n }\n function addManyMutably(newEntities, state) {\n newEntities = ensureEntitiesArray(newEntities);\n for (const entity of newEntities) {\n addOneMutably(entity, state);\n }\n }\n function setOneMutably(entity, state) {\n const key = selectIdValue(entity, selectId);\n if (!(key in state.entities)) {\n state.ids.push(key);\n }\n ;\n state.entities[key] = entity;\n }\n function setManyMutably(newEntities, state) {\n newEntities = ensureEntitiesArray(newEntities);\n for (const entity of newEntities) {\n setOneMutably(entity, state);\n }\n }\n function setAllMutably(newEntities, state) {\n newEntities = ensureEntitiesArray(newEntities);\n state.ids = [];\n state.entities = {};\n addManyMutably(newEntities, state);\n }\n function removeOneMutably(key, state) {\n return removeManyMutably([key], state);\n }\n function removeManyMutably(keys, state) {\n let didMutate = false;\n keys.forEach((key) => {\n if (key in state.entities) {\n delete state.entities[key];\n didMutate = true;\n }\n });\n if (didMutate) {\n state.ids = state.ids.filter((id) => id in state.entities);\n }\n }\n function removeAllMutably(state) {\n Object.assign(state, {\n ids: [],\n entities: {}\n });\n }\n function takeNewKey(keys, update, state) {\n const original3 = state.entities[update.id];\n if (original3 === void 0) {\n return false;\n }\n const updated = Object.assign({}, original3, update.changes);\n const newKey = selectIdValue(updated, selectId);\n const hasNewKey = newKey !== update.id;\n if (hasNewKey) {\n keys[update.id] = newKey;\n delete state.entities[update.id];\n }\n ;\n state.entities[newKey] = updated;\n return hasNewKey;\n }\n function updateOneMutably(update, state) {\n return updateManyMutably([update], state);\n }\n function updateManyMutably(updates, state) {\n const newKeys = {};\n const updatesPerEntity = {};\n updates.forEach((update) => {\n if (update.id in state.entities) {\n updatesPerEntity[update.id] = {\n id: update.id,\n // Spreads ignore falsy values, so this works even if there isn't\n // an existing update already at this key\n changes: {\n ...updatesPerEntity[update.id] ? updatesPerEntity[update.id].changes : null,\n ...update.changes\n }\n };\n }\n });\n updates = Object.values(updatesPerEntity);\n const didMutateEntities = updates.length > 0;\n if (didMutateEntities) {\n const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0;\n if (didMutateIds) {\n state.ids = Object.values(state.entities).map((e) => selectIdValue(e, selectId));\n }\n }\n }\n function upsertOneMutably(entity, state) {\n return upsertManyMutably([entity], state);\n }\n function upsertManyMutably(newEntities, state) {\n const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);\n updateManyMutably(updated, state);\n addManyMutably(added, state);\n }\n return {\n removeAll: createSingleArgumentStateOperator(removeAllMutably),\n addOne: createStateOperator(addOneMutably),\n addMany: createStateOperator(addManyMutably),\n setOne: createStateOperator(setOneMutably),\n setMany: createStateOperator(setManyMutably),\n setAll: createStateOperator(setAllMutably),\n updateOne: createStateOperator(updateOneMutably),\n updateMany: createStateOperator(updateManyMutably),\n upsertOne: createStateOperator(upsertOneMutably),\n upsertMany: createStateOperator(upsertManyMutably),\n removeOne: createStateOperator(removeOneMutably),\n removeMany: createStateOperator(removeManyMutably)\n };\n}\n\n// src/entities/sorted_state_adapter.ts\nfunction findInsertIndex(sortedItems, item, comparisonFunction) {\n let lowIndex = 0;\n let highIndex = sortedItems.length;\n while (lowIndex < highIndex) {\n let middleIndex = lowIndex + highIndex >>> 1;\n const currentItem = sortedItems[middleIndex];\n const res = comparisonFunction(item, currentItem);\n if (res >= 0) {\n lowIndex = middleIndex + 1;\n } else {\n highIndex = middleIndex;\n }\n }\n return lowIndex;\n}\nfunction insert(sortedItems, item, comparisonFunction) {\n const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);\n sortedItems.splice(insertAtIndex, 0, item);\n return sortedItems;\n}\nfunction createSortedStateAdapter(selectId, comparer) {\n const {\n removeOne,\n removeMany,\n removeAll\n } = createUnsortedStateAdapter(selectId);\n function addOneMutably(entity, state) {\n return addManyMutably([entity], state);\n }\n function addManyMutably(newEntities, state, existingIds) {\n newEntities = ensureEntitiesArray(newEntities);\n const existingKeys = new Set(existingIds ?? current3(state.ids));\n const models = newEntities.filter((model) => !existingKeys.has(selectIdValue(model, selectId)));\n if (models.length !== 0) {\n mergeFunction(state, models);\n }\n }\n function setOneMutably(entity, state) {\n return setManyMutably([entity], state);\n }\n function setManyMutably(newEntities, state) {\n newEntities = ensureEntitiesArray(newEntities);\n if (newEntities.length !== 0) {\n for (const item of newEntities) {\n delete state.entities[selectId(item)];\n }\n mergeFunction(state, newEntities);\n }\n }\n function setAllMutably(newEntities, state) {\n newEntities = ensureEntitiesArray(newEntities);\n state.entities = {};\n state.ids = [];\n addManyMutably(newEntities, state, []);\n }\n function updateOneMutably(update, state) {\n return updateManyMutably([update], state);\n }\n function updateManyMutably(updates, state) {\n let appliedUpdates = false;\n let replacedIds = false;\n for (let update of updates) {\n const entity = state.entities[update.id];\n if (!entity) {\n continue;\n }\n appliedUpdates = true;\n Object.assign(entity, update.changes);\n const newId = selectId(entity);\n if (update.id !== newId) {\n replacedIds = true;\n delete state.entities[update.id];\n const oldIndex = state.ids.indexOf(update.id);\n state.ids[oldIndex] = newId;\n state.entities[newId] = entity;\n }\n }\n if (appliedUpdates) {\n mergeFunction(state, [], appliedUpdates, replacedIds);\n }\n }\n function upsertOneMutably(entity, state) {\n return upsertManyMutably([entity], state);\n }\n function upsertManyMutably(newEntities, state) {\n const [added, updated, existingIdsArray] = splitAddedUpdatedEntities(newEntities, selectId, state);\n if (updated.length) {\n updateManyMutably(updated, state);\n }\n if (added.length) {\n addManyMutably(added, state, existingIdsArray);\n }\n }\n function areArraysEqual(a, b) {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length && i < b.length; i++) {\n if (a[i] === b[i]) {\n continue;\n }\n return false;\n }\n return true;\n }\n const mergeInsertion = (state, addedItems, appliedUpdates, replacedIds) => {\n const currentEntities = getCurrent(state.entities);\n const currentIds = getCurrent(state.ids);\n const stateEntities = state.entities;\n let ids = currentIds;\n if (replacedIds) {\n ids = Array.from(new Set(currentIds));\n }\n let sortedEntities = [];\n for (const id of ids) {\n const entity = currentEntities[id];\n if (entity) {\n sortedEntities.push(entity);\n }\n }\n const wasPreviouslyEmpty = sortedEntities.length === 0;\n for (const item of addedItems) {\n stateEntities[selectId(item)] = item;\n if (!wasPreviouslyEmpty) {\n insert(sortedEntities, item, comparer);\n }\n }\n if (wasPreviouslyEmpty) {\n sortedEntities = addedItems.slice().sort(comparer);\n } else if (appliedUpdates) {\n sortedEntities.sort(comparer);\n }\n const newSortedIds = sortedEntities.map(selectId);\n if (!areArraysEqual(currentIds, newSortedIds)) {\n state.ids = newSortedIds;\n }\n };\n const mergeFunction = mergeInsertion;\n return {\n removeOne,\n removeMany,\n removeAll,\n addOne: createStateOperator(addOneMutably),\n updateOne: createStateOperator(updateOneMutably),\n upsertOne: createStateOperator(upsertOneMutably),\n setOne: createStateOperator(setOneMutably),\n setMany: createStateOperator(setManyMutably),\n setAll: createStateOperator(setAllMutably),\n addMany: createStateOperator(addManyMutably),\n updateMany: createStateOperator(updateManyMutably),\n upsertMany: createStateOperator(upsertManyMutably)\n };\n}\n\n// src/entities/create_adapter.ts\nfunction createEntityAdapter(options = {}) {\n const {\n selectId,\n sortComparer\n } = {\n sortComparer: false,\n selectId: (instance) => instance.id,\n ...options\n };\n const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);\n const stateFactory = createInitialStateFactory(stateAdapter);\n const selectorsFactory = createSelectorsFactory();\n return {\n selectId,\n sortComparer,\n ...stateFactory,\n ...selectorsFactory,\n ...stateAdapter\n };\n}\n\n// src/listenerMiddleware/index.ts\nimport { isAction as isAction3 } from \"redux\";\n\n// src/listenerMiddleware/exceptions.ts\nvar task = \"task\";\nvar listener = \"listener\";\nvar completed = \"completed\";\nvar cancelled = \"cancelled\";\nvar taskCancelled = `task-${cancelled}`;\nvar taskCompleted = `task-${completed}`;\nvar listenerCancelled = `${listener}-${cancelled}`;\nvar listenerCompleted = `${listener}-${completed}`;\nvar TaskAbortError = class {\n constructor(code) {\n this.code = code;\n this.message = `${task} ${cancelled} (reason: ${code})`;\n }\n name = \"TaskAbortError\";\n message;\n};\n\n// src/listenerMiddleware/utils.ts\nvar assertFunction = (func, expected) => {\n if (typeof func !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(32) : `${expected} is not a function`);\n }\n};\nvar noop2 = () => {\n};\nvar catchRejection = (promise, onError = noop2) => {\n promise.catch(onError);\n return promise;\n};\nvar addAbortSignalListener = (abortSignal, callback) => {\n abortSignal.addEventListener(\"abort\", callback, {\n once: true\n });\n return () => abortSignal.removeEventListener(\"abort\", callback);\n};\nvar abortControllerWithReason = (abortController, reason) => {\n const signal = abortController.signal;\n if (signal.aborted) {\n return;\n }\n if (!(\"reason\" in signal)) {\n Object.defineProperty(signal, \"reason\", {\n enumerable: true,\n value: reason,\n configurable: true,\n writable: true\n });\n }\n ;\n abortController.abort(reason);\n};\n\n// src/listenerMiddleware/task.ts\nvar validateActive = (signal) => {\n if (signal.aborted) {\n const {\n reason\n } = signal;\n throw new TaskAbortError(reason);\n }\n};\nfunction raceWithSignal(signal, promise) {\n let cleanup = noop2;\n return new Promise((resolve, reject) => {\n const notifyRejection = () => reject(new TaskAbortError(signal.reason));\n if (signal.aborted) {\n notifyRejection();\n return;\n }\n cleanup = addAbortSignalListener(signal, notifyRejection);\n promise.finally(() => cleanup()).then(resolve, reject);\n }).finally(() => {\n cleanup = noop2;\n });\n}\nvar runTask = async (task2, cleanUp) => {\n try {\n await Promise.resolve();\n const value = await task2();\n return {\n status: \"ok\",\n value\n };\n } catch (error) {\n return {\n status: error instanceof TaskAbortError ? \"cancelled\" : \"rejected\",\n error\n };\n } finally {\n cleanUp?.();\n }\n};\nvar createPause = (signal) => {\n return (promise) => {\n return catchRejection(raceWithSignal(signal, promise).then((output) => {\n validateActive(signal);\n return output;\n }));\n };\n};\nvar createDelay = (signal) => {\n const pause = createPause(signal);\n return (timeoutMs) => {\n return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)));\n };\n};\n\n// src/listenerMiddleware/index.ts\nvar {\n assign\n} = Object;\nvar INTERNAL_NIL_TOKEN = {};\nvar alm = \"listenerMiddleware\";\nvar createFork = (parentAbortSignal, parentBlockingPromises) => {\n const linkControllers = (controller) => addAbortSignalListener(parentAbortSignal, () => abortControllerWithReason(controller, parentAbortSignal.reason));\n return (taskExecutor, opts) => {\n assertFunction(taskExecutor, \"taskExecutor\");\n const childAbortController = new AbortController();\n linkControllers(childAbortController);\n const result = runTask(async () => {\n validateActive(parentAbortSignal);\n validateActive(childAbortController.signal);\n const result2 = await taskExecutor({\n pause: createPause(childAbortController.signal),\n delay: createDelay(childAbortController.signal),\n signal: childAbortController.signal\n });\n validateActive(childAbortController.signal);\n return result2;\n }, () => abortControllerWithReason(childAbortController, taskCompleted));\n if (opts?.autoJoin) {\n parentBlockingPromises.push(result.catch(noop2));\n }\n return {\n result: createPause(parentAbortSignal)(result),\n cancel() {\n abortControllerWithReason(childAbortController, taskCancelled);\n }\n };\n };\n};\nvar createTakePattern = (startListening, signal) => {\n const take = async (predicate, timeout) => {\n validateActive(signal);\n let unsubscribe = () => {\n };\n const tuplePromise = new Promise((resolve, reject) => {\n let stopListening = startListening({\n predicate,\n effect: (action, listenerApi) => {\n listenerApi.unsubscribe();\n resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);\n }\n });\n unsubscribe = () => {\n stopListening();\n reject();\n };\n });\n const promises = [tuplePromise];\n if (timeout != null) {\n promises.push(new Promise((resolve) => setTimeout(resolve, timeout, null)));\n }\n try {\n const output = await raceWithSignal(signal, Promise.race(promises));\n validateActive(signal);\n return output;\n } finally {\n unsubscribe();\n }\n };\n return (predicate, timeout) => catchRejection(take(predicate, timeout));\n};\nvar getListenerEntryPropsFrom = (options) => {\n let {\n type,\n actionCreator,\n matcher,\n predicate,\n effect\n } = options;\n if (type) {\n predicate = createAction(type).match;\n } else if (actionCreator) {\n type = actionCreator.type;\n predicate = actionCreator.match;\n } else if (matcher) {\n predicate = matcher;\n } else if (predicate) {\n } else {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(21) : \"Creating or removing a listener requires one of the known fields for matching an action\");\n }\n assertFunction(effect, \"options.listener\");\n return {\n predicate,\n type,\n effect\n };\n};\nvar createListenerEntry = Object.assign((options) => {\n const {\n type,\n predicate,\n effect\n } = getListenerEntryPropsFrom(options);\n const id = nanoid();\n const entry = {\n id,\n effect,\n type,\n predicate,\n pending: /* @__PURE__ */ new Set(),\n unsubscribe: () => {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(22) : \"Unsubscribe not initialized\");\n }\n };\n return entry;\n}, {\n withTypes: () => createListenerEntry\n});\nvar cancelActiveListeners = (entry) => {\n entry.pending.forEach((controller) => {\n abortControllerWithReason(controller, listenerCancelled);\n });\n};\nvar createClearListenerMiddleware = (listenerMap) => {\n return () => {\n listenerMap.forEach(cancelActiveListeners);\n listenerMap.clear();\n };\n};\nvar safelyNotifyError = (errorHandler, errorToNotify, errorInfo) => {\n try {\n errorHandler(errorToNotify, errorInfo);\n } catch (errorHandlerError) {\n setTimeout(() => {\n throw errorHandlerError;\n }, 0);\n }\n};\nvar addListener = Object.assign(createAction(`${alm}/add`), {\n withTypes: () => addListener\n});\nvar clearAllListeners = createAction(`${alm}/removeAll`);\nvar removeListener = Object.assign(createAction(`${alm}/remove`), {\n withTypes: () => removeListener\n});\nvar defaultErrorHandler = (...args) => {\n console.error(`${alm}/error`, ...args);\n};\nvar createListenerMiddleware = (middlewareOptions = {}) => {\n const listenerMap = /* @__PURE__ */ new Map();\n const {\n extra,\n onError = defaultErrorHandler\n } = middlewareOptions;\n assertFunction(onError, \"onError\");\n const insertEntry = (entry) => {\n entry.unsubscribe = () => listenerMap.delete(entry.id);\n listenerMap.set(entry.id, entry);\n return (cancelOptions) => {\n entry.unsubscribe();\n if (cancelOptions?.cancelActive) {\n cancelActiveListeners(entry);\n }\n };\n };\n const startListening = (options) => {\n let entry = find(Array.from(listenerMap.values()), (existingEntry) => existingEntry.effect === options.effect);\n if (!entry) {\n entry = createListenerEntry(options);\n }\n return insertEntry(entry);\n };\n Object.assign(startListening, {\n withTypes: () => startListening\n });\n const stopListening = (options) => {\n const {\n type,\n effect,\n predicate\n } = getListenerEntryPropsFrom(options);\n const entry = find(Array.from(listenerMap.values()), (entry2) => {\n const matchPredicateOrType = typeof type === \"string\" ? entry2.type === type : entry2.predicate === predicate;\n return matchPredicateOrType && entry2.effect === effect;\n });\n if (entry) {\n entry.unsubscribe();\n if (options.cancelActive) {\n cancelActiveListeners(entry);\n }\n }\n return !!entry;\n };\n Object.assign(stopListening, {\n withTypes: () => stopListening\n });\n const notifyListener = async (entry, action, api, getOriginalState) => {\n const internalTaskController = new AbortController();\n const take = createTakePattern(startListening, internalTaskController.signal);\n const autoJoinPromises = [];\n try {\n entry.pending.add(internalTaskController);\n await Promise.resolve(entry.effect(\n action,\n // Use assign() rather than ... to avoid extra helper functions added to bundle\n assign({}, api, {\n getOriginalState,\n condition: (predicate, timeout) => take(predicate, timeout).then(Boolean),\n take,\n delay: createDelay(internalTaskController.signal),\n pause: createPause(internalTaskController.signal),\n extra,\n signal: internalTaskController.signal,\n fork: createFork(internalTaskController.signal, autoJoinPromises),\n unsubscribe: entry.unsubscribe,\n subscribe: () => {\n listenerMap.set(entry.id, entry);\n },\n cancelActiveListeners: () => {\n entry.pending.forEach((controller, _, set) => {\n if (controller !== internalTaskController) {\n abortControllerWithReason(controller, listenerCancelled);\n set.delete(controller);\n }\n });\n },\n cancel: () => {\n abortControllerWithReason(internalTaskController, listenerCancelled);\n entry.pending.delete(internalTaskController);\n },\n throwIfCancelled: () => {\n validateActive(internalTaskController.signal);\n }\n })\n ));\n } catch (listenerError) {\n if (!(listenerError instanceof TaskAbortError)) {\n safelyNotifyError(onError, listenerError, {\n raisedBy: \"effect\"\n });\n }\n } finally {\n await Promise.all(autoJoinPromises);\n abortControllerWithReason(internalTaskController, listenerCompleted);\n entry.pending.delete(internalTaskController);\n }\n };\n const clearListenerMiddleware = createClearListenerMiddleware(listenerMap);\n const middleware = (api) => (next) => (action) => {\n if (!isAction3(action)) {\n return next(action);\n }\n if (addListener.match(action)) {\n return startListening(action.payload);\n }\n if (clearAllListeners.match(action)) {\n clearListenerMiddleware();\n return;\n }\n if (removeListener.match(action)) {\n return stopListening(action.payload);\n }\n let originalState = api.getState();\n const getOriginalState = () => {\n if (originalState === INTERNAL_NIL_TOKEN) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(23) : `${alm}: getOriginalState can only be called synchronously`);\n }\n return originalState;\n };\n let result;\n try {\n result = next(action);\n if (listenerMap.size > 0) {\n const currentState = api.getState();\n const listenerEntries = Array.from(listenerMap.values());\n for (const entry of listenerEntries) {\n let runListener = false;\n try {\n runListener = entry.predicate(action, currentState, originalState);\n } catch (predicateError) {\n runListener = false;\n safelyNotifyError(onError, predicateError, {\n raisedBy: \"predicate\"\n });\n }\n if (!runListener) {\n continue;\n }\n notifyListener(entry, action, api, getOriginalState);\n }\n }\n } finally {\n originalState = INTERNAL_NIL_TOKEN;\n }\n return result;\n };\n return {\n middleware,\n startListening,\n stopListening,\n clearListeners: clearListenerMiddleware\n };\n};\n\n// src/dynamicMiddleware/index.ts\nimport { compose as compose3 } from \"redux\";\nvar createMiddlewareEntry = (middleware) => ({\n id: nanoid(),\n middleware,\n applied: /* @__PURE__ */ new Map()\n});\nvar matchInstance = (instanceId) => (action) => action?.meta?.instanceId === instanceId;\nvar createDynamicMiddleware = () => {\n const instanceId = nanoid();\n const middlewareMap = /* @__PURE__ */ new Map();\n const withMiddleware = Object.assign(createAction(\"dynamicMiddleware/add\", (...middlewares) => ({\n payload: middlewares,\n meta: {\n instanceId\n }\n })), {\n withTypes: () => withMiddleware\n });\n const addMiddleware = Object.assign(function addMiddleware2(...middlewares) {\n middlewares.forEach((middleware2) => {\n let entry = find(Array.from(middlewareMap.values()), (entry2) => entry2.middleware === middleware2);\n if (!entry) {\n entry = createMiddlewareEntry(middleware2);\n }\n middlewareMap.set(entry.id, entry);\n });\n }, {\n withTypes: () => addMiddleware\n });\n const getFinalMiddleware = (api) => {\n const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) => emplace(entry.applied, api, {\n insert: () => entry.middleware(api)\n }));\n return compose3(...appliedMiddleware);\n };\n const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));\n const middleware = (api) => (next) => (action) => {\n if (isWithMiddleware(action)) {\n addMiddleware(...action.payload);\n return api.dispatch;\n }\n return getFinalMiddleware(api)(next)(action);\n };\n return {\n middleware,\n addMiddleware,\n withMiddleware,\n instanceId\n };\n};\n\n// src/combineSlices.ts\nimport { combineReducers as combineReducers2 } from \"redux\";\nvar isSliceLike = (maybeSliceLike) => \"reducerPath\" in maybeSliceLike && typeof maybeSliceLike.reducerPath === \"string\";\nvar getReducers = (slices) => slices.flatMap((sliceOrMap) => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));\nvar ORIGINAL_STATE = Symbol.for(\"rtk-state-proxy-original\");\nvar isStateProxy = (value) => !!value && !!value[ORIGINAL_STATE];\nvar stateProxyMap = /* @__PURE__ */ new WeakMap();\nvar createStateProxy = (state, reducerMap) => emplace(stateProxyMap, state, {\n insert: () => new Proxy(state, {\n get: (target, prop, receiver) => {\n if (prop === ORIGINAL_STATE)\n return target;\n const result = Reflect.get(target, prop, receiver);\n if (typeof result === \"undefined\") {\n const reducer = reducerMap[prop.toString()];\n if (reducer) {\n const reducerResult = reducer(void 0, {\n type: nanoid()\n });\n if (typeof reducerResult === \"undefined\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(24) : `The slice reducer for key \"${prop.toString()}\" returned undefined when called for selector(). If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);\n }\n return reducerResult;\n }\n }\n return result;\n }\n })\n});\nvar original = (state) => {\n if (!isStateProxy(state)) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(25) : \"original must be used on state Proxy\");\n }\n return state[ORIGINAL_STATE];\n};\nvar noopReducer = (state = {}) => state;\nfunction combineSlices(...slices) {\n const reducerMap = Object.fromEntries(getReducers(slices));\n const getReducer = () => Object.keys(reducerMap).length ? combineReducers2(reducerMap) : noopReducer;\n let reducer = getReducer();\n function combinedReducer(state, action) {\n return reducer(state, action);\n }\n combinedReducer.withLazyLoadedSlices = () => combinedReducer;\n const inject = (slice, config = {}) => {\n const {\n reducerPath,\n reducer: reducerToInject\n } = slice;\n const currentReducer = reducerMap[reducerPath];\n if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {\n if (typeof process !== \"undefined\" && process.env.NODE_ENV === \"development\") {\n console.error(`called \\`inject\\` to override already-existing reducer ${reducerPath} without specifying \\`overrideExisting: true\\``);\n }\n return combinedReducer;\n }\n reducerMap[reducerPath] = reducerToInject;\n reducer = getReducer();\n return combinedReducer;\n };\n const selector = Object.assign(function makeSelector(selectorFn, selectState) {\n return function selector2(state, ...args) {\n return selectorFn(createStateProxy(selectState ? selectState(state, ...args) : state, reducerMap), ...args);\n };\n }, {\n original\n });\n return Object.assign(combinedReducer, {\n inject,\n selector\n });\n}\n\n// src/formatProdErrorMessage.ts\nfunction formatProdErrorMessage(code) {\n return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;\n}\nexport {\n ReducerType,\n SHOULD_AUTOBATCH,\n TaskAbortError,\n Tuple,\n addListener,\n asyncThunkCreator,\n autoBatchEnhancer,\n buildCreateSlice,\n clearAllListeners,\n combineSlices,\n configureStore,\n createAction,\n createActionCreatorInvariantMiddleware,\n createAsyncThunk,\n createDraftSafeSelector,\n createDraftSafeSelectorCreator,\n createDynamicMiddleware,\n createEntityAdapter,\n createImmutableStateInvariantMiddleware,\n createListenerMiddleware,\n produce as createNextState,\n createReducer,\n createSelector,\n createSelectorCreator2 as createSelectorCreator,\n createSerializableStateInvariantMiddleware,\n createSlice,\n current4 as current,\n findNonSerializableValue,\n formatProdErrorMessage,\n freeze,\n isActionCreator,\n isAllOf,\n isAnyOf,\n isAsyncThunkAction,\n isDraft6 as isDraft,\n isFSA as isFluxStandardAction,\n isFulfilled,\n isImmutableDefault,\n isPending,\n isPlain,\n isRejected,\n isRejectedWithValue,\n lruMemoize,\n miniSerializeError,\n nanoid,\n original2 as original,\n prepareAutoBatched,\n removeListener,\n unwrapResult,\n weakMapMemoize2 as weakMapMemoize\n};\n//# sourceMappingURL=redux-toolkit.modern.mjs.map","export function getUser() {\n const cookiePrefix = import.meta.env.VITE_COOKIE_PREFIX\n\n let user = localStorage.getItem(`${cookiePrefix}userData`)\n\n if (user) {\n user = JSON.parse(user)\n return {\n ...user.account,\n phone_number: user.identity ? user.identity : '',\n kyc: user.kyc ? user.kyc : null\n }\n }\n return {}\n}\n\n","// ** Redux Imports\nimport { createSlice } from '@reduxjs/toolkit'\n\nimport { getUser } from '../utility/UserHelper'\nconst cookiePrefix = import.meta.env.VITE_COOKIE_PREFIX\n\nconst initialUser = () => {\n return getUser()\n}\n\nconst initialAuthToken = () => {\n const item = localStorage.getItem(`${cookiePrefix}authToken`)\n return item ? item : null\n}\n\nconst isLoggedIn = () => {\n const user = initialUser()\n const exp = Object.keys(user).length !== 0\n return exp\n}\n\nexport const authSlice = createSlice({\n name: 'auth',\n initialState: {\n userData: initialUser(),\n authToken: initialAuthToken(),\n isLoggedIn: isLoggedIn()\n },\n reducers: {\n handleLogin: (state, action) => {\n const userData = action.payload.userData\n state.userData = {\n ...userData.account,\n phone_number: userData.identity ? userData.identity : '',\n kyc: userData.kyc ? userData.kyc : null\n }\n\n state.authToken = action.payload.authToken\n localStorage.setItem(`${cookiePrefix}userData`, JSON.stringify(userData))\n\n if (action.payload.authToken) {\n localStorage.setItem(`${cookiePrefix}authToken`, action.payload.authToken)\n }\n state.isLoggedIn = isLoggedIn()\n },\n handleLogout: state => {\n state.userData = {}\n state.authToken = null\n state.isLoggedIn = isLoggedIn()\n\n // ** Remove user & accessToken from localStorage\n localStorage.removeItem(`${cookiePrefix}userData`)\n localStorage.removeItem(`${cookiePrefix}authToken`)\n }\n }\n})\n\nexport const { handleLogin, handleLogout } = authSlice.actions\n\nexport default authSlice.reducer\n","import { createSlice } from '@reduxjs/toolkit'\n\nexport const transactionFiltersSlice = createSlice({\n name: 'transactionFilters',\n initialState: {\n transactionFilters: []\n },\n reducers: {\n addOrUpdateFilter: (state, action) => {\n const filter = action.payload\n\n const index = state.transactionFilters.findIndex(\n tempFilter => tempFilter.label === filter.label\n )\n\n if (index < 0) {\n state.transactionFilters.push(filter)\n } else {\n state.transactionFilters.splice(index, 1)\n }\n\n console.log(index)\n },\n addFilters: (state, action) => {\n const filters = action.payload\n\n state.transactionFilters = filters\n }\n }\n})\n\n// Action creators are generated for each case reducer function\nexport const { addOrUpdateFilter, addFilters } = transactionFiltersSlice.actions\nexport default transactionFiltersSlice.reducer\n","import auth from './auth'\nimport transactionFilters from './transactionFilters'\n\nconst rootReducer = { auth, transactionFilters }\n\nexport default rootReducer\n","// ** Redux Imports\nimport rootReducer from './rootReducer'\nimport { configureStore } from '@reduxjs/toolkit'\n\nconst store = configureStore({\n reducer: rootReducer,\n middleware: (getDefaultMiddleware) => {\n return getDefaultMiddleware({\n serializableCheck: false\n })\n }\n})\n\nexport { store }\n","/**\n * @license React\n * use-sync-external-store-with-selector.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var g=require(\"react\");function n(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var p=\"function\"===typeof Object.is?Object.is:n,q=g.useSyncExternalStore,r=g.useRef,t=g.useEffect,u=g.useMemo,v=g.useDebugValue;\nexports.useSyncExternalStoreWithSelector=function(a,b,e,l,h){var c=r(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f}else f=c.current;c=u(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==h&&f.hasValue){var b=f.value;if(h(b,a))return k=b}return k=a}b=k;if(p(d,a))return b;var e=l(a);if(void 0!==h&&h(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return[function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,h]);var d=q(a,c[0],c[1]);\nt(function(){f.hasValue=!0;f.value=d},[d]);v(d);return d};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/use-sync-external-store-with-selector.production.min.js');\n} else {\n module.exports = require('./cjs/use-sync-external-store-with-selector.development.js');\n}\n","// src/index.ts\nimport * as React2 from \"react\";\nimport { useSyncExternalStoreWithSelector as useSyncExternalStoreWithSelector2 } from \"use-sync-external-store/with-selector.js\";\n\n// src/utils/react.ts\nimport * as ReactOriginal from \"react\";\nvar React = (\n // prettier-ignore\n // @ts-ignore\n \"default\" in ReactOriginal ? ReactOriginal[\"default\"] : ReactOriginal\n);\n\n// src/components/Context.ts\nvar ContextKey = Symbol.for(`react-redux-context`);\nvar gT = typeof globalThis !== \"undefined\" ? globalThis : (\n /* fall back to a per-module scope (pre-8.1 behaviour) if `globalThis` is not available */\n {}\n);\nfunction getContext() {\n if (!React.createContext)\n return {};\n const contextMap = gT[ContextKey] ?? (gT[ContextKey] = /* @__PURE__ */ new Map());\n let realContext = contextMap.get(React.createContext);\n if (!realContext) {\n realContext = React.createContext(\n null\n );\n if (process.env.NODE_ENV !== \"production\") {\n realContext.displayName = \"ReactRedux\";\n }\n contextMap.set(React.createContext, realContext);\n }\n return realContext;\n}\nvar ReactReduxContext = /* @__PURE__ */ getContext();\n\n// src/utils/useSyncExternalStore.ts\nvar notInitialized = () => {\n throw new Error(\"uSES not initialized!\");\n};\n\n// src/hooks/useReduxContext.ts\nfunction createReduxContextHook(context = ReactReduxContext) {\n return function useReduxContext2() {\n const contextValue = React.useContext(context);\n if (process.env.NODE_ENV !== \"production\" && !contextValue) {\n throw new Error(\n \"could not find react-redux context value; please ensure the component is wrapped in a \"\n );\n }\n return contextValue;\n };\n}\nvar useReduxContext = /* @__PURE__ */ createReduxContextHook();\n\n// src/hooks/useSelector.ts\nvar useSyncExternalStoreWithSelector = notInitialized;\nvar initializeUseSelector = (fn) => {\n useSyncExternalStoreWithSelector = fn;\n};\nvar refEquality = (a, b) => a === b;\nfunction createSelectorHook(context = ReactReduxContext) {\n const useReduxContext2 = context === ReactReduxContext ? useReduxContext : createReduxContextHook(context);\n const useSelector2 = (selector, equalityFnOrOptions = {}) => {\n const { equalityFn = refEquality, devModeChecks = {} } = typeof equalityFnOrOptions === \"function\" ? { equalityFn: equalityFnOrOptions } : equalityFnOrOptions;\n if (process.env.NODE_ENV !== \"production\") {\n if (!selector) {\n throw new Error(`You must pass a selector to useSelector`);\n }\n if (typeof selector !== \"function\") {\n throw new Error(`You must pass a function as a selector to useSelector`);\n }\n if (typeof equalityFn !== \"function\") {\n throw new Error(\n `You must pass a function as an equality function to useSelector`\n );\n }\n }\n const {\n store,\n subscription,\n getServerState,\n stabilityCheck,\n identityFunctionCheck\n } = useReduxContext2();\n const firstRun = React.useRef(true);\n const wrappedSelector = React.useCallback(\n {\n [selector.name](state) {\n const selected = selector(state);\n if (process.env.NODE_ENV !== \"production\") {\n const {\n identityFunctionCheck: finalIdentityFunctionCheck,\n stabilityCheck: finalStabilityCheck\n } = {\n stabilityCheck,\n identityFunctionCheck,\n ...devModeChecks\n };\n if (finalStabilityCheck === \"always\" || finalStabilityCheck === \"once\" && firstRun.current) {\n const toCompare = selector(state);\n if (!equalityFn(selected, toCompare)) {\n let stack = void 0;\n try {\n throw new Error();\n } catch (e) {\n ;\n ({ stack } = e);\n }\n console.warn(\n \"Selector \" + (selector.name || \"unknown\") + \" returned a different result when called with the same parameters. This can lead to unnecessary rerenders.\\nSelectors that return a new reference (such as an object or an array) should be memoized: https://redux.js.org/usage/deriving-data-selectors#optimizing-selectors-with-memoization\",\n {\n state,\n selected,\n selected2: toCompare,\n stack\n }\n );\n }\n }\n if (finalIdentityFunctionCheck === \"always\" || finalIdentityFunctionCheck === \"once\" && firstRun.current) {\n if (selected === state) {\n let stack = void 0;\n try {\n throw new Error();\n } catch (e) {\n ;\n ({ stack } = e);\n }\n console.warn(\n \"Selector \" + (selector.name || \"unknown\") + \" returned the root state when called. This can lead to unnecessary rerenders.\\nSelectors that return the entire state are almost certainly a mistake, as they will cause a rerender whenever *anything* in state changes.\",\n { stack }\n );\n }\n }\n if (firstRun.current)\n firstRun.current = false;\n }\n return selected;\n }\n }[selector.name],\n [selector, stabilityCheck, devModeChecks.stabilityCheck]\n );\n const selectedState = useSyncExternalStoreWithSelector(\n subscription.addNestedSub,\n store.getState,\n getServerState || store.getState,\n wrappedSelector,\n equalityFn\n );\n React.useDebugValue(selectedState);\n return selectedState;\n };\n Object.assign(useSelector2, {\n withTypes: () => useSelector2\n });\n return useSelector2;\n}\nvar useSelector = /* @__PURE__ */ createSelectorHook();\n\n// src/utils/react-is.ts\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.element\");\nvar REACT_PORTAL_TYPE = Symbol.for(\"react.portal\");\nvar REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nvar REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\");\nvar REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\");\nvar REACT_PROVIDER_TYPE = Symbol.for(\"react.provider\");\nvar REACT_CONTEXT_TYPE = Symbol.for(\"react.context\");\nvar REACT_SERVER_CONTEXT_TYPE = Symbol.for(\"react.server_context\");\nvar REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\");\nvar REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\");\nvar REACT_SUSPENSE_LIST_TYPE = Symbol.for(\"react.suspense_list\");\nvar REACT_MEMO_TYPE = Symbol.for(\"react.memo\");\nvar REACT_LAZY_TYPE = Symbol.for(\"react.lazy\");\nvar REACT_OFFSCREEN_TYPE = Symbol.for(\"react.offscreen\");\nvar REACT_CLIENT_REFERENCE = Symbol.for(\"react.client.reference\");\nvar ForwardRef = REACT_FORWARD_REF_TYPE;\nvar Memo = REACT_MEMO_TYPE;\nfunction isValidElementType(type) {\n if (typeof type === \"string\" || typeof type === \"function\") {\n return true;\n }\n if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_OFFSCREEN_TYPE) {\n return true;\n }\n if (typeof type === \"object\" && type !== null) {\n if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object\n // types supported by any Flight configuration anywhere since\n // we don't know which Flight build this will end up being used\n // with.\n type.$$typeof === REACT_CLIENT_REFERENCE || type.getModuleId !== void 0) {\n return true;\n }\n }\n return false;\n}\nfunction typeOf(object) {\n if (typeof object === \"object\" && object !== null) {\n const $$typeof = object.$$typeof;\n switch ($$typeof) {\n case REACT_ELEMENT_TYPE: {\n const type = object.type;\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n case REACT_PROFILER_TYPE:\n case REACT_STRICT_MODE_TYPE:\n case REACT_SUSPENSE_TYPE:\n case REACT_SUSPENSE_LIST_TYPE:\n return type;\n default: {\n const $$typeofType = type && type.$$typeof;\n switch ($$typeofType) {\n case REACT_SERVER_CONTEXT_TYPE:\n case REACT_CONTEXT_TYPE:\n case REACT_FORWARD_REF_TYPE:\n case REACT_LAZY_TYPE:\n case REACT_MEMO_TYPE:\n case REACT_PROVIDER_TYPE:\n return $$typeofType;\n default:\n return $$typeof;\n }\n }\n }\n }\n case REACT_PORTAL_TYPE: {\n return $$typeof;\n }\n }\n }\n return void 0;\n}\nfunction isContextConsumer(object) {\n return typeOf(object) === REACT_CONTEXT_TYPE;\n}\nfunction isMemo(object) {\n return typeOf(object) === REACT_MEMO_TYPE;\n}\n\n// src/utils/warning.ts\nfunction warning(message) {\n if (typeof console !== \"undefined\" && typeof console.error === \"function\") {\n console.error(message);\n }\n try {\n throw new Error(message);\n } catch (e) {\n }\n}\n\n// src/connect/verifySubselectors.ts\nfunction verify(selector, methodName) {\n if (!selector) {\n throw new Error(`Unexpected value for ${methodName} in connect.`);\n } else if (methodName === \"mapStateToProps\" || methodName === \"mapDispatchToProps\") {\n if (!Object.prototype.hasOwnProperty.call(selector, \"dependsOnOwnProps\")) {\n warning(\n `The selector for ${methodName} of connect did not specify a value for dependsOnOwnProps.`\n );\n }\n }\n}\nfunction verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps) {\n verify(mapStateToProps, \"mapStateToProps\");\n verify(mapDispatchToProps, \"mapDispatchToProps\");\n verify(mergeProps, \"mergeProps\");\n}\n\n// src/connect/selectorFactory.ts\nfunction pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, {\n areStatesEqual,\n areOwnPropsEqual,\n areStatePropsEqual\n}) {\n let hasRunAtLeastOnce = false;\n let state;\n let ownProps;\n let stateProps;\n let dispatchProps;\n let mergedProps;\n function handleFirstCall(firstState, firstOwnProps) {\n state = firstState;\n ownProps = firstOwnProps;\n stateProps = mapStateToProps(state, ownProps);\n dispatchProps = mapDispatchToProps(dispatch, ownProps);\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps);\n hasRunAtLeastOnce = true;\n return mergedProps;\n }\n function handleNewPropsAndNewState() {\n stateProps = mapStateToProps(state, ownProps);\n if (mapDispatchToProps.dependsOnOwnProps)\n dispatchProps = mapDispatchToProps(dispatch, ownProps);\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps);\n return mergedProps;\n }\n function handleNewProps() {\n if (mapStateToProps.dependsOnOwnProps)\n stateProps = mapStateToProps(state, ownProps);\n if (mapDispatchToProps.dependsOnOwnProps)\n dispatchProps = mapDispatchToProps(dispatch, ownProps);\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps);\n return mergedProps;\n }\n function handleNewState() {\n const nextStateProps = mapStateToProps(state, ownProps);\n const statePropsChanged = !areStatePropsEqual(nextStateProps, stateProps);\n stateProps = nextStateProps;\n if (statePropsChanged)\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps);\n return mergedProps;\n }\n function handleSubsequentCalls(nextState, nextOwnProps) {\n const propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps);\n const stateChanged = !areStatesEqual(\n nextState,\n state,\n nextOwnProps,\n ownProps\n );\n state = nextState;\n ownProps = nextOwnProps;\n if (propsChanged && stateChanged)\n return handleNewPropsAndNewState();\n if (propsChanged)\n return handleNewProps();\n if (stateChanged)\n return handleNewState();\n return mergedProps;\n }\n return function pureFinalPropsSelector(nextState, nextOwnProps) {\n return hasRunAtLeastOnce ? handleSubsequentCalls(nextState, nextOwnProps) : handleFirstCall(nextState, nextOwnProps);\n };\n}\nfunction finalPropsSelectorFactory(dispatch, {\n initMapStateToProps,\n initMapDispatchToProps,\n initMergeProps,\n ...options\n}) {\n const mapStateToProps = initMapStateToProps(dispatch, options);\n const mapDispatchToProps = initMapDispatchToProps(dispatch, options);\n const mergeProps = initMergeProps(dispatch, options);\n if (process.env.NODE_ENV !== \"production\") {\n verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps);\n }\n return pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, options);\n}\n\n// src/utils/bindActionCreators.ts\nfunction bindActionCreators(actionCreators, dispatch) {\n const boundActionCreators = {};\n for (const key in actionCreators) {\n const actionCreator = actionCreators[key];\n if (typeof actionCreator === \"function\") {\n boundActionCreators[key] = (...args) => dispatch(actionCreator(...args));\n }\n }\n return boundActionCreators;\n}\n\n// src/utils/isPlainObject.ts\nfunction isPlainObject(obj) {\n if (typeof obj !== \"object\" || obj === null)\n return false;\n const proto = Object.getPrototypeOf(obj);\n if (proto === null)\n return true;\n let baseProto = proto;\n while (Object.getPrototypeOf(baseProto) !== null) {\n baseProto = Object.getPrototypeOf(baseProto);\n }\n return proto === baseProto;\n}\n\n// src/utils/verifyPlainObject.ts\nfunction verifyPlainObject(value, displayName, methodName) {\n if (!isPlainObject(value)) {\n warning(\n `${methodName}() in ${displayName} must return a plain object. Instead received ${value}.`\n );\n }\n}\n\n// src/connect/wrapMapToProps.ts\nfunction wrapMapToPropsConstant(getConstant) {\n return function initConstantSelector(dispatch) {\n const constant = getConstant(dispatch);\n function constantSelector() {\n return constant;\n }\n constantSelector.dependsOnOwnProps = false;\n return constantSelector;\n };\n}\nfunction getDependsOnOwnProps(mapToProps) {\n return mapToProps.dependsOnOwnProps ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;\n}\nfunction wrapMapToPropsFunc(mapToProps, methodName) {\n return function initProxySelector(dispatch, { displayName }) {\n const proxy = function mapToPropsProxy(stateOrDispatch, ownProps) {\n return proxy.dependsOnOwnProps ? proxy.mapToProps(stateOrDispatch, ownProps) : proxy.mapToProps(stateOrDispatch, void 0);\n };\n proxy.dependsOnOwnProps = true;\n proxy.mapToProps = function detectFactoryAndVerify(stateOrDispatch, ownProps) {\n proxy.mapToProps = mapToProps;\n proxy.dependsOnOwnProps = getDependsOnOwnProps(mapToProps);\n let props = proxy(stateOrDispatch, ownProps);\n if (typeof props === \"function\") {\n proxy.mapToProps = props;\n proxy.dependsOnOwnProps = getDependsOnOwnProps(props);\n props = proxy(stateOrDispatch, ownProps);\n }\n if (process.env.NODE_ENV !== \"production\")\n verifyPlainObject(props, displayName, methodName);\n return props;\n };\n return proxy;\n };\n}\n\n// src/connect/invalidArgFactory.ts\nfunction createInvalidArgFactory(arg, name) {\n return (dispatch, options) => {\n throw new Error(\n `Invalid value of type ${typeof arg} for ${name} argument when connecting component ${options.wrappedComponentName}.`\n );\n };\n}\n\n// src/connect/mapDispatchToProps.ts\nfunction mapDispatchToPropsFactory(mapDispatchToProps) {\n return mapDispatchToProps && typeof mapDispatchToProps === \"object\" ? wrapMapToPropsConstant(\n (dispatch) => (\n // @ts-ignore\n bindActionCreators(mapDispatchToProps, dispatch)\n )\n ) : !mapDispatchToProps ? wrapMapToPropsConstant((dispatch) => ({\n dispatch\n })) : typeof mapDispatchToProps === \"function\" ? (\n // @ts-ignore\n wrapMapToPropsFunc(mapDispatchToProps, \"mapDispatchToProps\")\n ) : createInvalidArgFactory(mapDispatchToProps, \"mapDispatchToProps\");\n}\n\n// src/connect/mapStateToProps.ts\nfunction mapStateToPropsFactory(mapStateToProps) {\n return !mapStateToProps ? wrapMapToPropsConstant(() => ({})) : typeof mapStateToProps === \"function\" ? (\n // @ts-ignore\n wrapMapToPropsFunc(mapStateToProps, \"mapStateToProps\")\n ) : createInvalidArgFactory(mapStateToProps, \"mapStateToProps\");\n}\n\n// src/connect/mergeProps.ts\nfunction defaultMergeProps(stateProps, dispatchProps, ownProps) {\n return { ...ownProps, ...stateProps, ...dispatchProps };\n}\nfunction wrapMergePropsFunc(mergeProps) {\n return function initMergePropsProxy(dispatch, { displayName, areMergedPropsEqual }) {\n let hasRunOnce = false;\n let mergedProps;\n return function mergePropsProxy(stateProps, dispatchProps, ownProps) {\n const nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps);\n if (hasRunOnce) {\n if (!areMergedPropsEqual(nextMergedProps, mergedProps))\n mergedProps = nextMergedProps;\n } else {\n hasRunOnce = true;\n mergedProps = nextMergedProps;\n if (process.env.NODE_ENV !== \"production\")\n verifyPlainObject(mergedProps, displayName, \"mergeProps\");\n }\n return mergedProps;\n };\n };\n}\nfunction mergePropsFactory(mergeProps) {\n return !mergeProps ? () => defaultMergeProps : typeof mergeProps === \"function\" ? wrapMergePropsFunc(mergeProps) : createInvalidArgFactory(mergeProps, \"mergeProps\");\n}\n\n// src/utils/batch.ts\nfunction defaultNoopBatch(callback) {\n callback();\n}\n\n// src/utils/Subscription.ts\nfunction createListenerCollection() {\n let first = null;\n let last = null;\n return {\n clear() {\n first = null;\n last = null;\n },\n notify() {\n defaultNoopBatch(() => {\n let listener = first;\n while (listener) {\n listener.callback();\n listener = listener.next;\n }\n });\n },\n get() {\n const listeners = [];\n let listener = first;\n while (listener) {\n listeners.push(listener);\n listener = listener.next;\n }\n return listeners;\n },\n subscribe(callback) {\n let isSubscribed = true;\n const listener = last = {\n callback,\n next: null,\n prev: last\n };\n if (listener.prev) {\n listener.prev.next = listener;\n } else {\n first = listener;\n }\n return function unsubscribe() {\n if (!isSubscribed || first === null)\n return;\n isSubscribed = false;\n if (listener.next) {\n listener.next.prev = listener.prev;\n } else {\n last = listener.prev;\n }\n if (listener.prev) {\n listener.prev.next = listener.next;\n } else {\n first = listener.next;\n }\n };\n }\n };\n}\nvar nullListeners = {\n notify() {\n },\n get: () => []\n};\nfunction createSubscription(store, parentSub) {\n let unsubscribe;\n let listeners = nullListeners;\n let subscriptionsAmount = 0;\n let selfSubscribed = false;\n function addNestedSub(listener) {\n trySubscribe();\n const cleanupListener = listeners.subscribe(listener);\n let removed = false;\n return () => {\n if (!removed) {\n removed = true;\n cleanupListener();\n tryUnsubscribe();\n }\n };\n }\n function notifyNestedSubs() {\n listeners.notify();\n }\n function handleChangeWrapper() {\n if (subscription.onStateChange) {\n subscription.onStateChange();\n }\n }\n function isSubscribed() {\n return selfSubscribed;\n }\n function trySubscribe() {\n subscriptionsAmount++;\n if (!unsubscribe) {\n unsubscribe = parentSub ? parentSub.addNestedSub(handleChangeWrapper) : store.subscribe(handleChangeWrapper);\n listeners = createListenerCollection();\n }\n }\n function tryUnsubscribe() {\n subscriptionsAmount--;\n if (unsubscribe && subscriptionsAmount === 0) {\n unsubscribe();\n unsubscribe = void 0;\n listeners.clear();\n listeners = nullListeners;\n }\n }\n function trySubscribeSelf() {\n if (!selfSubscribed) {\n selfSubscribed = true;\n trySubscribe();\n }\n }\n function tryUnsubscribeSelf() {\n if (selfSubscribed) {\n selfSubscribed = false;\n tryUnsubscribe();\n }\n }\n const subscription = {\n addNestedSub,\n notifyNestedSubs,\n handleChangeWrapper,\n isSubscribed,\n trySubscribe: trySubscribeSelf,\n tryUnsubscribe: tryUnsubscribeSelf,\n getListeners: () => listeners\n };\n return subscription;\n}\n\n// src/utils/useIsomorphicLayoutEffect.ts\nvar canUseDOM = !!(typeof window !== \"undefined\" && typeof window.document !== \"undefined\" && typeof window.document.createElement !== \"undefined\");\nvar isReactNative = typeof navigator !== \"undefined\" && navigator.product === \"ReactNative\";\nvar useIsomorphicLayoutEffect = canUseDOM || isReactNative ? React.useLayoutEffect : React.useEffect;\n\n// src/utils/shallowEqual.ts\nfunction is(x, y) {\n if (x === y) {\n return x !== 0 || y !== 0 || 1 / x === 1 / y;\n } else {\n return x !== x && y !== y;\n }\n}\nfunction shallowEqual(objA, objB) {\n if (is(objA, objB))\n return true;\n if (typeof objA !== \"object\" || objA === null || typeof objB !== \"object\" || objB === null) {\n return false;\n }\n const keysA = Object.keys(objA);\n const keysB = Object.keys(objB);\n if (keysA.length !== keysB.length)\n return false;\n for (let i = 0; i < keysA.length; i++) {\n if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {\n return false;\n }\n }\n return true;\n}\n\n// src/utils/hoistStatics.ts\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n $$typeof: true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n $$typeof: true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {\n [ForwardRef]: FORWARD_REF_STATICS,\n [Memo]: MEMO_STATICS\n};\nfunction getStatics(component) {\n if (isMemo(component)) {\n return MEMO_STATICS;\n }\n return TYPE_STATICS[component[\"$$typeof\"]] || REACT_STATICS;\n}\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent) {\n if (typeof sourceComponent !== \"string\") {\n if (objectPrototype) {\n const inheritedComponent = getPrototypeOf(sourceComponent);\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent);\n }\n }\n let keys = getOwnPropertyNames(sourceComponent);\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n const targetStatics = getStatics(targetComponent);\n const sourceStatics = getStatics(sourceComponent);\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n if (!KNOWN_STATICS[key] && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n const descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n try {\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {\n }\n }\n }\n }\n return targetComponent;\n}\n\n// src/components/connect.tsx\nvar useSyncExternalStore = notInitialized;\nvar initializeConnect = (fn) => {\n useSyncExternalStore = fn;\n};\nvar NO_SUBSCRIPTION_ARRAY = [null, null];\nvar stringifyComponent = (Comp) => {\n try {\n return JSON.stringify(Comp);\n } catch (err) {\n return String(Comp);\n }\n};\nfunction useIsomorphicLayoutEffectWithArgs(effectFunc, effectArgs, dependencies) {\n useIsomorphicLayoutEffect(() => effectFunc(...effectArgs), dependencies);\n}\nfunction captureWrapperProps(lastWrapperProps, lastChildProps, renderIsScheduled, wrapperProps, childPropsFromStoreUpdate, notifyNestedSubs) {\n lastWrapperProps.current = wrapperProps;\n renderIsScheduled.current = false;\n if (childPropsFromStoreUpdate.current) {\n childPropsFromStoreUpdate.current = null;\n notifyNestedSubs();\n }\n}\nfunction subscribeUpdates(shouldHandleStateChanges, store, subscription, childPropsSelector, lastWrapperProps, lastChildProps, renderIsScheduled, isMounted, childPropsFromStoreUpdate, notifyNestedSubs, additionalSubscribeListener) {\n if (!shouldHandleStateChanges)\n return () => {\n };\n let didUnsubscribe = false;\n let lastThrownError = null;\n const checkForUpdates = () => {\n if (didUnsubscribe || !isMounted.current) {\n return;\n }\n const latestStoreState = store.getState();\n let newChildProps, error;\n try {\n newChildProps = childPropsSelector(\n latestStoreState,\n lastWrapperProps.current\n );\n } catch (e) {\n error = e;\n lastThrownError = e;\n }\n if (!error) {\n lastThrownError = null;\n }\n if (newChildProps === lastChildProps.current) {\n if (!renderIsScheduled.current) {\n notifyNestedSubs();\n }\n } else {\n lastChildProps.current = newChildProps;\n childPropsFromStoreUpdate.current = newChildProps;\n renderIsScheduled.current = true;\n additionalSubscribeListener();\n }\n };\n subscription.onStateChange = checkForUpdates;\n subscription.trySubscribe();\n checkForUpdates();\n const unsubscribeWrapper = () => {\n didUnsubscribe = true;\n subscription.tryUnsubscribe();\n subscription.onStateChange = null;\n if (lastThrownError) {\n throw lastThrownError;\n }\n };\n return unsubscribeWrapper;\n}\nfunction strictEqual(a, b) {\n return a === b;\n}\nvar hasWarnedAboutDeprecatedPureOption = false;\nfunction connect(mapStateToProps, mapDispatchToProps, mergeProps, {\n // The `pure` option has been removed, so TS doesn't like us destructuring this to check its existence.\n // @ts-ignore\n pure,\n areStatesEqual = strictEqual,\n areOwnPropsEqual = shallowEqual,\n areStatePropsEqual = shallowEqual,\n areMergedPropsEqual = shallowEqual,\n // use React's forwardRef to expose a ref of the wrapped component\n forwardRef = false,\n // the context consumer to use\n context = ReactReduxContext\n} = {}) {\n if (process.env.NODE_ENV !== \"production\") {\n if (pure !== void 0 && !hasWarnedAboutDeprecatedPureOption) {\n hasWarnedAboutDeprecatedPureOption = true;\n warning(\n 'The `pure` option has been removed. `connect` is now always a \"pure/memoized\" component'\n );\n }\n }\n const Context = context;\n const initMapStateToProps = mapStateToPropsFactory(mapStateToProps);\n const initMapDispatchToProps = mapDispatchToPropsFactory(mapDispatchToProps);\n const initMergeProps = mergePropsFactory(mergeProps);\n const shouldHandleStateChanges = Boolean(mapStateToProps);\n const wrapWithConnect = (WrappedComponent) => {\n if (process.env.NODE_ENV !== \"production\") {\n const isValid = /* @__PURE__ */ isValidElementType(WrappedComponent);\n if (!isValid)\n throw new Error(\n `You must pass a component to the function returned by connect. Instead received ${stringifyComponent(\n WrappedComponent\n )}`\n );\n }\n const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || \"Component\";\n const displayName = `Connect(${wrappedComponentName})`;\n const selectorFactoryOptions = {\n shouldHandleStateChanges,\n displayName,\n wrappedComponentName,\n WrappedComponent,\n // @ts-ignore\n initMapStateToProps,\n // @ts-ignore\n initMapDispatchToProps,\n initMergeProps,\n areStatesEqual,\n areStatePropsEqual,\n areOwnPropsEqual,\n areMergedPropsEqual\n };\n function ConnectFunction(props) {\n const [propsContext, reactReduxForwardedRef, wrapperProps] = React.useMemo(() => {\n const { reactReduxForwardedRef: reactReduxForwardedRef2, ...wrapperProps2 } = props;\n return [props.context, reactReduxForwardedRef2, wrapperProps2];\n }, [props]);\n const ContextToUse = React.useMemo(() => {\n let ResultContext = Context;\n if (propsContext?.Consumer) {\n if (process.env.NODE_ENV !== \"production\") {\n const isValid = /* @__PURE__ */ isContextConsumer(\n // @ts-ignore\n /* @__PURE__ */ React.createElement(propsContext.Consumer, null)\n );\n if (!isValid) {\n throw new Error(\n \"You must pass a valid React context consumer as `props.context`\"\n );\n }\n ResultContext = propsContext;\n }\n }\n return ResultContext;\n }, [propsContext, Context]);\n const contextValue = React.useContext(ContextToUse);\n const didStoreComeFromProps = Boolean(props.store) && Boolean(props.store.getState) && Boolean(props.store.dispatch);\n const didStoreComeFromContext = Boolean(contextValue) && Boolean(contextValue.store);\n if (process.env.NODE_ENV !== \"production\" && !didStoreComeFromProps && !didStoreComeFromContext) {\n throw new Error(\n `Could not find \"store\" in the context of \"${displayName}\". Either wrap the root component in a , or pass a custom React context provider to and the corresponding React context consumer to ${displayName} in connect options.`\n );\n }\n const store = didStoreComeFromProps ? props.store : contextValue.store;\n const getServerState = didStoreComeFromContext ? contextValue.getServerState : store.getState;\n const childPropsSelector = React.useMemo(() => {\n return finalPropsSelectorFactory(store.dispatch, selectorFactoryOptions);\n }, [store]);\n const [subscription, notifyNestedSubs] = React.useMemo(() => {\n if (!shouldHandleStateChanges)\n return NO_SUBSCRIPTION_ARRAY;\n const subscription2 = createSubscription(\n store,\n didStoreComeFromProps ? void 0 : contextValue.subscription\n );\n const notifyNestedSubs2 = subscription2.notifyNestedSubs.bind(subscription2);\n return [subscription2, notifyNestedSubs2];\n }, [store, didStoreComeFromProps, contextValue]);\n const overriddenContextValue = React.useMemo(() => {\n if (didStoreComeFromProps) {\n return contextValue;\n }\n return {\n ...contextValue,\n subscription\n };\n }, [didStoreComeFromProps, contextValue, subscription]);\n const lastChildProps = React.useRef(void 0);\n const lastWrapperProps = React.useRef(wrapperProps);\n const childPropsFromStoreUpdate = React.useRef(void 0);\n const renderIsScheduled = React.useRef(false);\n const isMounted = React.useRef(false);\n const latestSubscriptionCallbackError = React.useRef(\n void 0\n );\n useIsomorphicLayoutEffect(() => {\n isMounted.current = true;\n return () => {\n isMounted.current = false;\n };\n }, []);\n const actualChildPropsSelector = React.useMemo(() => {\n const selector = () => {\n if (childPropsFromStoreUpdate.current && wrapperProps === lastWrapperProps.current) {\n return childPropsFromStoreUpdate.current;\n }\n return childPropsSelector(store.getState(), wrapperProps);\n };\n return selector;\n }, [store, wrapperProps]);\n const subscribeForReact = React.useMemo(() => {\n const subscribe = (reactListener) => {\n if (!subscription) {\n return () => {\n };\n }\n return subscribeUpdates(\n shouldHandleStateChanges,\n store,\n subscription,\n // @ts-ignore\n childPropsSelector,\n lastWrapperProps,\n lastChildProps,\n renderIsScheduled,\n isMounted,\n childPropsFromStoreUpdate,\n notifyNestedSubs,\n reactListener\n );\n };\n return subscribe;\n }, [subscription]);\n useIsomorphicLayoutEffectWithArgs(captureWrapperProps, [\n lastWrapperProps,\n lastChildProps,\n renderIsScheduled,\n wrapperProps,\n childPropsFromStoreUpdate,\n notifyNestedSubs\n ]);\n let actualChildProps;\n try {\n actualChildProps = useSyncExternalStore(\n // TODO We're passing through a big wrapper that does a bunch of extra side effects besides subscribing\n subscribeForReact,\n // TODO This is incredibly hacky. We've already processed the store update and calculated new child props,\n // TODO and we're just passing that through so it triggers a re-render for us rather than relying on `uSES`.\n actualChildPropsSelector,\n getServerState ? () => childPropsSelector(getServerState(), wrapperProps) : actualChildPropsSelector\n );\n } catch (err) {\n if (latestSubscriptionCallbackError.current) {\n ;\n err.message += `\nThe error may be correlated with this previous error:\n${latestSubscriptionCallbackError.current.stack}\n\n`;\n }\n throw err;\n }\n useIsomorphicLayoutEffect(() => {\n latestSubscriptionCallbackError.current = void 0;\n childPropsFromStoreUpdate.current = void 0;\n lastChildProps.current = actualChildProps;\n });\n const renderedWrappedComponent = React.useMemo(() => {\n return (\n // @ts-ignore\n /* @__PURE__ */ React.createElement(\n WrappedComponent,\n {\n ...actualChildProps,\n ref: reactReduxForwardedRef\n }\n )\n );\n }, [reactReduxForwardedRef, WrappedComponent, actualChildProps]);\n const renderedChild = React.useMemo(() => {\n if (shouldHandleStateChanges) {\n return /* @__PURE__ */ React.createElement(ContextToUse.Provider, { value: overriddenContextValue }, renderedWrappedComponent);\n }\n return renderedWrappedComponent;\n }, [ContextToUse, renderedWrappedComponent, overriddenContextValue]);\n return renderedChild;\n }\n const _Connect = React.memo(ConnectFunction);\n const Connect = _Connect;\n Connect.WrappedComponent = WrappedComponent;\n Connect.displayName = ConnectFunction.displayName = displayName;\n if (forwardRef) {\n const _forwarded = React.forwardRef(\n function forwardConnectRef(props, ref) {\n return /* @__PURE__ */ React.createElement(Connect, { ...props, reactReduxForwardedRef: ref });\n }\n );\n const forwarded = _forwarded;\n forwarded.displayName = displayName;\n forwarded.WrappedComponent = WrappedComponent;\n return /* @__PURE__ */ hoistNonReactStatics(forwarded, WrappedComponent);\n }\n return /* @__PURE__ */ hoistNonReactStatics(Connect, WrappedComponent);\n };\n return wrapWithConnect;\n}\nvar connect_default = connect;\n\n// src/components/Provider.tsx\nfunction Provider({\n store,\n context,\n children,\n serverState,\n stabilityCheck = \"once\",\n identityFunctionCheck = \"once\"\n}) {\n const contextValue = React.useMemo(() => {\n const subscription = createSubscription(store);\n return {\n store,\n subscription,\n getServerState: serverState ? () => serverState : void 0,\n stabilityCheck,\n identityFunctionCheck\n };\n }, [store, serverState, stabilityCheck, identityFunctionCheck]);\n const previousState = React.useMemo(() => store.getState(), [store]);\n useIsomorphicLayoutEffect(() => {\n const { subscription } = contextValue;\n subscription.onStateChange = subscription.notifyNestedSubs;\n subscription.trySubscribe();\n if (previousState !== store.getState()) {\n subscription.notifyNestedSubs();\n }\n return () => {\n subscription.tryUnsubscribe();\n subscription.onStateChange = void 0;\n };\n }, [contextValue, previousState]);\n const Context = context || ReactReduxContext;\n return /* @__PURE__ */ React.createElement(Context.Provider, { value: contextValue }, children);\n}\nvar Provider_default = Provider;\n\n// src/hooks/useStore.ts\nfunction createStoreHook(context = ReactReduxContext) {\n const useReduxContext2 = context === ReactReduxContext ? useReduxContext : (\n // @ts-ignore\n createReduxContextHook(context)\n );\n const useStore2 = () => {\n const { store } = useReduxContext2();\n return store;\n };\n Object.assign(useStore2, {\n withTypes: () => useStore2\n });\n return useStore2;\n}\nvar useStore = /* @__PURE__ */ createStoreHook();\n\n// src/hooks/useDispatch.ts\nfunction createDispatchHook(context = ReactReduxContext) {\n const useStore2 = context === ReactReduxContext ? useStore : createStoreHook(context);\n const useDispatch2 = () => {\n const store = useStore2();\n return store.dispatch;\n };\n Object.assign(useDispatch2, {\n withTypes: () => useDispatch2\n });\n return useDispatch2;\n}\nvar useDispatch = /* @__PURE__ */ createDispatchHook();\n\n// src/exports.ts\nvar batch = defaultNoopBatch;\n\n// src/index.ts\ninitializeUseSelector(useSyncExternalStoreWithSelector2);\ninitializeConnect(React2.useSyncExternalStore);\nexport {\n Provider_default as Provider,\n ReactReduxContext,\n batch,\n connect_default as connect,\n createDispatchHook,\n createSelectorHook,\n createStoreHook,\n shallowEqual,\n useDispatch,\n useSelector,\n useStore\n};\n//# sourceMappingURL=react-redux.mjs.map","import { useLayoutEffect } from \"react\"\nimport { useLocation } from \"react-router-dom\"\n\nconst ScrollToTop = () => {\n const { pathname } = useLocation()\n\n useLayoutEffect(() => {\n window.scrollTo(0, 0)\n }, [pathname])\n\n return null\n}\n\nexport default ScrollToTop","/**\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 */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","// This is a magic string replaced by rollup\n\nconst SDK_VERSION = \"8.47.0\" ;\n\nexport { SDK_VERSION };\n//# sourceMappingURL=version.js.map\n","import { SDK_VERSION } from './version.js';\n\n/** Get's the global object for the current JavaScript runtime */\nconst GLOBAL_OBJ = globalThis ;\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 */\nfunction getGlobalSingleton(name, creator, obj) {\n const gbl = (obj || GLOBAL_OBJ) ;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const versionedCarrier = (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});\n return versionedCarrier[name] || (versionedCarrier[name] = creator());\n}\n\nexport { GLOBAL_OBJ, getGlobalSingleton };\n//# sourceMappingURL=worldwide.js.map\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 */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { getGlobalSingleton, GLOBAL_OBJ } from './worldwide.js';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nconst CONSOLE_LEVELS = [\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'log',\n 'assert',\n 'trace',\n] ;\n\n/** This may be mutated by the console instrumentation. */\nconst originalConsoleMethods\n\n = {};\n\n/** JSDoc */\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 */\nfunction consoleSandbox(callback) {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console ;\n const wrappedFuncs = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) ;\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\n const originalConsoleMethod = originalConsoleMethods[level] ;\n wrappedFuncs[level] = console[level] ;\n console[level] = originalConsoleMethod;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] ;\n });\n }\n}\n\nfunction makeLogger() {\n let enabled = false;\n const logger = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n isEnabled: () => enabled,\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = (...args) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger ;\n}\n\n/**\n * This is a logger singleton which either logs things or no-ops if logging is not enabled.\n * The logger is a singleton on the carrier, to ensure that a consistent logger is used throughout the SDK.\n */\nconst logger = getGlobalSingleton('logger', makeLogger);\n\nexport { CONSOLE_LEVELS, consoleSandbox, logger, originalConsoleMethods };\n//# sourceMappingURL=logger.js.map\n","const STACKTRACE_FRAME_LIMIT = 50;\nconst 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 */\nfunction createStackParser(...parsers) {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack, skipFirstLines = 0, framesToPop = 0) => {\n const frames = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirstLines; i < lines.length; i++) {\n const line = lines[i] ;\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT + 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 */\nfunction stackParserFromStackParserOptions(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 */\nfunction stripSentryFramesAndReverse(stack) {\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 hub itself, making it:\n //\n // Sentry.captureException()\n // getCurrentHub().captureException()\n //\n // instead of just the top `Sentry` call itself.\n // This forces us to possibly strip an additional frame in the exact same was as above.\n if (STRIP_FRAME_REGEXP.test(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) {\n return arr[arr.length - 1] || {};\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nfunction getFunctionName(fn) {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Get's stack frames from an event without needing to check for undefined properties.\n */\nfunction getFramesFromEvent(event) {\n const exception = event.exception;\n\n if (exception) {\n const frames = [];\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 (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n\nexport { UNKNOWN_FUNCTION, createStackParser, getFramesFromEvent, getFunctionName, stackParserFromStackParserOptions, stripSentryFramesAndReverse };\n//# sourceMappingURL=stacktrace.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { logger } from '../logger.js';\nimport { getFunctionName } from '../stacktrace.js';\n\n// We keep the handlers globally\nconst handlers = {};\nconst instrumented = {};\n\n/** Add a handler function. */\nfunction addHandler(type, handler) {\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 */\nfunction resetInstrumentationHandlers() {\n Object.keys(handlers).forEach(key => {\n handlers[key ] = undefined;\n });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nfunction maybeInstrument(type, instrumentFn) {\n if (!instrumented[type]) {\n instrumented[type] = true;\n try {\n instrumentFn();\n } catch (e) {\n DEBUG_BUILD && logger.error(`Error while instrumenting ${type}`, e);\n }\n }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nfunction triggerHandlers(type, data) {\n const typeHandlers = type && handlers[type];\n if (!typeHandlers) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nexport { addHandler, maybeInstrument, resetInstrumentationHandlers, triggerHandlers };\n//# sourceMappingURL=handlers.js.map\n","import { GLOBAL_OBJ } from '../worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\nlet _oldOnErrorHandler = 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 */\nfunction addGlobalErrorInstrumentationHandler(handler) {\n const type = 'error';\n addHandler(type, handler);\n maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError() {\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,\n url,\n line,\n column,\n error,\n ) {\n const handlerData = {\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\nexport { addGlobalErrorInstrumentationHandler };\n//# sourceMappingURL=globalError.js.map\n","import { GLOBAL_OBJ } from '../worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\nlet _oldOnUnhandledRejectionHandler = 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 */\nfunction addGlobalUnhandledRejectionInstrumentationHandler(\n handler,\n) {\n const type = 'unhandledrejection';\n addHandler(type, handler);\n maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection() {\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) {\n const handlerData = 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\nexport { addGlobalUnhandledRejectionInstrumentationHandler };\n//# sourceMappingURL=globalUnhandledRejection.js.map\n","import { SDK_VERSION } from './utils-hoist/version.js';\nimport { GLOBAL_OBJ } from './utils-hoist/worldwide.js';\n\n/**\n * An object that contains globally accessible properties and maintains a scope stack.\n * @hidden\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 **/\nfunction getMainCarrier() {\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. */\nfunction getSentryCarrier(carrier) {\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\nexport { getMainCarrier, getSentryCarrier };\n//# sourceMappingURL=carrier.js.map\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 */\nfunction isError(wat) {\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, className) {\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 */\nfunction isErrorEvent(wat) {\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 */\nfunction isDOMError(wat) {\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 */\nfunction isDOMException(wat) {\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 */\nfunction isString(wat) {\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 */\nfunction isParameterizedString(wat) {\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 */\nfunction isPrimitive(wat) {\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 */\nfunction isPlainObject(wat) {\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 */\nfunction isEvent(wat) {\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 */\nfunction isElement(wat) {\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 */\nfunction isRegExp(wat) {\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 */\nfunction isThenable(wat) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isSyntheticEvent(wat) {\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 */\nfunction isInstanceOf(wat, base) {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\n/**\n * Checks whether given value's type is a Vue ViewModel.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isVueViewModel(wat) {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n return !!(typeof wat === 'object' && wat !== null && ((wat ).__isVue || (wat )._isVue));\n}\n\nexport { isDOMError, isDOMException, isElement, isError, isErrorEvent, isEvent, isInstanceOf, isParameterizedString, isPlainObject, isPrimitive, isRegExp, isString, isSyntheticEvent, isThenable, isVueViewModel };\n//# sourceMappingURL=is.js.map\n","import { isString } from './is.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\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 */\nfunction htmlTreeAsString(\n elem,\n options = {},\n) {\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 ;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el, keyAttrs) {\n const elem = el\n\n;\n\n const out = [];\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n // @ts-expect-error WINDOW has HTMLElement\n if (WINDOW.HTMLElement) {\n // If using the component name annotation plugin, this value may be available on the DOM node\n if (elem instanceof HTMLElement && elem.dataset) {\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 =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n 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 */\nfunction getLocationHref() {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existence of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getDomElement(selector) {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) ;\n }\n return null;\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` 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 */\nfunction getComponentName(elem) {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem ;\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\nexport { getComponentName, getDomElement, getLocationHref, htmlTreeAsString };\n//# sourceMappingURL=browser.js.map\n","import { isVueViewModel, isString, isRegExp } from './is.js';\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 */\nfunction truncate(str, max = 0) {\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 */\nfunction snipLine(line, colno) {\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 */\nfunction safeJoin(input, delimiter) {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/8981\n if (isVueViewModel(value)) {\n output.push('[VueViewModel]');\n } else {\n output.push(String(value));\n }\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nfunction isMatchingPattern(\n value,\n pattern,\n requireExactStringMatch = false,\n) {\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 */\nfunction stringMatchesSomePattern(\n testString,\n patterns = [],\n requireExactStringMatch = false,\n) {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n\nexport { isMatchingPattern, safeJoin, snipLine, stringMatchesSomePattern, truncate };\n//# sourceMappingURL=string.js.map\n","import { htmlTreeAsString } from './browser.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { isError, isEvent, isInstanceOf, isElement, isPlainObject, isPrimitive } from './is.js';\nimport { logger } from './logger.js';\nimport { truncate } from './string.js';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nfunction fill(source, name, replacementFactory) {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] ;\n const wrapped = replacementFactory(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 (typeof wrapped === 'function') {\n markFunctionWrapped(wrapped, original);\n }\n\n try {\n source[name] = wrapped;\n } catch (e) {\n DEBUG_BUILD && logger.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 */\nfunction addNonEnumerableProperty(obj, name, value) {\n try {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n } catch (o_O) {\n DEBUG_BUILD && logger.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nfunction markFunctionWrapped(wrapped, original) {\n try {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n } catch (o_O) {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction getOriginalFunction(func) {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n *\n * @deprecated This function is deprecated and will be removed in the next major version of the SDK.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction urlEncode(object) {\n return Object.entries(object)\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor\n * an Error.\n */\nfunction convertToPlainObject(value)\n\n {\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\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) {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj) {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj )[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 */\nfunction extractExceptionKeysForMessage(exception, maxLength = 40) {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n const firstKey = keys[0];\n\n if (!firstKey) {\n return '[object has no keys]';\n }\n\n if (firstKey.length >= maxLength) {\n return truncate(firstKey, maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nfunction dropUndefinedKeys(inputValue) {\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, memoizationMap) {\n if (isPojo(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal ;\n }\n\n const returnValue = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.getOwnPropertyNames(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue ;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal ;\n }\n\n const returnValue = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue ;\n }\n\n return inputValue;\n}\n\nfunction isPojo(input) {\n if (!isPlainObject(input)) {\n return false;\n }\n\n try {\n const name = (Object.getPrototypeOf(input) ).constructor.name;\n return !name || name === 'Object';\n } catch (e2) {\n return true;\n }\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nfunction objectify(wat) {\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 ).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\nexport { addNonEnumerableProperty, convertToPlainObject, dropUndefinedKeys, extractExceptionKeysForMessage, fill, getOriginalFunction, markFunctionWrapped, objectify, urlEncode };\n//# sourceMappingURL=object.js.map\n","import { GLOBAL_OBJ } from './worldwide.js';\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 */\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n *\n * TODO(v8): Return type should be rounded.\n */\nfunction dateTimestampInSeconds() {\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() {\n const { performance } = GLOBAL_OBJ ;\n if (!performance || !performance.now) {\n return dateTimestampInSeconds;\n }\n\n // Some browser and environments don't have a timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n const approxStartingTimeOrigin = Date.now() - performance.now();\n const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nconst timestampInSeconds = createUnixTimestampInSecondsFunc();\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n *\n * @deprecated This variable will be removed in the next major version.\n */\nlet _browserPerformanceTimeOriginMode;\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 */\nconst browserPerformanceTimeOrigin = (() => {\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 ;\n if (!performance || !performance.now) {\n // eslint-disable-next-line deprecation/deprecation\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n // eslint-disable-next-line deprecation/deprecation\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n // eslint-disable-next-line deprecation/deprecation\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n // eslint-disable-next-line deprecation/deprecation\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n\nexport { _browserPerformanceTimeOriginMode, browserPerformanceTimeOrigin, dateTimestampInSeconds, timestampInSeconds };\n//# sourceMappingURL=time.js.map\n","import { addNonEnumerableProperty } from './object.js';\nimport { snipLine } from './string.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nfunction uuid4() {\n const gbl = GLOBAL_OBJ ;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n let getRandomByte = () => Math.random() * 16;\n try {\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto && crypto.getRandomValues) {\n getRandomByte = () => {\n // crypto.getRandomValues might return undefined instead of the typed array\n // in old Chromium versions (e.g. 23.0.1235.0 (151422))\n // However, `typedArray` is still filled in-place.\n // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray\n const typedArray = new Uint8Array(1);\n crypto.getRandomValues(typedArray);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return typedArray[0];\n };\n }\n } catch (_) {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event) {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nfunction getEventDescription(event) {\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 */\nfunction addExceptionTypeValue(event, value, type) {\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 */\nfunction addExceptionMechanism(event, newMechanism) {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\n\nfunction _parseInt(input) {\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 */\nfunction parseSemver(input) {\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 */\nfunction addContextToFrame(lines, frame, linesOfContext = 5) {\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) => 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) => 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 */\nfunction checkOrSetAlreadyCaught(exception) {\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 , '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\nfunction isAlreadyCaptured(exception) {\n try {\n return (exception ).__sentry_captured__;\n } catch (e) {} // eslint-disable-line no-empty\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n *\n * @deprecated This function has been deprecated and will not be replaced.\n */\nfunction arrayify(maybeArray) {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n\nexport { addContextToFrame, addExceptionMechanism, addExceptionTypeValue, arrayify, checkOrSetAlreadyCaught, getEventDescription, parseSemver, uuid4 };\n//# sourceMappingURL=misc.js.map\n","import { isThenable } from './is.js';\n\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** SyncPromise internal states */\nvar States; (function (States) {\n /** Pending */\n const PENDING = 0; States[States[\"PENDING\"] = PENDING] = \"PENDING\";\n /** Resolved / OK */\n const RESOLVED = 1; States[States[\"RESOLVED\"] = RESOLVED] = \"RESOLVED\";\n /** Rejected / Error */\n const REJECTED = 2; States[States[\"REJECTED\"] = REJECTED] = \"REJECTED\";\n})(States || (States = {}));\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\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 */\nfunction resolvedSyncPromise(value) {\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 */\nfunction rejectedSyncPromise(reason) {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise {\n\n constructor(\n executor,\n ) {SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this);\n this._state = States.PENDING;\n this._handlers = [];\n\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n then(\n onfulfilled,\n onrejected,\n ) {\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 );\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n catch(\n onrejected,\n ) {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n finally(onfinally) {\n return new SyncPromise((resolve, reject) => {\n let val;\n let isRejected;\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 );\n });\n });\n }\n\n /** JSDoc */\n __init() {this._resolve = (value) => {\n this._setResult(States.RESOLVED, value);\n };}\n\n /** JSDoc */\n __init2() {this._reject = (reason) => {\n this._setResult(States.REJECTED, reason);\n };}\n\n /** JSDoc */\n __init3() {this._setResult = (state, value) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value ).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };}\n\n /** JSDoc */\n __init4() {this._executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n handler[1](this._value );\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };}\n}\n\nexport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise };\n//# sourceMappingURL=syncpromise.js.map\n","import './utils-hoist/version.js';\nimport './utils-hoist/debug-build.js';\nimport './utils-hoist/logger.js';\nimport { dropUndefinedKeys } from './utils-hoist/object.js';\nimport { timestampInSeconds } from './utils-hoist/time.js';\nimport { uuid4 } from './utils-hoist/misc.js';\nimport './utils-hoist/syncpromise.js';\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 */\nfunction makeSession(context) {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nfunction updateSession(session, context = {}) {\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 */\nfunction closeSession(session, status) {\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) {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n\nexport { closeSession, makeSession, updateSession };\n//# sourceMappingURL=session.js.map\n","import { uuid4 } from './misc.js';\n\n/**\n * Returns a new minimal propagation context.\n *\n * @deprecated Use `generateTraceId` and `generateSpanId` instead.\n */\nfunction generatePropagationContext() {\n return {\n traceId: generateTraceId(),\n spanId: generateSpanId(),\n };\n}\n\n/**\n * Generate a random, valid trace ID.\n */\nfunction generateTraceId() {\n return uuid4();\n}\n\n/**\n * Generate a random, valid span ID.\n */\nfunction generateSpanId() {\n return uuid4().substring(16);\n}\n\nexport { generatePropagationContext, generateSpanId, generateTraceId };\n//# sourceMappingURL=propagationContext.js.map\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 */\nfunction merge(initialObj, mergeObj, levels = 2) {\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 && mergeObj && 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\nexport { merge };\n//# sourceMappingURL=merge.js.map\n","import { addNonEnumerableProperty } from '../utils-hoist/object.js';\n\nconst SCOPE_SPAN_FIELD = '_sentrySpan';\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 */\nfunction _setSpanForScope(scope, span) {\n if (span) {\n addNonEnumerableProperty(scope , SCOPE_SPAN_FIELD, span);\n } else {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete (scope )[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 */\nfunction _getSpanForScope(scope) {\n return scope[SCOPE_SPAN_FIELD];\n}\n\nexport { _getSpanForScope, _setSpanForScope };\n//# sourceMappingURL=spanOnScope.js.map\n","import { updateSession } from './session.js';\nimport { isPlainObject } from './utils-hoist/is.js';\nimport { logger } from './utils-hoist/logger.js';\nimport { uuid4 } from './utils-hoist/misc.js';\nimport { generateTraceId, generateSpanId } from './utils-hoist/propagationContext.js';\nimport { dateTimestampInSeconds } from './utils-hoist/time.js';\nimport { merge } from './utils/merge.js';\nimport { _setSpanForScope, _getSpanForScope } from './utils/spanOnScope.js';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information.\n */\nclass ScopeClass {\n /** Flag if notifying is happening. */\n\n /** Callback for client to receive scope changes. */\n\n /** Callback list that will be called during event processing. */\n\n /** Array of breadcrumbs. */\n\n /** User */\n\n /** Tags */\n\n /** Extra */\n\n /** Contexts */\n\n /** Attachments */\n\n /** Propagation Context for distributed tracing */\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\n /** Fingerprint */\n\n /** Severity */\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\n /** Session */\n\n /** Request Mode Session Status */\n // eslint-disable-next-line deprecation/deprecation\n\n /** The client on this scope */\n\n /** Contains the last event id of a captured event. */\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 constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = {\n traceId: generateTraceId(),\n spanId: generateSpanId(),\n };\n }\n\n /**\n * @inheritDoc\n */\n clone() {\n const newScope = new ScopeClass();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\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._requestSession = this._requestSession;\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 * @inheritDoc\n */\n setClient(client) {\n this._client = client;\n }\n\n /**\n * @inheritDoc\n */\n setLastEventId(lastEventId) {\n this._lastEventId = lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n getClient() {\n return this._client ;\n }\n\n /**\n * @inheritDoc\n */\n lastEventId() {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n addScopeListener(callback) {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n addEventProcessor(callback) {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setUser(user) {\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 * @inheritDoc\n */\n getUser() {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n getRequestSession() {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n setRequestSession(requestSession) {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTags(tags) {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setExtras(extras) {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setExtra(key, extra) {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setFingerprint(fingerprint) {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setLevel(level) {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTransactionName(name) {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setContext(key, context) {\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 * @inheritDoc\n */\n setSession(session) {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getSession() {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n update(captureContext) {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n const [scopeInstance, requestSession] =\n scopeToMerge instanceof Scope\n ? // eslint-disable-next-line deprecation/deprecation\n [scopeToMerge.getScopeData(), scopeToMerge.getRequestSession()]\n : isPlainObject(scopeToMerge)\n ? [captureContext , (captureContext ).requestSession]\n : [];\n\n const { tags, extra, user, contexts, level, fingerprint = [], propagationContext } = scopeInstance || {};\n\n this._tags = { ...this._tags, ...tags };\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 if (requestSession) {\n this._requestSession = requestSession;\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n clear() {\n // client is not cleared here on purpose!\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._session = undefined;\n _setSpanForScope(this, undefined);\n this._attachments = [];\n this.setPropagationContext({ traceId: generateTraceId() });\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n addBreadcrumb(breadcrumb, maxBreadcrumbs) {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n\n const breadcrumbs = this._breadcrumbs;\n breadcrumbs.push(mergedBreadcrumb);\n this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getLastBreadcrumb() {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n clearBreadcrumbs() {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n addAttachment(attachment) {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n clearAttachments() {\n this._attachments = [];\n return this;\n }\n\n /** @inheritDoc */\n getScopeData() {\n return {\n breadcrumbs: this._breadcrumbs,\n attachments: this._attachments,\n contexts: this._contexts,\n tags: this._tags,\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 * @inheritDoc\n */\n setSDKProcessingMetadata(newData) {\n this._sdkProcessingMetadata = merge(this._sdkProcessingMetadata, newData, 2);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setPropagationContext(\n context,\n ) {\n this._propagationContext = {\n // eslint-disable-next-line deprecation/deprecation\n spanId: generateSpanId(),\n ...context,\n };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getPropagationContext() {\n return this._propagationContext;\n }\n\n /**\n * @inheritDoc\n */\n captureException(exception, hint) {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureMessage(message, level, hint) {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint) {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n _notifyScopeListeners() {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\n/**\n * Holds additional event information.\n */\nconst Scope = ScopeClass;\n\n/**\n * Holds additional event information.\n */\n\nexport { Scope };\n//# sourceMappingURL=scope.js.map\n","import { Scope } from './scope.js';\nimport { getGlobalSingleton } from './utils-hoist/worldwide.js';\n\n/** Get the default current scope. */\nfunction getDefaultCurrentScope() {\n return getGlobalSingleton('defaultCurrentScope', () => new Scope());\n}\n\n/** Get the default isolation scope. */\nfunction getDefaultIsolationScope() {\n return getGlobalSingleton('defaultIsolationScope', () => new Scope());\n}\n\nexport { getDefaultCurrentScope, getDefaultIsolationScope };\n//# sourceMappingURL=defaultScopes.js.map\n","import { getDefaultCurrentScope, getDefaultIsolationScope } from '../defaultScopes.js';\nimport { Scope } from '../scope.js';\nimport { isThenable } from '../utils-hoist/is.js';\nimport { getMainCarrier, getSentryCarrier } from '../carrier.js';\n\n/**\n * This is an object that holds a stack of scopes.\n */\nclass AsyncContextStack {\n\n constructor(scope, isolationScope) {\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 withScope(callback) {\n const scope = this._pushScope();\n\n let maybePromiseResult;\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 getClient() {\n return this.getStackTop().client ;\n }\n\n /**\n * Returns the scope of the top stack.\n */\n getScope() {\n return this.getStackTop().scope;\n }\n\n /**\n * Get the isolation scope for the stack.\n */\n getIsolationScope() {\n return this._isolationScope;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n */\n getStackTop() {\n return this._stack[this._stack.length - 1] ;\n }\n\n /**\n * Push a scope to the stack.\n */\n _pushScope() {\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 _popScope() {\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() {\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) {\n return getAsyncContextStack().withScope(callback);\n}\n\nfunction withSetScope(scope, callback) {\n const stack = getAsyncContextStack() ;\n return stack.withScope(() => {\n stack.getStackTop().scope = scope;\n return callback(scope);\n });\n}\n\nfunction withIsolationScope(callback) {\n return getAsyncContextStack().withScope(() => {\n return callback(getAsyncContextStack().getIsolationScope());\n });\n}\n\n/**\n * Get the stack-based async context strategy.\n */\nfunction getStackAsyncContextStrategy() {\n return {\n withIsolationScope,\n withScope,\n withSetScope,\n withSetIsolationScope: (_isolationScope, callback) => {\n return withIsolationScope(callback);\n },\n getCurrentScope: () => getAsyncContextStack().getScope(),\n getIsolationScope: () => getAsyncContextStack().getIsolationScope(),\n };\n}\n\nexport { AsyncContextStack, getStackAsyncContextStrategy };\n//# sourceMappingURL=stackStrategy.js.map\n","import { getMainCarrier, getSentryCarrier } from '../carrier.js';\nimport { getStackAsyncContextStrategy } from './stackStrategy.js';\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nfunction setAsyncContextStrategy(strategy) {\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 */\nfunction getAsyncContextStrategy(carrier) {\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\nexport { getAsyncContextStrategy, setAsyncContextStrategy };\n//# sourceMappingURL=index.js.map\n","import { getAsyncContextStrategy } from './asyncContext/index.js';\nimport { getMainCarrier } from './carrier.js';\nimport { Scope } from './scope.js';\nimport { dropUndefinedKeys } from './utils-hoist/object.js';\nimport { getGlobalSingleton } from './utils-hoist/worldwide.js';\n\n/**\n * Get the currently active scope.\n */\nfunction getCurrentScope() {\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 */\nfunction getIsolationScope() {\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 */\nfunction getGlobalScope() {\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 */\n\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nfunction withScope(\n ...rest\n) {\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 */\n\n/**\n * Either creates a new active isolation scope, or sets the given isolation scope as active scope in the given callback.\n */\nfunction withIsolationScope(\n ...rest\n\n) {\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 */\nfunction getClient() {\n return getCurrentScope().getClient();\n}\n\n/**\n * Get a trace context for the given scope.\n */\nfunction getTraceContextFromScope(scope) {\n const propagationContext = scope.getPropagationContext();\n\n // TODO(v9): Use generateSpanId() instead of spanId\n // eslint-disable-next-line deprecation/deprecation\n const { traceId, spanId, parentSpanId } = propagationContext;\n\n const traceContext = dropUndefinedKeys({\n trace_id: traceId,\n span_id: spanId,\n parent_span_id: parentSpanId,\n });\n\n return traceContext;\n}\n\nexport { getClient, getCurrentScope, getGlobalScope, getIsolationScope, getTraceContextFromScope, withIsolationScope, withScope };\n//# sourceMappingURL=currentScopes.js.map\n","import { dropUndefinedKeys } from '../utils-hoist/object.js';\n\n/**\n * key: bucketKey\n * value: [exportKey, MetricSummary]\n */\n\nconst METRICS_SPAN_FIELD = '_sentryMetrics';\n\n/**\n * Fetches the metric summary if it exists for the passed span\n */\nfunction getMetricSummaryJsonForSpan(span) {\n const storage = (span )[METRICS_SPAN_FIELD];\n\n if (!storage) {\n return undefined;\n }\n const output = {};\n\n for (const [, [exportKey, summary]] of storage) {\n const arr = output[exportKey] || (output[exportKey] = []);\n arr.push(dropUndefinedKeys(summary));\n }\n\n return output;\n}\n\n/**\n * Updates the metric summary on a span.\n */\nfunction updateMetricSummaryOnSpan(\n span,\n metricType,\n sanitizedName,\n value,\n unit,\n tags,\n bucketKey,\n) {\n const existingStorage = (span )[METRICS_SPAN_FIELD];\n const storage =\n existingStorage ||\n ((span )[METRICS_SPAN_FIELD] = new Map());\n\n const exportKey = `${metricType}:${sanitizedName}@${unit}`;\n const bucketItem = storage.get(bucketKey);\n\n if (bucketItem) {\n const [, summary] = bucketItem;\n storage.set(bucketKey, [\n exportKey,\n {\n min: Math.min(summary.min, value),\n max: Math.max(summary.max, value),\n count: (summary.count += 1),\n sum: (summary.sum += value),\n tags: summary.tags,\n },\n ]);\n } else {\n storage.set(bucketKey, [\n exportKey,\n {\n min: value,\n max: value,\n count: 1,\n sum: value,\n tags,\n },\n ]);\n }\n}\n\nexport { getMetricSummaryJsonForSpan, updateMetricSummaryOnSpan };\n//# sourceMappingURL=metric-summary.js.map\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 */\nconst SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';\n\n/**\n * Use this attribute to represent the sample rate used for a span.\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';\n\n/**\n * Use this attribute to represent the operation of a span.\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';\n\n/**\n * Use this attribute to represent the origin of a span.\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';\n\n/** The reason why an idle span finished. */\nconst 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. */\nconst SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = 'sentry.measurement_unit';\n\n/** The value of a measurement, which may be stored as a TimedEvent. */\nconst 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 */\nconst SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = 'sentry.custom_span_name';\n\n/**\n * The id of the profile that this span occurred in.\n */\nconst SEMANTIC_ATTRIBUTE_PROFILE_ID = 'sentry.profile_id';\n\nconst SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = 'sentry.exclusive_time';\n\nconst SEMANTIC_ATTRIBUTE_CACHE_HIT = 'cache.hit';\n\nconst SEMANTIC_ATTRIBUTE_CACHE_KEY = 'cache.key';\n\nconst SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE = 'cache.item_size';\n\n/** TODO: Remove these once we update to latest semantic conventions */\nconst SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD = 'http.request.method';\nconst SEMANTIC_ATTRIBUTE_URL_FULL = 'url.full';\n\nexport { SEMANTIC_ATTRIBUTE_CACHE_HIT, SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, SEMANTIC_ATTRIBUTE_CACHE_KEY, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD, SEMANTIC_ATTRIBUTE_PROFILE_ID, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_URL_FULL };\n//# sourceMappingURL=semanticAttributes.js.map\n","const SPAN_STATUS_UNSET = 0;\nconst SPAN_STATUS_OK = 1;\nconst 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 unknown_error.\n */\n// https://develop.sentry.dev/sdk/event-payloads/span/\nfunction getSpanStatusFromHttpCode(httpStatus) {\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: 'unknown_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 */\nfunction setHttpStatus(span, httpStatus) {\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\nexport { SPAN_STATUS_ERROR, SPAN_STATUS_OK, SPAN_STATUS_UNSET, getSpanStatusFromHttpCode, setHttpStatus };\n//# sourceMappingURL=spanstatus.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { isString } from './is.js';\nimport { logger } from './logger.js';\n\n/**\n * @deprecated Use a `\"baggage\"` string directly\n */\nconst BAGGAGE_HEADER_NAME = 'baggage';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nconst 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 */\nconst 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 */\nfunction baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader,\n) {\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 ;\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 */\nfunction dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext,\n) {\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 */\nfunction parseBaggageHeader(\n baggageHeader,\n) {\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) {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\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 */\nfunction objectToBaggageHeader(object) {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n\nexport { BAGGAGE_HEADER_NAME, MAX_BAGGAGE_STRING_LENGTH, SENTRY_BAGGAGE_KEY_PREFIX, SENTRY_BAGGAGE_KEY_PREFIX_REGEX, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader, parseBaggageHeader };\n//# sourceMappingURL=baggage.js.map\n","import { baggageHeaderToDynamicSamplingContext } from './baggage.js';\nimport { generateTraceId, generateSpanId } from './propagationContext.js';\n\n// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- RegExp is used for readability here\nconst TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nfunction extractTraceparentData(traceparent) {\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;\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 */\nfunction propagationContextFromHeaders(\n sentryTrace,\n baggage,\n) {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n if (!traceparentData || !traceparentData.traceId) {\n return { traceId: generateTraceId(), spanId: generateSpanId() };\n }\n\n const { traceId, parentSpanId, parentSampled } = traceparentData;\n\n const virtualSpanId = generateSpanId();\n\n return {\n traceId,\n parentSpanId,\n spanId: virtualSpanId,\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n };\n}\n\n/**\n * Create sentry-trace header from span context values.\n */\nfunction generateSentryTraceHeader(\n traceId = generateTraceId(),\n spanId = generateSpanId(),\n sampled,\n) {\n let sampledString = '';\n if (sampled !== undefined) {\n sampledString = sampled ? '-1' : '-0';\n }\n return `${traceId}-${spanId}${sampledString}`;\n}\n\nexport { TRACEPARENT_REGEXP, extractTraceparentData, generateSentryTraceHeader, propagationContextFromHeaders };\n//# sourceMappingURL=tracing.js.map\n","import { getAsyncContextStrategy } from '../asyncContext/index.js';\nimport { getMainCarrier } from '../carrier.js';\nimport { getCurrentScope } from '../currentScopes.js';\nimport { getMetricSummaryJsonForSpan, updateMetricSummaryOnSpan } from '../metrics/metric-summary.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME } from '../semanticAttributes.js';\nimport { SPAN_STATUS_UNSET, SPAN_STATUS_OK } from '../tracing/spanstatus.js';\nimport { consoleSandbox } from '../utils-hoist/logger.js';\nimport { dropUndefinedKeys, addNonEnumerableProperty } from '../utils-hoist/object.js';\nimport { generateSpanId } from '../utils-hoist/propagationContext.js';\nimport { timestampInSeconds } from '../utils-hoist/time.js';\nimport { generateSentryTraceHeader } from '../utils-hoist/tracing.js';\nimport { _getSpanForScope } from './spanOnScope.js';\n\n// These are aligned with OpenTelemetry trace flags\nconst TRACE_FLAG_NONE = 0x0;\nconst TRACE_FLAG_SAMPLED = 0x1;\n\n// todo(v9): Remove this once we've stopped dropping spans via `beforeSendSpan`\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 */\nfunction spanToTransactionTraceContext(span) {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, origin } = spanToJSON(span);\n\n return dropUndefinedKeys({\n parent_span_id,\n span_id,\n trace_id,\n data,\n op,\n status,\n origin,\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 */\nfunction spanToTraceContext(span) {\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 span_id = isRemote ? generateSpanId() : spanId;\n\n return dropUndefinedKeys({\n parent_span_id,\n span_id,\n trace_id,\n });\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nfunction spanToTraceHeader(span) {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a span time input into a timestamp in seconds.\n */\nfunction spanTimeInputToSeconds(input) {\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) {\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.\nfunction spanToJSON(span) {\n if (spanIsSentrySpan(span)) {\n return span.getSpanJSON();\n }\n\n try {\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, parentSpanId, status } = span;\n\n return dropUndefinedKeys({\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] ,\n _metrics_summary: getMetricSummaryJsonForSpan(span),\n });\n }\n\n // Finally, at least we have `spanContext()`....\n return {\n span_id,\n trace_id,\n };\n } catch (e) {\n return {};\n }\n}\n\nfunction spanIsOpenTelemetrySdkTraceBaseSpan(span) {\n const castSpan = span ;\n return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status;\n}\n\n/** Exported only for tests. */\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) {\n return typeof (span ).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 */\nfunction spanIsSampled(span) {\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. */\nfunction getStatusMessage(status) {\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 || 'unknown_error';\n}\n\nconst CHILD_SPANS_FIELD = '_sentryChildSpans';\nconst ROOT_SPAN_FIELD = '_sentryRootSpan';\n\n/**\n * Adds an opaque child span reference to a span.\n */\nfunction addChildSpanToSpan(span, childSpan) {\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 , 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. */\nfunction removeChildSpanFromSpan(span, childSpan) {\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 */\nfunction getSpanDescendants(span) {\n const resultSet = new Set();\n\n function addSpanChildren(span) {\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 */\nfunction getRootSpan(span) {\n return span[ROOT_SPAN_FIELD] || span;\n}\n\n/**\n * Returns the currently active span.\n */\nfunction getActiveSpan() {\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 * Updates the metric summary on the currently active span\n */\nfunction updateMetricSummaryOnActiveSpan(\n metricType,\n sanitizedName,\n value,\n unit,\n tags,\n bucketKey,\n) {\n const span = getActiveSpan();\n if (span) {\n updateMetricSummaryOnSpan(span, metricType, sanitizedName, value, unit, tags, bucketKey);\n }\n}\n\n/**\n * Logs a warning once if `beforeSendSpan` is used to drop spans.\n *\n * todo(v9): Remove this once we've stopped dropping spans via `beforeSendSpan`.\n */\nfunction showSpanDropWarning() {\n if (!hasShownSpanDropWarning) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly.',\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 */\nfunction updateSpanName(span, name) {\n span.updateName(name);\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom',\n [SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]: name,\n });\n}\n\nexport { TRACE_FLAG_NONE, TRACE_FLAG_SAMPLED, addChildSpanToSpan, getActiveSpan, getRootSpan, getSpanDescendants, getStatusMessage, removeChildSpanFromSpan, showSpanDropWarning, spanIsSampled, spanTimeInputToSeconds, spanToJSON, spanToTraceContext, spanToTraceHeader, spanToTransactionTraceContext, updateMetricSummaryOnActiveSpan, updateSpanName };\n//# sourceMappingURL=spanUtils.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { addGlobalErrorInstrumentationHandler } from '../utils-hoist/instrument/globalError.js';\nimport { addGlobalUnhandledRejectionInstrumentationHandler } from '../utils-hoist/instrument/globalUnhandledRejection.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { getActiveSpan, getRootSpan } from '../utils/spanUtils.js';\nimport { SPAN_STATUS_ERROR } from './spanstatus.js';\n\nlet errorsInstrumented = false;\n\n/**\n * Ensure that global errors automatically set the active span status.\n */\nfunction registerSpanErrorInstrumentation() {\n if (errorsInstrumented) {\n return;\n }\n\n errorsInstrumented = true;\n addGlobalErrorInstrumentationHandler(errorCallback);\n addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active root span as failed\n */\nfunction errorCallback() {\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n if (rootSpan) {\n const message = 'internal_error';\n DEBUG_BUILD && logger.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\nerrorCallback.tag = 'sentry_tracingErrorCallback';\n\nexport { registerSpanErrorInstrumentation };\n//# sourceMappingURL=errors.js.map\n","import { addNonEnumerableProperty } from '../utils-hoist/object.js';\n\nconst SCOPE_ON_START_SPAN_FIELD = '_sentryScope';\nconst ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';\n\n/** Store the scope & isolation scope for a span, which can the be used when it is finished. */\nfunction setCapturedScopesOnSpan(span, scope, isolationScope) {\n if (span) {\n addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope);\n addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);\n }\n}\n\n/**\n * Grabs the scope and isolation scope off a span that were active when the span was started.\n */\nfunction getCapturedScopesOnSpan(span) {\n return {\n scope: (span )[SCOPE_ON_START_SPAN_FIELD],\n isolationScope: (span )[ISOLATION_SCOPE_ON_START_SPAN_FIELD],\n };\n}\n\nexport { getCapturedScopesOnSpan, setCapturedScopesOnSpan };\n//# sourceMappingURL=utils.js.map\n","import { getClient } from '../currentScopes.js';\n\n// Treeshakable guard to remove all code related to tracing\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nfunction hasTracingEnabled(\n maybeOptions,\n) {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const client = getClient();\n const options = maybeOptions || (client && client.getOptions());\n // eslint-disable-next-line deprecation/deprecation\n return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options);\n}\n\nexport { hasTracingEnabled };\n//# sourceMappingURL=hasTracingEnabled.js.map\n","import { generateTraceId, generateSpanId } from '../utils-hoist/propagationContext.js';\nimport { TRACE_FLAG_NONE } from '../utils/spanUtils.js';\n\n/**\n * A Sentry Span that is non-recording, meaning it will not be sent to Sentry.\n */\nclass SentryNonRecordingSpan {\n\n constructor(spanContext = {}) {\n this._traceId = spanContext.traceId || generateTraceId();\n this._spanId = spanContext.spanId || generateSpanId();\n }\n\n /** @inheritdoc */\n spanContext() {\n return {\n spanId: this._spanId,\n traceId: this._traceId,\n traceFlags: TRACE_FLAG_NONE,\n };\n }\n\n /** @inheritdoc */\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n end(_timestamp) {}\n\n /** @inheritdoc */\n setAttribute(_key, _value) {\n return this;\n }\n\n /** @inheritdoc */\n setAttributes(_values) {\n return this;\n }\n\n /** @inheritdoc */\n setStatus(_status) {\n return this;\n }\n\n /** @inheritdoc */\n updateName(_name) {\n return this;\n }\n\n /** @inheritdoc */\n isRecording() {\n return false;\n }\n\n /** @inheritdoc */\n addEvent(\n _name,\n _attributesOrStartTime,\n _startTime,\n ) {\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 addLink(_link) {\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 addLinks(_links) {\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 recordException(_exception, _time) {\n // noop\n }\n}\n\nexport { SentryNonRecordingSpan };\n//# sourceMappingURL=sentryNonRecordingSpan.js.map\n","const DEFAULT_ENVIRONMENT = 'production';\n\nexport { DEFAULT_ENVIRONMENT };\n//# sourceMappingURL=constants.js.map\n","import { DEFAULT_ENVIRONMENT } from '../constants.js';\nimport { getClient } from '../currentScopes.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes.js';\nimport { baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader } from '../utils-hoist/baggage.js';\nimport { dropUndefinedKeys, addNonEnumerableProperty } from '../utils-hoist/object.js';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled.js';\nimport { getRootSpan, spanToJSON, spanIsSampled } from '../utils/spanUtils.js';\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\n/**\n * Freeze the given DSC on the given span.\n */\nfunction freezeDscOnSpan(span, dsc) {\n const spanWithMaybeDsc = span ;\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 */\nfunction getDynamicSamplingContextFromClient(trace_id, client) {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n\n const dsc = dropUndefinedKeys({\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n public_key,\n trace_id,\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 */\nfunction getDynamicSamplingContextFromScope(client, scope) {\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 */\nfunction getDynamicSamplingContextFromSpan(span) {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n const rootSpan = getRootSpan(span);\n\n // For core implementation, we freeze the DSC onto the span as a non-enumerable property\n const frozenDsc = (rootSpan )[FROZEN_DSC_FIELD];\n if (frozenDsc) {\n return frozenDsc;\n }\n\n // For OpenTelemetry, we freeze the DSC on the trace state\n const traceState = rootSpan.spanContext().traceState;\n const traceStateDsc = traceState && 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 dscOnTraceState;\n }\n\n // Else, we generate it from the span\n const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);\n const jsonSpan = spanToJSON(rootSpan);\n const attributes = jsonSpan.data || {};\n const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];\n\n if (maybeSampleRate != null) {\n dsc.sample_rate = `${maybeSampleRate}`;\n }\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n const name = jsonSpan.description;\n if (source !== 'url' && name) {\n dsc.transaction = name;\n }\n\n // How can we even land here with hasTracingEnabled() 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 (hasTracingEnabled()) {\n dsc.sampled = String(spanIsSampled(rootSpan));\n }\n\n client.emit('createDsc', dsc, rootSpan);\n\n return dsc;\n}\n\n/**\n * Convert a Span to a baggage header.\n */\nfunction spanToBaggageHeader(span) {\n const dsc = getDynamicSamplingContextFromSpan(span);\n return dynamicSamplingContextToSentryBaggageHeader(dsc);\n}\n\nexport { freezeDscOnSpan, getDynamicSamplingContextFromClient, getDynamicSamplingContextFromScope, getDynamicSamplingContextFromSpan, spanToBaggageHeader };\n//# sourceMappingURL=dynamicSamplingContext.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { spanToJSON, spanIsSampled, getRootSpan } from '../utils/spanUtils.js';\n\n/**\n * Print a log message for a started span.\n */\nfunction logSpanStart(span) {\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 = [`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 logger.log(`${header}\n ${infoParts.join('\\n ')}`);\n}\n\n/**\n * Print a log message for an ended span.\n */\nfunction logSpanEnd(span) {\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 logger.log(msg);\n}\n\nexport { logSpanEnd, logSpanStart };\n//# sourceMappingURL=logSpans.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { logger } from '../utils-hoist/logger.js';\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 */\nfunction parseSampleRate(sampleRate) {\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 DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n sampleRate,\n )} of type ${JSON.stringify(typeof sampleRate)}.`,\n );\n return undefined;\n }\n\n return rate;\n}\n\nexport { parseSampleRate };\n//# sourceMappingURL=parseSampleRate.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled.js';\nimport { parseSampleRate } from '../utils/parseSampleRate.js';\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 */\nfunction sampleSpan(\n options,\n samplingContext,\n) {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n return [false];\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n } else {\n // When `enableTracing === true`, we use a sample rate of 100%\n sampleRate = 1;\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 && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');\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 logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n return [false, parsedSampleRate];\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n const shouldSample = Math.random() < parsedSampleRate;\n\n // if we're not going to keep it, we're done\n if (!shouldSample) {\n DEBUG_BUILD &&\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return [false, parsedSampleRate];\n }\n\n return [true, parsedSampleRate];\n}\n\nexport { sampleSpan };\n//# sourceMappingURL=sampling.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { consoleSandbox, logger } from './logger.js';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol) {\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 */\nfunction dsnToString(dsn, withPassword = false) {\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 */\nfunction dsnFromString(str) {\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() ;\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 , publicKey });\n}\n\nfunction dsnFromComponents(components) {\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) {\n if (!DEBUG_BUILD) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nfunction makeDsn(from) {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n\nexport { dsnFromString, dsnToString, makeDsn };\n//# sourceMappingURL=dsn.js.map\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Helper to decycle json objects\n *\n * @deprecated This function is deprecated and will be removed in the next major version.\n */\n// TODO(v9): Move this function into normalize() directly\nfunction memoBuilder() {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner = hasWeakSet ? new WeakSet() : [];\n function memoize(obj) {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj) {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n\nexport { memoBuilder };\n//# sourceMappingURL=memo.js.map\n","import { isVueViewModel, isSyntheticEvent } from './is.js';\nimport { memoBuilder } from './memo.js';\nimport { convertToPlainObject } from './object.js';\nimport { getFunctionName } from './stacktrace.js';\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\nfunction normalize(input, depth = 100, maxProperties = +Infinity) {\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 */\nfunction normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object,\n // Default Node.js REPL depth\n depth = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize = 100 * 1024,\n) {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized ;\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,\n value,\n depth = +Infinity,\n maxProperties = +Infinity,\n // eslint-disable-next-line deprecation/deprecation\n memo = memoBuilder(),\n) {\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 ;\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 )['__sentry_skip_normalization__']) {\n return value ;\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 )['__sentry_override_normalization_depth__'] === 'number'\n ? ((value )['__sentry_override_normalization_depth__'] )\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 ;\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) ;\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 );\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,\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,\n) {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value )._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n if (isVueViewModel(value)) {\n return '[VueViewModel]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && !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) {\n const prototype = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value) {\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) {\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 */\nfunction normalizeUrlToBase(url, basePath) {\n const escapedBase = basePath\n // Backslash to forward\n .replace(/\\\\/g, '/')\n // Escape RegExp special characters\n .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n let newUrl = url;\n try {\n newUrl = decodeURI(url);\n } catch (_Oo) {\n // Sometime this breaks\n }\n return (\n newUrl\n .replace(/\\\\/g, '/')\n .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor\n .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n );\n}\n\nexport { normalize, normalizeToSize, normalizeUrlToBase };\n//# sourceMappingURL=normalize.js.map\n","import { dsnToString } from './dsn.js';\nimport { normalize } from './normalize.js';\nimport { dropUndefinedKeys } from './object.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\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 */\nfunction createEnvelope(headers, items = []) {\n return [headers, items] ;\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 */\nfunction addItemToEnvelope(envelope, newItem) {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] ;\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 */\nfunction forEachEnvelopeItem(\n envelope,\n callback,\n) {\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 */\nfunction envelopeContainsItemType(envelope, types) {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8 array.\n */\nfunction encodeUTF8(input) {\n return GLOBAL_OBJ.__SENTRY__ && GLOBAL_OBJ.__SENTRY__.encodePolyfill\n ? GLOBAL_OBJ.__SENTRY__.encodePolyfill(input)\n : new TextEncoder().encode(input);\n}\n\n/**\n * Decode a UTF8 array to string.\n */\nfunction decodeUTF8(input) {\n return GLOBAL_OBJ.__SENTRY__ && GLOBAL_OBJ.__SENTRY__.decodePolyfill\n ? GLOBAL_OBJ.__SENTRY__.decodePolyfill(input)\n : new TextDecoder().decode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nfunction serializeEnvelope(envelope) {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts = JSON.stringify(envHeaders);\n\n function append(next) {\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;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\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) {\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 */\nfunction parseEnvelope(env) {\n let buffer = typeof env === 'string' ? encodeUTF8(env) : env;\n\n function readBinary(length) {\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() {\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))) ;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items = [];\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 */\nfunction createSpanEnvelopeItem(spanJson) {\n const spanHeaders = {\n type: 'span',\n };\n\n return [spanHeaders, spanJson];\n}\n\n/**\n * Creates attachment envelope items\n */\nfunction createAttachmentEnvelopeItem(attachment) {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP = {\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 statsd: 'metric_bucket',\n raw_security: 'security',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nfunction envelopeItemTypeToDataCategory(type) {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nfunction getSdkMetadataForEnvelopeHeader(metadataOrEvent) {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nfunction createEventEnvelopeHeaders(\n event,\n sdkInfo,\n tunnel,\n dsn,\n) {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id ,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n\nexport { addItemToEnvelope, createAttachmentEnvelopeItem, createEnvelope, createEventEnvelopeHeaders, createSpanEnvelopeItem, envelopeContainsItemType, envelopeItemTypeToDataCategory, forEachEnvelopeItem, getSdkMetadataForEnvelopeHeader, parseEnvelope, serializeEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { getDynamicSamplingContextFromSpan } from './tracing/dynamicSamplingContext.js';\nimport { dsnToString } from './utils-hoist/dsn.js';\nimport { getSdkMetadataForEnvelopeHeader, createEnvelope, createEventEnvelopeHeaders, createSpanEnvelopeItem } from './utils-hoist/envelope.js';\nimport './utils-hoist/version.js';\nimport './utils-hoist/debug-build.js';\nimport './utils-hoist/logger.js';\nimport { spanToJSON, showSpanDropWarning } from './utils/spanUtils.js';\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n **/\nfunction enhanceEventWithSdkInfo(event, sdkInfo) {\n if (!sdkInfo) {\n return event;\n }\n event.sdk = event.sdk || {};\n event.sdk.name = event.sdk.name || sdkInfo.name;\n event.sdk.version = event.sdk.version || sdkInfo.version;\n event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])];\n event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])];\n return event;\n}\n\n/** Creates an envelope from a Session */\nfunction createSessionEnvelope(\n session,\n dsn,\n metadata,\n tunnel,\n) {\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 =\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 */\nfunction createEventEnvelope(\n event,\n dsn,\n metadata,\n tunnel,\n) {\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 && 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 = [{ 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 */\nfunction createSpanEnvelope(spans, client) {\n function dscHasRequiredProps(dsc) {\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 && client.getDsn();\n const tunnel = client && client.getOptions().tunnel;\n\n const headers = {\n sent_at: new Date().toISOString(),\n ...(dscHasRequiredProps(dsc) && { trace: dsc }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const beforeSendSpan = client && client.getOptions().beforeSendSpan;\n const convertToSpanJSON = beforeSendSpan\n ? (span) => {\n const spanJson = beforeSendSpan(spanToJSON(span) );\n if (!spanJson) {\n showSpanDropWarning();\n }\n return spanJson;\n }\n : (span) => spanToJSON(span);\n\n const items = [];\n for (const span of spans) {\n const spanJson = convertToSpanJSON(span);\n if (spanJson) {\n items.push(createSpanEnvelopeItem(spanJson));\n }\n }\n\n return createEnvelope(headers, items);\n}\n\nexport { createEventEnvelope, createSessionEnvelope, createSpanEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT } from '../semanticAttributes.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { getRootSpan, getActiveSpan } from '../utils/spanUtils.js';\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 */\nfunction setMeasurement(name, value, unit, activeSpan = getActiveSpan()) {\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n\n if (rootSpan) {\n DEBUG_BUILD && logger.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 ,\n });\n }\n}\n\n/**\n * Convert timed events to measurements.\n */\nfunction timedEventsToMeasurements(events) {\n if (!events || events.length === 0) {\n return undefined;\n }\n\n const measurements = {};\n events.forEach(event => {\n const attributes = event.attributes || {};\n const unit = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT] ;\n const value = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE] ;\n\n if (typeof unit === 'string' && typeof value === 'number') {\n measurements[event.name] = { value, unit };\n }\n });\n\n return measurements;\n}\n\nexport { setMeasurement, timedEventsToMeasurements };\n//# sourceMappingURL=measurement.js.map\n","import { getClient, getCurrentScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { createSpanEnvelope } from '../envelope.js';\nimport { getMetricSummaryJsonForSpan } from '../metrics/metric-summary.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_PROFILE_ID, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME } from '../semanticAttributes.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { dropUndefinedKeys } from '../utils-hoist/object.js';\nimport { generateTraceId, generateSpanId } from '../utils-hoist/propagationContext.js';\nimport { timestampInSeconds } from '../utils-hoist/time.js';\nimport { TRACE_FLAG_SAMPLED, TRACE_FLAG_NONE, spanTimeInputToSeconds, getStatusMessage, getRootSpan, spanToJSON, getSpanDescendants, spanToTransactionTraceContext } from '../utils/spanUtils.js';\nimport { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext.js';\nimport { logSpanEnd } from './logSpans.js';\nimport { timedEventsToMeasurements } from './measurement.js';\nimport { getCapturedScopesOnSpan } from './utils.js';\n\nconst MAX_SPAN_COUNT = 1000;\n\n/**\n * Span contains all data about a span\n */\nclass SentrySpan {\n\n /** Epoch timestamp in seconds when the span started. */\n\n /** Epoch timestamp in seconds when the span ended. */\n\n /** Internal keeper of the status */\n\n /** The timed events added to this span. */\n\n /** if true, treat span as a standalone span (not part of a transaction) */\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 constructor(spanContext = {}) {\n this._traceId = spanContext.traceId || generateTraceId();\n this._spanId = spanContext.spanId || generateSpanId();\n this._startTime = spanContext.startTimestamp || timestampInSeconds();\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 /**\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 addLink(_link) {\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 addLinks(_links) {\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 recordException(_exception, _time) {\n // noop\n }\n\n /** @inheritdoc */\n spanContext() {\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 setAttribute(key, value) {\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 setAttributes(attributes) {\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 updateStartTime(timeInput) {\n this._startTime = spanTimeInputToSeconds(timeInput);\n }\n\n /**\n * @inheritDoc\n */\n setStatus(value) {\n this._status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n updateName(name) {\n this._name = name;\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'custom');\n return this;\n }\n\n /** @inheritdoc */\n end(endTimestamp) {\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 getSpanJSON() {\n return dropUndefinedKeys({\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] ,\n _metrics_summary: getMetricSummaryJsonForSpan(this),\n profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID] ,\n exclusive_time: this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME] ,\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 });\n }\n\n /** @inheritdoc */\n isRecording() {\n return !this._endTime && !!this._sampled;\n }\n\n /**\n * @inheritdoc\n */\n addEvent(\n name,\n attributesOrStartTime,\n startTime,\n ) {\n DEBUG_BUILD && logger.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 = {\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 isStandaloneSpan() {\n return !!this._isStandaloneSpan;\n }\n\n /** Emit `spanEnd` when the span is ended. */\n _onSpanEnded() {\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 logger.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 _convertSpanToTransaction() {\n // We can only convert finished spans\n if (!isFullFinishedSpan(spanToJSON(this))) {\n return undefined;\n }\n\n if (!this._name) {\n DEBUG_BUILD && logger.warn('Transaction has no name, falling back to ``.');\n this._name = '';\n }\n\n const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);\n const scope = capturedSpanScope || getCurrentScope();\n const client = scope.getClient() || getClient();\n\n if (this._sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n DEBUG_BUILD && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n if (client) {\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n return undefined;\n }\n\n // 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 span.data && delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];\n });\n // eslint-enabled-next-line @typescript-eslint/no-dynamic-delete\n\n const transaction = {\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 ...dropUndefinedKeys({\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),\n }),\n },\n _metrics_summary: getMetricSummaryJsonForSpan(this),\n ...(source && {\n transaction_info: {\n source,\n },\n }),\n };\n\n const measurements = timedEventsToMeasurements(this._events);\n const hasMeasurements = measurements && Object.keys(measurements).length;\n\n if (hasMeasurements) {\n DEBUG_BUILD &&\n logger.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) {\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) {\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) {\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) {\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\nexport { SentrySpan };\n//# sourceMappingURL=sentrySpan.js.map\n","import { getMainCarrier } from '../carrier.js';\nimport { withScope, getCurrentScope, getIsolationScope, getClient } from '../currentScopes.js';\nimport { getAsyncContextStrategy } from '../asyncContext/index.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE } from '../semanticAttributes.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { generateTraceId } from '../utils-hoist/propagationContext.js';\nimport { propagationContextFromHeaders } from '../utils-hoist/tracing.js';\nimport { handleCallbackErrors } from '../utils/handleCallbackErrors.js';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled.js';\nimport { _setSpanForScope, _getSpanForScope } from '../utils/spanOnScope.js';\nimport { spanToJSON, addChildSpanToSpan, spanIsSampled, spanTimeInputToSeconds, getRootSpan } from '../utils/spanUtils.js';\nimport { getDynamicSamplingContextFromSpan, freezeDscOnSpan } from './dynamicSamplingContext.js';\nimport { logSpanStart } from './logSpans.js';\nimport { sampleSpan } from './sampling.js';\nimport { SentryNonRecordingSpan } from './sentryNonRecordingSpan.js';\nimport { SentrySpan } from './sentrySpan.js';\nimport { SPAN_STATUS_ERROR } from './spanstatus.js';\nimport { setCapturedScopesOnSpan } from './utils.js';\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 */\nfunction startSpan(options, callback) {\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 } = options;\n\n return withScope(options.scope, () => {\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);\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 () => activeSpan.end(),\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. You'll have to call `span.end()` manually.\n *\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * 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 */\nfunction startSpanManual(options, callback) {\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 } = options;\n\n return withScope(options.scope, () => {\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);\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 function finishAndSetSpan() {\n activeSpan.end();\n }\n\n return handleCallbackErrors(\n () => callback(activeSpan, finishAndSetSpan),\n () => {\n // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n 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 */\nfunction startInactiveSpan(options) {\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) => withScope(options.scope, callback)\n : customParentSpan !== undefined\n ? (callback) => withActiveSpan(customParentSpan, callback)\n : (callback) => callback();\n\n return wrapper(() => {\n const scope = getCurrentScope();\n const parentSpan = getParentSpan(scope);\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 */\nconst continueTrace = (\n {\n sentryTrace,\n baggage,\n }\n\n,\n callback,\n) => {\n return withScope(scope => {\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n scope.setPropagationContext(propagationContext);\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 */\nfunction withActiveSpan(span, callback) {\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. */\nfunction suppressTracing(callback) {\n const acs = getAcs();\n\n if (acs.suppressTracing) {\n return acs.suppressTracing(callback);\n }\n\n return withScope(scope => {\n scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true });\n return callback();\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 */\nfunction startNewTrace(callback) {\n return withScope(scope => {\n scope.setPropagationContext({ traceId: generateTraceId() });\n DEBUG_BUILD && logger.info(`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\n) {\n if (!hasTracingEnabled()) {\n return new SentryNonRecordingSpan();\n }\n\n const isolationScope = getIsolationScope();\n\n let 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) {\n const exp = options.experimental || {};\n const initialCtx = {\n isStandalone: exp.standalone,\n ...options,\n };\n\n if (options.startTime) {\n const ctx = { ...initialCtx };\n ctx.startTimestamp = spanTimeInputToSeconds(options.startTime);\n delete ctx.startTime;\n return ctx;\n }\n\n return initialCtx;\n}\n\nfunction getAcs() {\n const carrier = getMainCarrier();\n return getAsyncContextStrategy(carrier);\n}\n\nfunction _startRootSpan(spanArguments, scope, parentSampled) {\n const client = getClient();\n const options = (client && client.getOptions()) || {};\n\n const { name = '', attributes } = spanArguments;\n const [sampled, sampleRate] = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY]\n ? [false]\n : sampleSpan(options, {\n name,\n parentSampled,\n attributes,\n transactionContext: {\n name,\n parentSampled,\n },\n });\n\n const rootSpan = new SentrySpan({\n ...spanArguments,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom',\n ...spanArguments.attributes,\n },\n sampled,\n });\n if (sampleRate !== undefined) {\n rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, sampleRate);\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, scope, spanArguments) {\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) {\n const span = _getSpanForScope(scope) ;\n\n if (!span) {\n return undefined;\n }\n\n const client = getClient();\n const options = client ? client.getOptions() : {};\n if (options.parentSpanIsAlwaysRootSpan) {\n return getRootSpan(span) ;\n }\n\n return span;\n}\n\nfunction getActiveSpanWrapper(parentSpan) {\n return parentSpan !== undefined\n ? (callback) => {\n return withActiveSpan(parentSpan, callback);\n }\n : (callback) => callback();\n}\n\nexport { continueTrace, startInactiveSpan, startNewTrace, startSpan, startSpanManual, suppressTracing, withActiveSpan };\n//# sourceMappingURL=trace.js.map\n","import { getClient, getCurrentScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON } from '../semanticAttributes.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { timestampInSeconds } from '../utils-hoist/time.js';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled.js';\nimport { _setSpanForScope } from '../utils/spanOnScope.js';\nimport { getActiveSpan, spanTimeInputToSeconds, getSpanDescendants, spanToJSON, removeChildSpanFromSpan } from '../utils/spanUtils.js';\nimport { SentryNonRecordingSpan } from './sentryNonRecordingSpan.js';\nimport { SPAN_STATUS_ERROR } from './spanstatus.js';\nimport { startInactiveSpan } from './trace.js';\n\nconst TRACING_DEFAULTS = {\n idleTimeout: 1000,\n finalTimeout: 30000,\n childSpanTimeout: 15000,\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';\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 */\nfunction startIdleSpan(startSpanOptions, options = {}) {\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;\n\n // The reason why the span was finished\n let _finishReason = FINISH_REASON_EXTERNAL_FINISH;\n\n let _autoFinishAllowed = !options.disableAutoFinish;\n\n const _cleanupHooks = [];\n\n const {\n idleTimeout = TRACING_DEFAULTS.idleTimeout,\n finalTimeout = TRACING_DEFAULTS.finalTimeout,\n childSpanTimeout = TRACING_DEFAULTS.childSpanTimeout,\n beforeSpanEnd,\n } = options;\n\n const client = getClient();\n\n if (!client || !hasTracingEnabled()) {\n return new SentryNonRecordingSpan();\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) {\n if (beforeSpanEnd) {\n beforeSpanEnd(span);\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 // If we have no spans, we just end, nothing else to do here\n if (!spans.length) {\n onIdleSpanEnded(spanEndTimestamp);\n return Reflect.apply(target, thisArg, [spanEndTimestamp, ...rest]);\n }\n\n const childEndTimestamps = spans\n .map(span => spanToJSON(span).timestamp)\n .filter(timestamp => !!timestamp) ;\n const latestSpanEndTimestamp = childEndTimestamps.length ? Math.max(...childEndTimestamps) : undefined;\n\n // In reality this should always exist here, but type-wise it may be undefined...\n const spanStartTimestamp = spanToJSON(span).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() {\n if (_idleTimeoutID) {\n clearTimeout(_idleTimeoutID);\n _idleTimeoutID = 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) {\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) {\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) {\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) {\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 }\n }\n\n function onIdleSpanEnded(endTimestamp) {\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 logger.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 logger.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 logger.log('[Tracing] Discarding span since it happened after idle span was finished', stringifiedSpan);\n } else if (!spanEndedBeforeFinalTimeout) {\n logger.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 (_finished || startedSpan === span || !!spanToJSON(startedSpan).timestamp) {\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) {\n const span = startInactiveSpan(options);\n\n _setSpanForScope(getCurrentScope(), span);\n\n DEBUG_BUILD && logger.log('[Tracing] Started span is an idle span');\n\n return span;\n}\n\nexport { TRACING_DEFAULTS, startIdleSpan };\n//# sourceMappingURL=idleSpan.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { isThenable } from './utils-hoist/is.js';\nimport { logger } from './utils-hoist/logger.js';\nimport { SyncPromise } from './utils-hoist/syncpromise.js';\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nfunction notifyEventProcessors(\n processors,\n event,\n hint,\n index = 0,\n) {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) ;\n\n DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n}\n\nexport { notifyEventProcessors };\n//# sourceMappingURL=eventProcessors.js.map\n","import { GLOBAL_OBJ } from './worldwide.js';\n\nlet parsedStackResults;\nlet lastKeysCount;\nlet cachedFilenameDebugIds;\n\n/**\n * Returns a map of filenames to debug identifiers.\n */\nfunction getFilenameToDebugIdMap(stackParser) {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n if (!debugIdMap) {\n return {};\n }\n\n const debugIdKeys = Object.keys(debugIdMap);\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 (cachedFilenameDebugIds && debugIdKeys.length === lastKeysCount) {\n return cachedFilenameDebugIds;\n }\n\n lastKeysCount = debugIdKeys.length;\n\n // Build a map of filename -> debug_id.\n cachedFilenameDebugIds = debugIdKeys.reduce((acc, stackKey) => {\n if (!parsedStackResults) {\n parsedStackResults = {};\n }\n\n const result = parsedStackResults[stackKey];\n\n if (result) {\n acc[result[0]] = result[1];\n } else {\n const parsedStack = stackParser(stackKey);\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n const filename = stackFrame && stackFrame.filename;\n const debugId = debugIdMap[stackKey];\n\n if (filename && debugId) {\n acc[filename] = debugId;\n parsedStackResults[stackKey] = [filename, debugId];\n break;\n }\n }\n }\n\n return acc;\n }, {});\n\n return cachedFilenameDebugIds;\n}\n\n/**\n * Returns a list of debug images for the given resources.\n */\nfunction getDebugImagesForResources(\n stackParser,\n resource_paths,\n) {\n const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);\n\n if (!filenameDebugIdMap) {\n return [];\n }\n\n const images = [];\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\nexport { getDebugImagesForResources, getFilenameToDebugIdMap };\n//# sourceMappingURL=debug-ids.js.map\n","import { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext.js';\nimport { dropUndefinedKeys } from '../utils-hoist/object.js';\nimport { merge } from './merge.js';\nimport { spanToTraceContext, getRootSpan, spanToJSON } from './spanUtils.js';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nfunction applyScopeDataToEvent(event, data) {\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. */\nfunction mergeScopeData(data, mergeData) {\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 */\nfunction mergeAndOverwriteScopeData\n\n(data, prop, mergeVal) {\n data[prop] = merge(data[prop], mergeVal, 1);\n}\n\nfunction applyDataToEvent(event, data) {\n const { extra, tags, user, contexts, level, transactionName } = data;\n\n const cleanedExtra = dropUndefinedKeys(extra);\n if (cleanedExtra && Object.keys(cleanedExtra).length) {\n event.extra = { ...cleanedExtra, ...event.extra };\n }\n\n const cleanedTags = dropUndefinedKeys(tags);\n if (cleanedTags && Object.keys(cleanedTags).length) {\n event.tags = { ...cleanedTags, ...event.tags };\n }\n\n const cleanedUser = dropUndefinedKeys(user);\n if (cleanedUser && Object.keys(cleanedUser).length) {\n event.user = { ...cleanedUser, ...event.user };\n }\n\n const cleanedContexts = dropUndefinedKeys(contexts);\n if (cleanedContexts && Object.keys(cleanedContexts).length) {\n event.contexts = { ...cleanedContexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n // 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, breadcrumbs) {\n const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event, sdkProcessingMetadata) {\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...sdkProcessingMetadata,\n };\n}\n\nfunction applySpanToEvent(event, span) {\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, fingerprint) {\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 && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n}\n\nexport { applyScopeDataToEvent, mergeAndOverwriteScopeData, mergeScopeData };\n//# sourceMappingURL=applyScopeDataToEvent.js.map\n","import { DEFAULT_ENVIRONMENT } from '../constants.js';\nimport { getGlobalScope } from '../currentScopes.js';\nimport { notifyEventProcessors } from '../eventProcessors.js';\nimport { Scope } from '../scope.js';\nimport { getFilenameToDebugIdMap } from '../utils-hoist/debug-ids.js';\nimport { uuid4, addExceptionMechanism } from '../utils-hoist/misc.js';\nimport { normalize } from '../utils-hoist/normalize.js';\nimport { truncate } from '../utils-hoist/string.js';\nimport { dateTimestampInSeconds } from '../utils-hoist/time.js';\nimport { mergeScopeData, applyScopeDataToEvent } from './applyScopeDataToEvent.js';\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 */\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 */\nfunction prepareEvent(\n options,\n event,\n hint,\n scope,\n client,\n isolationScope,\n) {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = options;\n const prepared = {\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 */\nfunction applyClientOptions(event, options) {\n const { environment, release, dist, maxValueLength = 250 } = 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 if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nfunction applyDebugIds(event, stackParser) {\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception.values.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace.frames.forEach(frame => {\n if (filenameDebugIdMap && frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nfunction applyDebugMeta(event) {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception.values.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace.frames.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.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, integrationNames) {\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, depth, maxBreadth) {\n if (!event) {\n return null;\n }\n\n const normalized = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n 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 && event.contexts.flags && normalized.contexts) {\n normalized.contexts.flags = normalize(event.contexts.flags, 3, maxBreadth);\n }\n\n return normalized;\n}\n\nfunction getFinalScope(\n scope,\n captureContext,\n) {\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 */\nfunction parseEventHintOrCaptureContext(\n hint,\n) {\n if (!hint) {\n return undefined;\n }\n\n // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext\n if (hintIsScopeOrFunction(hint)) {\n return { captureContext: hint };\n }\n\n if (hintIsScopeContext(hint)) {\n return {\n captureContext: hint,\n };\n }\n\n return hint;\n}\n\nfunction hintIsScopeOrFunction(\n hint,\n) {\n return hint instanceof Scope || typeof hint === 'function';\n}\n\nconst captureContextKeys = [\n 'user',\n 'level',\n 'extra',\n 'contexts',\n 'tags',\n 'fingerprint',\n 'requestSession',\n 'propagationContext',\n] ;\n\nfunction hintIsScopeContext(hint) {\n return Object.keys(hint).some(key => captureContextKeys.includes(key ));\n}\n\nexport { applyClientOptions, applyDebugIds, applyDebugMeta, parseEventHintOrCaptureContext, prepareEvent };\n//# sourceMappingURL=prepareEvent.js.map\n","import { DEFAULT_ENVIRONMENT } from './constants.js';\nimport { getCurrentScope, getIsolationScope, getClient, withIsolationScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { makeSession, updateSession, closeSession } from './session.js';\nimport { isThenable } from './utils-hoist/is.js';\nimport { logger } from './utils-hoist/logger.js';\nimport { uuid4 } from './utils-hoist/misc.js';\nimport { timestampInSeconds } from './utils-hoist/time.js';\nimport { GLOBAL_OBJ } from './utils-hoist/worldwide.js';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent.js';\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 */\nfunction captureException(exception, hint) {\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 */\nfunction captureMessage(message, captureContext) {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n return getCurrentScope().captureMessage(message, level, context);\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 */\nfunction captureEvent(event, hint) {\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 */\nfunction setContext(name, context) {\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 */\nfunction setExtras(extras) {\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 */\nfunction setExtra(key, extra) {\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 */\nfunction setTags(tags) {\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 */\nfunction setTag(key, value) {\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 */\nfunction setUser(user) {\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 */\nfunction lastEventId() {\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 */\nfunction captureCheckIn(checkIn, upsertMonitorConfig) {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nfunction withMonitor(\n monitorSlug,\n callback,\n upsertMonitorConfig,\n) {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status) {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n\n return withIsolationScope(() => {\n let maybePromiseResult;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishCheckIn('ok');\n },\n e => {\n finishCheckIn('error');\n throw e;\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\n });\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 */\nasync function flush(timeout) {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nasync function close(timeout) {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nfunction isInitialized() {\n return !!getClient();\n}\n\n/** If the SDK is initialized & enabled. */\nfunction isEnabled() {\n const client = getClient();\n return !!client && 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 */\nfunction addEventProcessor(callback) {\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 */\nfunction startSession(context) {\n const client = getClient();\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nfunction endSession() {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate() {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n const client = getClient();\n // TODO (v8): Remove currentScope and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session && client) {\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 */\nfunction captureSession(end = false) {\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\nexport { addEventProcessor, captureCheckIn, captureEvent, captureException, captureMessage, captureSession, close, endSession, flush, isEnabled, isInitialized, lastEventId, setContext, setExtra, setExtras, setTag, setTags, setUser, startSession, withMonitor };\n//# sourceMappingURL=exports.js.map\n","import { makeDsn, dsnToString } from './utils-hoist/dsn.js';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn) {\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) {\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, sdkInfo) {\n const params = {\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 */\nfunction getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkInfo) {\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nfunction getReportDialogEndpoint(\n dsnLike,\n dialogOptions\n\n,\n) {\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] )}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n\nexport { getEnvelopeEndpointWithUrlEncodedAuth, getReportDialogEndpoint };\n//# sourceMappingURL=api.js.map\n","import { getClient } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { logger } from './utils-hoist/logger.js';\n\nconst installedIntegrations = [];\n\n/** Map of integrations assigned to a client */\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) {\n const integrationsByName = {};\n\n integrations.forEach((currentInstance) => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.values(integrationsByName);\n}\n\n/** Gets integrations to install */\nfunction getIntegrationsToSetup(options) {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach((integration) => {\n integration.isDefaultInstance = true;\n });\n\n let integrations;\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 const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = finalIntegrations.findIndex(integration => integration.name === 'Debug');\n if (debugIndex > -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1) ;\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nfunction setupIntegrations(client, integrations) {\n const integrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(client, integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/**\n * Execute the `afterAllSetup` hooks of the given integrations.\n */\nfunction afterSetupIntegrations(client, integrations) {\n for (const integration of integrations) {\n // guard against empty provided integrations\n if (integration && integration.afterAllSetup) {\n integration.afterAllSetup(client);\n }\n }\n}\n\n/** Setup a single integration. */\nfunction setupIntegration(client, integration, integrationIndex) {\n if (integrationIndex[integration.name]) {\n DEBUG_BUILD && logger.log(`Integration skipped because it was already installed: ${integration.name}`);\n return;\n }\n integrationIndex[integration.name] = integration;\n\n // `setupOnce` is only called the first time\n if (installedIntegrations.indexOf(integration.name) === -1 && 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) ;\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) ;\n\n const processor = Object.assign((event, hint) => callback(event, hint, client), {\n id: integration.name,\n });\n\n client.addEventProcessor(processor);\n }\n\n DEBUG_BUILD && logger.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current scope's client. */\nfunction addIntegration(integration) {\n const client = getClient();\n\n if (!client) {\n DEBUG_BUILD && logger.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\n}\n\n/**\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 */\nfunction defineIntegration(fn) {\n return fn;\n}\n\nexport { addIntegration, afterSetupIntegrations, defineIntegration, getIntegrationsToSetup, installedIntegrations, setupIntegration, setupIntegrations };\n//# sourceMappingURL=integration.js.map\n","import { createEnvelope } from './envelope.js';\nimport { dateTimestampInSeconds } from './time.js';\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 */\nfunction createClientReportEnvelope(\n discarded_events,\n dsn,\n timestamp,\n) {\n const clientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n\nexport { createClientReportEnvelope };\n//# sourceMappingURL=clientreport.js.map\n","/** An error emitted by Sentry SDKs and related utilities. */\nclass SentryError extends Error {\n /** Display name of this error instance. */\n\n constructor(\n message,\n logLevel = 'warn',\n ) {\n super(message);this.message = message;\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n\nexport { SentryError };\n//# sourceMappingURL=error.js.map\n","import { getEnvelopeEndpointWithUrlEncodedAuth } from './api.js';\nimport { getTraceContextFromScope, getCurrentScope, getIsolationScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope.js';\nimport { setupIntegration, afterSetupIntegrations, setupIntegrations } from './integration.js';\nimport { updateSession } from './session.js';\nimport { getDynamicSamplingContextFromScope } from './tracing/dynamicSamplingContext.js';\nimport { createClientReportEnvelope } from './utils-hoist/clientreport.js';\nimport { makeDsn, dsnToString } from './utils-hoist/dsn.js';\nimport { addItemToEnvelope, createAttachmentEnvelopeItem } from './utils-hoist/envelope.js';\nimport { SentryError } from './utils-hoist/error.js';\nimport { isPrimitive, isThenable, isPlainObject, isParameterizedString } from './utils-hoist/is.js';\nimport { logger, consoleSandbox } from './utils-hoist/logger.js';\nimport { uuid4, checkOrSetAlreadyCaught } from './utils-hoist/misc.js';\nimport { resolvedSyncPromise, SyncPromise, rejectedSyncPromise } from './utils-hoist/syncpromise.js';\nimport { parseSampleRate } from './utils/parseSampleRate.js';\nimport { prepareEvent } from './utils/prepareEvent.js';\nimport { showSpanDropWarning } from './utils/spanUtils.js';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nclass BaseClient {\n /** Options passed to the SDK. */\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n\n /** Array of set up integrations. */\n\n /** Number of calls being processed */\n\n /** Holds flushable */\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n constructor(options) {\n this._options = options;\n this._integrations = {};\n this._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n this._eventProcessors = [];\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n DEBUG_BUILD && logger.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(\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 // TODO(v9): Remove this deprecation warning\n const tracingOptions = ['enableTracing', 'tracesSampleRate', 'tracesSampler'] ;\n const undefinedOption = tracingOptions.find(option => option in options && options[option] == undefined);\n if (undefinedOption) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n `[Sentry] Deprecation warning: \\`${undefinedOption}\\` is set to undefined, which leads to tracing being enabled. In v9, a value of \\`undefined\\` will result in tracing being disabled.`,\n );\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n captureException(exception, hint, scope) {\n const eventId = uuid4();\n\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return eventId;\n }\n\n const hintWithEventId = {\n event_id: eventId,\n ...hint,\n };\n\n this._process(\n this.eventFromException(exception, hintWithEventId).then(event =>\n this._captureEvent(event, hintWithEventId, scope),\n ),\n );\n\n return hintWithEventId.event_id;\n }\n\n /**\n * @inheritDoc\n */\n captureMessage(\n message,\n level,\n hint,\n currentScope,\n ) {\n const hintWithEventId = {\n event_id: uuid4(),\n ...hint,\n };\n\n const eventMessage = isParameterizedString(message) ? message : String(message);\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(eventMessage, level, hintWithEventId)\n : this.eventFromException(message, hintWithEventId);\n\n this._process(promisedEvent.then(event => this._captureEvent(event, hintWithEventId, currentScope)));\n\n return hintWithEventId.event_id;\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint, currentScope) {\n const eventId = uuid4();\n\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return eventId;\n }\n\n const hintWithEventId = {\n event_id: eventId,\n ...hint,\n };\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope;\n\n this._process(this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope));\n\n return hintWithEventId.event_id;\n }\n\n /**\n * @inheritDoc\n */\n captureSession(session) {\n if (!(typeof session.release === 'string')) {\n DEBUG_BUILD && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n getDsn() {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n getOptions() {\n return this._options;\n }\n\n /**\n * @see SdkMetadata\n *\n * @return The metadata of the SDK\n */\n getSdkMetadata() {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n getTransport() {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n flush(timeout) {\n const transport = this._transport;\n if (transport) {\n this.emit('flush');\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n close(timeout) {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n this.emit('close');\n return result;\n });\n }\n\n /** Get all installed event processors. */\n getEventProcessors() {\n return this._eventProcessors;\n }\n\n /** @inheritDoc */\n addEventProcessor(eventProcessor) {\n this._eventProcessors.push(eventProcessor);\n }\n\n /** @inheritdoc */\n init() {\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 The installed integration or `undefined` if no integration with that `name` was installed.\n */\n getIntegrationByName(integrationName) {\n return this._integrations[integrationName] ;\n }\n\n /**\n * @inheritDoc\n */\n addIntegration(integration) {\n const isAlreadyInstalled = this._integrations[integration.name];\n\n // This hook takes care of only installing if not already installed\n setupIntegration(this, integration, this._integrations);\n // Here we need to check manually to make sure to not run this multiple times\n if (!isAlreadyInstalled) {\n afterSetupIntegrations(this, [integration]);\n }\n }\n\n /**\n * @inheritDoc\n */\n sendEvent(event, hint = {}) {\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 const promise = this.sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n\n /**\n * @inheritDoc\n */\n sendSession(session) {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(env);\n }\n\n /**\n * @inheritDoc\n */\n recordDroppedEvent(reason, category, eventOrCount) {\n if (this._options.sendClientReports) {\n // TODO v9: We do not need the `event` passed as third argument anymore, and can possibly remove this overload\n // If event is passed as third argument, we assume this is a count of 1\n const count = typeof eventOrCount === 'number' ? eventOrCount : 1;\n\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n DEBUG_BUILD && logger.log(`Recording outcome: \"${key}\"${count > 1 ? ` (${count} times)` : ''}`);\n this._outcomes[key] = (this._outcomes[key] || 0) + count;\n }\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n /* eslint-disable @typescript-eslint/unified-signatures */\n\n /** @inheritdoc */\n\n /** @inheritdoc */\n on(hook, callback) {\n const hooks = (this._hooks[hook] = this._hooks[hook] || []);\n\n // @ts-expect-error We assume the types are correct\n hooks.push(callback);\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 // @ts-expect-error We assume the types are correct\n const cbIndex = hooks.indexOf(callback);\n if (cbIndex > -1) {\n hooks.splice(cbIndex, 1);\n }\n };\n }\n\n /** @inheritdoc */\n\n /** @inheritdoc */\n emit(hook, ...rest) {\n const callbacks = this._hooks[hook];\n if (callbacks) {\n callbacks.forEach(callback => callback(...rest));\n }\n }\n\n /**\n * @inheritdoc\n */\n sendEnvelope(envelope) {\n this.emit('beforeEnvelope', envelope);\n\n if (this._isEnabled() && this._transport) {\n return this._transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending envelope:', reason);\n return reason;\n });\n }\n\n DEBUG_BUILD && logger.error('Transport disabled');\n\n return resolvedSyncPromise({});\n }\n\n /* eslint-enable @typescript-eslint/unified-signatures */\n\n /** Setup integrations for this client. */\n _setupIntegrations() {\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 _updateSessionFromEvent(session, event) {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n _isClientDoneProcessing(timeout) {\n return new SyncPromise(resolve => {\n let ticked = 0;\n const tick = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a transport is present. */\n _isEnabled() {\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 _prepareEvent(\n event,\n hint,\n currentScope = getCurrentScope(),\n isolationScope = getIsolationScope(),\n ) {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n 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 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 _captureEvent(event, hint = {}, scope) {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (DEBUG_BUILD) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason ;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param 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 _processEvent(event, hint, currentScope) {\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', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope;\n\n return this._prepareEvent(event, hint, currentScope, capturedSpanIsolationScope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data ).__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, event);\n if (isTransaction) {\n const spans = event.spans || [];\n // the transaction itself counts as one span, plus all the child spans that are added\n const spanCount = 1 + spans.length;\n this.recordDroppedEvent('before_send', 'span', spanCount);\n }\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = currentScope && currentScope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n if (isTransaction) {\n const spanCountBefore =\n (processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing) ||\n 0;\n const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;\n\n const droppedSpanCount = spanCountBefore - spanCountAfter;\n if (droppedSpanCount > 0) {\n this.recordDroppedEvent('before_send', 'span', droppedSpanCount);\n }\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n _process(promise) {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n _clearOutcomes() {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.entries(outcomes).map(([key, quantity]) => {\n const [reason, category] = key.split(':') ;\n return {\n reason,\n category,\n quantity,\n };\n });\n }\n\n /**\n * Sends client reports as an envelope.\n */\n _flushOutcomes() {\n DEBUG_BUILD && logger.log('Flushing outcomes...');\n\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n DEBUG_BUILD && logger.log('No outcomes to send');\n return;\n }\n\n // This is really the only place where we want to check for a DSN and only send outcomes then\n if (!this._dsn) {\n DEBUG_BUILD && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n DEBUG_BUILD && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n\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,\n beforeSendLabel,\n) {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n client,\n options,\n event,\n hint,\n) {\n const { beforeSend, beforeSendTransaction, beforeSendSpan } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event)) {\n if (event.spans && beforeSendSpan) {\n const processedSpans = [];\n for (const span of event.spans) {\n const processedSpan = beforeSendSpan(span);\n if (processedSpan) {\n processedSpans.push(processedSpan);\n } else {\n showSpanDropWarning();\n client.recordDroppedEvent('before_send', 'span');\n }\n }\n event.spans = processedSpans;\n }\n\n if (beforeSendTransaction) {\n if (event.spans) {\n // We store the # of spans before processing in SDK metadata,\n // so we can compare it afterwards to determine how many spans were dropped\n const spanCountBefore = event.spans.length;\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n spanCountBeforeProcessing: spanCountBefore,\n };\n }\n return beforeSendTransaction(event, hint);\n }\n }\n\n return event;\n}\n\nfunction isErrorEvent(event) {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\nexport { BaseClient };\n//# sourceMappingURL=baseclient.js.map\n","import { getCurrentScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { logger, consoleSandbox } from './utils-hoist/logger.js';\n\n/** A class object that can instantiate Client objects. */\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 */\nfunction initAndBind(\n clientClass,\n options,\n) {\n if (options.debug === true) {\n if (DEBUG_BUILD) {\n logger.enable();\n } else {\n // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n });\n }\n }\n const scope = getCurrentScope();\n scope.update(options.initialScope);\n\n const client = new clientClass(options);\n setCurrentClient(client);\n client.init();\n return client;\n}\n\n/**\n * Make the given client the current client.\n */\nfunction setCurrentClient(client) {\n getCurrentScope().setClient(client);\n}\n\nexport { initAndBind, setCurrentClient };\n//# sourceMappingURL=sdk.js.map\n","import { SentryError } from './error.js';\nimport { rejectedSyncPromise, SyncPromise, resolvedSyncPromise } from './syncpromise.js';\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 */\nfunction makePromiseBuffer(limit) {\n const buffer = [];\n\n function isReady() {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task) {\n return buffer.splice(buffer.indexOf(task), 1)[0] || Promise.resolve(undefined);\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) {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout) {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n\nexport { makePromiseBuffer };\n//# sourceMappingURL=promisebuffer.js.map\n","// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\n\nconst 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 */\nfunction parseRetryAfterHeader(header, now = Date.now()) {\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 */\nfunction disabledUntil(limits, dataCategory) {\n return limits[dataCategory] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nfunction isRateLimited(limits, dataCategory, now = Date.now()) {\n return disabledUntil(limits, dataCategory) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nfunction updateRateLimits(\n limits,\n { statusCode, headers },\n now = Date.now(),\n) {\n const updatedRateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n * Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.\n * Only present if rate limit applies to the metric_bucket data category.\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories, , , namespaces] = limit.split(':', 5) ;\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n if (category === 'metric_bucket') {\n // namespaces will be present when category === 'metric_bucket'\n if (!namespaces || namespaces.split(';').includes('custom')) {\n updatedRateLimits[category] = now + delay;\n }\n } else {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n\nexport { DEFAULT_RETRY_AFTER, disabledUntil, isRateLimited, parseRetryAfterHeader, updateRateLimits };\n//# sourceMappingURL=ratelimit.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { forEachEnvelopeItem, envelopeItemTypeToDataCategory, createEnvelope, serializeEnvelope } from '../utils-hoist/envelope.js';\nimport { SentryError } from '../utils-hoist/error.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { makePromiseBuffer } from '../utils-hoist/promisebuffer.js';\nimport { isRateLimited, updateRateLimits } from '../utils-hoist/ratelimit.js';\nimport { resolvedSyncPromise } from '../utils-hoist/syncpromise.js';\n\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 64;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nfunction createTransport(\n options,\n makeRequest,\n buffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n) {\n let rateLimits = {};\n const flush = (timeout) => buffer.drain(timeout);\n\n function send(envelope) {\n const filteredEnvelopeItems = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const dataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, dataCategory)) {\n const event = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', dataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise({});\n }\n\n const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems );\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason) => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = () =>\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 && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise({});\n } else {\n throw error;\n }\n },\n );\n }\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item, type) {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item )[1] : undefined;\n}\n\nexport { DEFAULT_TRANSPORT_BUFFER_SIZE, createTransport };\n//# sourceMappingURL=base.js.map\n","/**\n * Checks whether given url points to Sentry server\n *\n * @param url url to verify\n */\nfunction isSentryRequestUrl(url, client) {\n const dsn = client && client.getDsn();\n const tunnel = client && client.getOptions().tunnel;\n return checkDsn(url, dsn) || checkTunnel(url, tunnel);\n}\n\nfunction checkTunnel(url, tunnel) {\n if (!tunnel) {\n return false;\n }\n\n return removeTrailingSlash(url) === removeTrailingSlash(tunnel);\n}\n\nfunction checkDsn(url, dsn) {\n return dsn ? url.includes(dsn.host) : false;\n}\n\nfunction removeTrailingSlash(str) {\n return str[str.length - 1] === '/' ? str.slice(0, -1) : str;\n}\n\nexport { isSentryRequestUrl };\n//# sourceMappingURL=isSentryRequestUrl.js.map\n","import { SDK_VERSION } from '../utils-hoist/version.js';\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 */\nfunction applySdkMetadata(options, name, names = [name], source = 'npm') {\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\nexport { applySdkMetadata };\n//# sourceMappingURL=sdkMetadata.js.map\n","import { getAsyncContextStrategy } from '../asyncContext/index.js';\nimport { getMainCarrier } from '../carrier.js';\nimport { getClient, getCurrentScope } from '../currentScopes.js';\nimport { isEnabled } from '../exports.js';\nimport '../tracing/errors.js';\nimport '../utils-hoist/version.js';\nimport '../utils-hoist/debug-build.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport '../debug-build.js';\nimport '../utils-hoist/time.js';\nimport { getActiveSpan, spanToTraceHeader } from './spanUtils.js';\nimport { TRACEPARENT_REGEXP, generateSentryTraceHeader } from '../utils-hoist/tracing.js';\nimport { getDynamicSamplingContextFromSpan, getDynamicSamplingContextFromScope } from '../tracing/dynamicSamplingContext.js';\nimport { dynamicSamplingContextToSentryBaggageHeader } from '../utils-hoist/baggage.js';\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 to strings. 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 * @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 */\nfunction getTraceData(options = {}) {\n const 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 = 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 logger.warn('Invalid sentry-trace data. Cannot generate trace data');\n return {};\n }\n\n return {\n 'sentry-trace': sentryTrace,\n baggage,\n };\n}\n\n/**\n * Get a sentry-trace header value for the given scope.\n */\nfunction scopeToTraceHeader(scope) {\n // TODO(v9): Use generateSpanId() instead of spanId\n // eslint-disable-next-line deprecation/deprecation\n const { traceId, sampled, spanId } = scope.getPropagationContext();\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\nexport { getTraceData };\n//# sourceMappingURL=traceData.js.map\n","import { getClient, getIsolationScope } from './currentScopes.js';\nimport { consoleSandbox } from './utils-hoist/logger.js';\nimport { dateTimestampInSeconds } from './utils-hoist/time.js';\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 */\nfunction addBreadcrumb(breadcrumb, hint) {\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\nexport { addBreadcrumb };\n//# sourceMappingURL=breadcrumbs.js.map\n","import { getClient } from '../currentScopes.js';\nimport { defineIntegration } from '../integration.js';\nimport { getOriginalFunction } from '../utils-hoist/object.js';\n\nlet originalFunctionToString;\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 ( ...args) {\n const originalFunction = getOriginalFunction(this);\n const context =\n SETUP_CLIENTS.has(getClient() ) && originalFunction !== undefined ? originalFunction : this;\n return originalFunctionToString.apply(context, args);\n };\n } catch (e) {\n // ignore errors here, just don't patch this\n }\n },\n setup(client) {\n SETUP_CLIENTS.set(client, true);\n },\n };\n}) ;\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 */\nconst functionToStringIntegration = defineIntegration(_functionToStringIntegration);\n\nexport { functionToStringIntegration };\n//# sourceMappingURL=functiontostring.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { defineIntegration } from '../integration.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { getEventDescription } from '../utils-hoist/misc.js';\nimport { stringMatchesSomePattern } from '../utils-hoist/string.js';\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 \"undefined is not an object (evaluating 'a.L')\", // 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];\n\n/** Options for the InboundFilters integration */\n\nconst INTEGRATION_NAME = 'InboundFilters';\nconst _inboundFiltersIntegration = ((options = {}) => {\n return {\n name: INTEGRATION_NAME,\n processEvent(event, _hint, client) {\n const clientOptions = client.getOptions();\n const mergedOptions = _mergeOptions(options, clientOptions);\n return _shouldDropEvent(event, mergedOptions) ? null : event;\n },\n };\n}) ;\n\nconst inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration);\n\nfunction _mergeOptions(\n internalOptions = {},\n clientOptions = {},\n) {\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 ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\nfunction _shouldDropEvent(event, options) {\n if (options.ignoreInternal && _isSentryError(event)) {\n DEBUG_BUILD &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isUselessError(event)) {\n DEBUG_BUILD &&\n logger.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 (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event, ignoreErrors) {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event, ignoreTransactions) {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event, denyUrls) {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event, allowUrls) {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event) {\n const possibleMessages = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n let lastException;\n try {\n // @ts-expect-error Try catching to save bundle size\n lastException = event.exception.values[event.exception.values.length - 1];\n } catch (e) {\n // try catching to save bundle size checking existence of variables\n }\n\n if (lastException) {\n if (lastException.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n }\n\n return possibleMessages;\n}\n\nfunction _isSentryError(event) {\n try {\n // @ts-expect-error can't be a sentry error if undefined\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames = []) {\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) {\n try {\n let frames;\n try {\n // @ts-expect-error we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n DEBUG_BUILD && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n\nfunction _isUselessError(event) {\n if (event.type) {\n // event is not an error\n return false;\n }\n\n // We only want to consider events for dropping that actually have recorded exception values.\n if (!event.exception || !event.exception.values || event.exception.values.length === 0) {\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\nexport { inboundFiltersIntegration };\n//# sourceMappingURL=inboundfilters.js.map\n","import { isInstanceOf } from './is.js';\nimport { truncate } from './string.js';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nfunction applyAggregateErrorsToEvent(\n exceptionFromErrorImplementation,\n parser,\n maxValueLimit = 250,\n key,\n limit,\n event,\n hint,\n) {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return;\n }\n\n // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n const originalException =\n event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n // We only create exception grouping if there is an exception in the event.\n if (originalException) {\n event.exception.values = truncateAggregateExceptions(\n aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException ,\n key,\n event.exception.values,\n originalException,\n 0,\n ),\n maxValueLimit,\n );\n }\n}\n\nfunction aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error,\n key,\n prevExceptions,\n exception,\n exceptionId,\n) {\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, exceptionId) {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n ...(exception.type === 'AggregateError' && { is_exception_group: true }),\n exception_id: exceptionId,\n };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n exception,\n source,\n exceptionId,\n parentId,\n) {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n\n/**\n * Truncate the message (exception.value) of all exceptions in the event.\n * Because this event processor is ran after `applyClientOptions`,\n * we need to truncate the message of the added exceptions here.\n */\nfunction truncateAggregateExceptions(exceptions, maxValueLength) {\n return exceptions.map(exception => {\n if (exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n return exception;\n });\n}\n\nexport { applyAggregateErrorsToEvent };\n//# sourceMappingURL=aggregate-errors.js.map\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 */\nfunction parseUrl(url) {\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 */\nfunction stripUrlQueryAndFragment(urlPath) {\n return (urlPath.split(/[?#]/, 1) )[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n *\n * @deprecated This function will be removed in the next major version.\n */\n// TODO(v9): Hoist this function into the places where we use it. (as it stands only react router v6 instrumentation)\nfunction getNumberOfUrlSegments(url) {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span name\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nfunction getSanitizedUrlString(url) {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n // TODO: Use new URL global if it exists\n .replace(/(:80)$/, '')\n .replace(/(:443)$/, '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n\nexport { getNumberOfUrlSegments, getSanitizedUrlString, parseUrl, stripUrlQueryAndFragment };\n//# sourceMappingURL=url.js.map\n","import { CONSOLE_LEVELS, originalConsoleMethods } from '../logger.js';\nimport { fill } from '../object.js';\nimport { GLOBAL_OBJ } from '../worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\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 */\nfunction addConsoleInstrumentationHandler(handler) {\n const type = 'console';\n addHandler(type, handler);\n maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole() {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level) {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod) {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args) {\n const handlerData = { args, level };\n triggerHandlers('console', handlerData);\n\n const log = originalConsoleMethods[level];\n log && log.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n\nexport { addConsoleInstrumentationHandler };\n//# sourceMappingURL=console.js.map\n","/**\n * @deprecated This variable has been deprecated and will be removed in the next major version.\n */\nconst validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\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 */\nfunction severityLevelFromString(level) {\n return (\n level === 'warn' ? 'warning' : ['fatal', 'error', 'warning', 'log', 'info', 'debug'].includes(level) ? level : 'log'\n ) ;\n}\n\nexport { severityLevelFromString, validSeverityLevels };\n//# sourceMappingURL=severity.js.map\n","import { defineIntegration } from '../integration.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { getFramesFromEvent } from '../utils-hoist/stacktrace.js';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() => {\n let previousEvent;\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 && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n return (previousEvent = currentEvent);\n },\n };\n}) ;\n\n/**\n * Deduplication filter.\n */\nconst dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/** only exported for tests. */\nfunction _shouldDropEvent(currentEvent, previousEvent) {\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, previousEvent) {\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, previousEvent) {\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, previousEvent) {\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 ;\n previousFrames = previousFrames ;\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, previousEvent) {\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 ;\n previousFingerprint = previousFingerprint ;\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\nfunction _getExceptionFromEvent(event) {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\nexport { _shouldDropEvent, dedupeIntegration };\n//# sourceMappingURL=dedupe.js.map\n","import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP } from './semanticAttributes.js';\nimport './tracing/errors.js';\nimport { isInstanceOf } from './utils-hoist/is.js';\nimport './utils-hoist/version.js';\nimport './utils-hoist/debug-build.js';\nimport './utils-hoist/logger.js';\nimport './utils-hoist/time.js';\nimport './utils-hoist/syncpromise.js';\nimport { parseUrl } from './utils-hoist/url.js';\nimport { SENTRY_BAGGAGE_KEY_PREFIX } from './utils-hoist/baggage.js';\nimport './debug-build.js';\nimport { hasTracingEnabled } from './utils/hasTracingEnabled.js';\nimport { getActiveSpan } from './utils/spanUtils.js';\nimport { SentryNonRecordingSpan } from './tracing/sentryNonRecordingSpan.js';\nimport { setHttpStatus, SPAN_STATUS_ERROR } from './tracing/spanstatus.js';\nimport { startInactiveSpan } from './tracing/trace.js';\nimport { getTraceData } from './utils/traceData.js';\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 */\nfunction instrumentFetchRequest(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n spanOrigin = 'auto.http.browser',\n) {\n if (!handlerData.fetchData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = hasTracingEnabled() && shouldCreateSpan(handlerData.fetchData.url);\n\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n endSpan(span, handlerData);\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const { method, url } = handlerData.fetchData;\n\n const fullUrl = getFullURL(url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const hasParent = !!getActiveSpan();\n\n const span =\n shouldCreateSpanResult && hasParent\n ? startInactiveSpan({\n name: `${method} ${url}`,\n attributes: {\n url,\n type: 'fetch',\n 'http.method': method,\n 'http.url': fullUrl,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.client',\n },\n })\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 = handlerData.args[0];\n\n const options = 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 hasTracingEnabled() && hasParent ? span : undefined,\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 return span;\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers.\n */\nfunction _addTracingHeadersToFetchRequest(\n request,\n fetchOptionsObj\n\n,\n span,\n) {\n const traceHeaders = getTraceData({ span });\n const sentryTrace = traceHeaders['sentry-trace'];\n const baggage = traceHeaders.baggage;\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 headers = fetchOptionsObj.headers || (isRequest(request) ? request.headers : undefined);\n\n if (!headers) {\n return { ...traceHeaders };\n } else if (isHeaders(headers)) {\n const newHeaders = new Headers(headers);\n newHeaders.set('sentry-trace', sentryTrace);\n\n if (baggage) {\n const prevBaggageHeader = newHeaders.get('baggage');\n if (prevBaggageHeader) {\n const prevHeaderStrippedFromSentryBaggage = stripBaggageHeaderOfSentryBaggageValues(prevBaggageHeader);\n newHeaders.set(\n 'baggage',\n // If there are non-sentry entries (i.e. if the stripped string is non-empty/truthy) combine the stripped header and sentry baggage header\n // otherwise just set the sentry baggage header\n prevHeaderStrippedFromSentryBaggage ? `${prevHeaderStrippedFromSentryBaggage},${baggage}` : baggage,\n );\n } else {\n newHeaders.set('baggage', baggage);\n }\n }\n\n return newHeaders;\n } else if (Array.isArray(headers)) {\n const newHeaders = [\n ...headers\n // Remove any existing sentry-trace headers\n .filter(header => {\n return !(Array.isArray(header) && header[0] === 'sentry-trace');\n })\n // Get rid of previous sentry baggage values in baggage header\n .map(header => {\n if (Array.isArray(header) && header[0] === 'baggage' && typeof header[1] === 'string') {\n const [headerName, headerValue, ...rest] = header;\n return [headerName, stripBaggageHeaderOfSentryBaggageValues(headerValue), ...rest];\n } else {\n return header;\n }\n }),\n // Attach the new sentry-trace header\n ['sentry-trace', sentryTrace],\n ];\n\n if (baggage) {\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 ;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n let newBaggageHeaders = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders = existingBaggageHeader\n .map(headerItem =>\n typeof headerItem === 'string' ? stripBaggageHeaderOfSentryBaggageValues(headerItem) : headerItem,\n )\n .filter(headerItem => headerItem === '');\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(stripBaggageHeaderOfSentryBaggageValues(existingBaggageHeader));\n }\n\n if (baggage) {\n newBaggageHeaders.push(baggage);\n }\n\n return {\n ...(headers ),\n 'sentry-trace': sentryTrace,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers.\n *\n * @deprecated This function will not be exported anymore in v9.\n */\nfunction addTracingHeadersToFetchRequest(\n request,\n _client,\n _scope,\n fetchOptionsObj\n\n,\n span,\n) {\n return _addTracingHeadersToFetchRequest(request , fetchOptionsObj, span);\n}\n\nfunction getFullURL(url) {\n try {\n const parsed = new URL(url);\n return parsed.href;\n } catch (e) {\n return undefined;\n }\n}\n\nfunction endSpan(span, handlerData) {\n if (handlerData.response) {\n setHttpStatus(span, handlerData.response.status);\n\n const contentLength =\n handlerData.response && handlerData.response.headers && handlerData.response.headers.get('content-length');\n\n if (contentLength) {\n const contentLengthNum = parseInt(contentLength);\n if (contentLengthNum > 0) {\n span.setAttribute('http.response_content_length', contentLengthNum);\n }\n }\n } else if (handlerData.error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n span.end();\n}\n\nfunction stripBaggageHeaderOfSentryBaggageValues(baggageHeader) {\n return (\n baggageHeader\n .split(',')\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n .filter(baggageEntry => !baggageEntry.split('=')[0].startsWith(SENTRY_BAGGAGE_KEY_PREFIX))\n .join(',')\n );\n}\n\nfunction isRequest(request) {\n return typeof Request !== 'undefined' && isInstanceOf(request, Request);\n}\n\nfunction isHeaders(headers) {\n return typeof Headers !== 'undefined' && isInstanceOf(headers, Headers);\n}\n\nexport { addTracingHeadersToFetchRequest, instrumentFetchRequest };\n//# sourceMappingURL=fetch.js.map\n","/**\n * Determine a breadcrumb's log level (only `warning` or `error`) based on an HTTP status code.\n */\nfunction getBreadcrumbLogLevelFromHttpStatusCode(statusCode) {\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\nexport { getBreadcrumbLogLevelFromHttpStatusCode };\n//# sourceMappingURL=breadcrumb-log-level.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { logger } from './logger.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nconst WINDOW = GLOBAL_OBJ ;\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsErrorEvent() {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMError() {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-expect-error It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMException() {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsFetch() {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * isNative checks if the given function is a native implementation\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isNativeFunction(func) {\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 */\nfunction supportsNativeFetch() {\n if (typeof EdgeRuntime === 'string') {\n return true;\n }\n\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (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 ) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFunction(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n DEBUG_BUILD &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsReportingObserver() {\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 */\nfunction supportsReferrerPolicy() {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' ,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n\nexport { isNativeFunction, supportsDOMError, supportsDOMException, supportsErrorEvent, supportsFetch, supportsNativeFetch, supportsReferrerPolicy, supportsReportingObserver };\n//# sourceMappingURL=supports.js.map\n","import { isError } from '../is.js';\nimport { fill, addNonEnumerableProperty } from '../object.js';\nimport { supportsNativeFetch } from '../supports.js';\nimport { timestampInSeconds } from '../time.js';\nimport { GLOBAL_OBJ } from '../worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\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 */\nfunction addFetchInstrumentationHandler(\n handler,\n skipNativeFetchCheck,\n) {\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 */\nfunction addFetchEndInstrumentationHandler(handler) {\n const type = 'fetch-body-resolved';\n addHandler(type, handler);\n maybeInstrument(type, () => instrumentFetch(streamHandler));\n}\n\nfunction instrumentFetch(onFetchResolved, skipNativeFetchCheck = false) {\n if (skipNativeFetchCheck && !supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch) {\n return function (...args) {\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 = {\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 };\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) => {\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) => {\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 // 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, onFinishedResolving) {\n if (res && 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 (error) {\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) {\n // clone response for awaiting stream\n let clonedResponseForResolving;\n try {\n clonedResponseForResolving = response.clone();\n } catch (e) {\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, prop) {\n return !!obj && typeof obj === 'object' && !!(obj )[prop];\n}\n\nfunction getUrlFromResource(resource) {\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 */\nfunction parseFetchArgs(fetchArgs) {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs ;\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg ),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n\nexport { addFetchEndInstrumentationHandler, addFetchInstrumentationHandler, parseFetchArgs };\n//# sourceMappingURL=fetch.js.map\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 * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nfunction isBrowserBundle() {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nfunction getSDKSource() {\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\nexport { getSDKSource, isBrowserBundle };\n//# sourceMappingURL=env.js.map\n","import { isBrowserBundle } from './env.js';\n\n/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nfunction isNodeEnv() {\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 * @deprecated This function will be removed in the next major version.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction dynamicRequire(mod, request) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @returns possibly required module\n */\nfunction loadModule(moduleName) {\n let mod;\n\n try {\n // eslint-disable-next-line deprecation/deprecation\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n if (!mod) {\n try {\n // eslint-disable-next-line deprecation/deprecation\n const { cwd } = dynamicRequire(module, 'process');\n // eslint-disable-next-line deprecation/deprecation\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) ;\n } catch (e) {\n // no-empty\n }\n }\n\n return mod;\n}\n\nexport { dynamicRequire, isNodeEnv, loadModule };\n//# sourceMappingURL=node.js.map\n","import { isNodeEnv } from './node.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * Returns true if we are in the browser.\n */\nfunction isBrowser() {\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' && (!isNodeEnv() || isElectronNodeRenderer());\n}\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer() {\n const process = (GLOBAL_OBJ ).process;\n return !!process && process.type === 'renderer';\n}\n\nexport { isBrowser };\n//# sourceMappingURL=isBrowser.js.map\n","import { GLOBAL_OBJ } from '../worldwide.js';\n\n// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n\nconst WINDOW = GLOBAL_OBJ ;\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsHistory() {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n // TODO(v9): Remove this custom check, it is pretty old and likely not needed anymore\n const chromeVar = (WINDOW ).chrome;\n const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n\nexport { supportsHistory };\n//# sourceMappingURL=supportsHistory.js.map\n","// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Polyfill for the nullish coalescing operator (`??`).\n *\n * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the\n * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n *\n * @param lhs The value of the expression to the left of the `??`\n * @param rhsFn A function returning the value of the expression to the right of the `??`\n * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value\n */\nfunction _nullishCoalesce(lhs, rhsFn) {\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n return lhs != null ? lhs : rhsFn();\n}\n\n// Sucrase version:\n// function _nullishCoalesce(lhs, rhsFn) {\n// if (lhs != null) {\n// return lhs;\n// } else {\n// return rhsFn();\n// }\n// }\n\nexport { _nullishCoalesce };\n//# sourceMappingURL=_nullishCoalesce.js.map\n","/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The value of the expression\n */\nfunction _optionalChain(ops) {\n let lastAccessLHS = undefined;\n let value = ops[0];\n let i = 1;\n while (i < ops.length) {\n const op = ops[i] ;\n const fn = ops[i + 1] ;\n i += 2;\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it\n return;\n }\n if (op === 'access' || op === 'optionalAccess') {\n lastAccessLHS = value;\n value = fn(value);\n } else if (op === 'call' || op === 'optionalCall') {\n value = fn((...args) => (value ).call(lastAccessLHS, ...args));\n lastAccessLHS = undefined;\n }\n }\n return value;\n}\n\n// Sucrase version\n// function _optionalChain(ops) {\n// let lastAccessLHS = undefined;\n// let value = ops[0];\n// let i = 1;\n// while (i < ops.length) {\n// const op = ops[i];\n// const fn = ops[i + 1];\n// i += 2;\n// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n// return undefined;\n// }\n// if (op === 'access' || op === 'optionalAccess') {\n// lastAccessLHS = value;\n// value = fn(value);\n// } else if (op === 'call' || op === 'optionalCall') {\n// value = fn((...args) => value.call(lastAccessLHS, ...args));\n// lastAccessLHS = undefined;\n// }\n// }\n// return value;\n// }\n\nexport { _optionalChain };\n//# sourceMappingURL=_optionalChain.js.map\n","import { GLOBAL_OBJ, getOriginalFunction, markFunctionWrapped, addNonEnumerableProperty, withScope, addExceptionTypeValue, addExceptionMechanism, captureException } from '@sentry/core';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nlet ignoreOnError = 0;\n\n/**\n * @hidden\n */\nfunction shouldIgnoreOnError() {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nfunction ignoreNextOnError() {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nfunction wrap(\n fn,\n options\n\n = {},\n) {\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) {\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 ).__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 (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n // 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 ( ...args) {\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 captureException(ex);\n });\n\n throw ex;\n }\n } ;\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 ] = fn[property ];\n }\n }\n } catch (e2) {\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() {\n return fn.name;\n },\n });\n }\n } catch (e3) {\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\nexport { WINDOW, ignoreNextOnError, shouldIgnoreOnError, wrap };\n//# sourceMappingURL=helpers.js.map\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 */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","import { addExceptionMechanism, resolvedSyncPromise, isErrorEvent, isDOMError, isDOMException, addExceptionTypeValue, isError, isPlainObject, isEvent, isParameterizedString, getClient, normalizeToSize, extractExceptionKeysForMessage } from '@sentry/core';\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nfunction exceptionFromError(stackParser, ex) {\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 = {\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,\n exception,\n syntheticException,\n isUnhandledRejection,\n) {\n const client = getClient();\n const normalizeDepth = client && 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 } ,\n ],\n },\n extra,\n } ;\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n // 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, ex) {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nfunction parseStackFrames(\n stackParser,\n ex,\n) {\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 (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\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) {\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) {\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) {\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 */\nfunction extractType(ex) {\n const name = ex && 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 */\nfunction extractMessage(ex) {\n const message = ex && ex.message;\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 // Emscripten sets array[type, message] to the \"message\" property on the WebAssembly.Exception object\n if (isWebAssemblyException(ex) && Array.isArray(ex.message) && ex.message.length == 2) {\n return ex.message[1];\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 */\nfunction eventFromException(\n stackParser,\n exception,\n hint,\n attachStacktrace,\n) {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nfunction eventFromMessage(\n stackParser,\n message,\n level = 'info',\n hint,\n attachStacktrace,\n) {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nfunction eventFromUnknownInput(\n stackParser,\n exception,\n syntheticException,\n attachStacktrace,\n isUnhandledRejection,\n) {\n let event;\n\n if (isErrorEvent(exception ) && (exception ).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception ;\n return eventFromError(stackParser, errorEvent.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 )) {\n const domException = exception ;\n\n if ('stack' in (exception )) {\n event = eventFromError(stackParser, exception );\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 , syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\nfunction eventFromString(\n stackParser,\n message,\n syntheticException,\n attachStacktrace,\n) {\n const 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,\n { isUnhandledRejection },\n) {\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) {\n try {\n const prototype = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : undefined;\n } catch (e) {\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) {\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\nexport { eventFromException, eventFromMessage, eventFromUnknownInput, exceptionFromError, extractMessage, extractType };\n//# sourceMappingURL=eventbuilder.js.map\n","import { dsnToString, createEnvelope } from '@sentry/core';\n\n/**\n * Creates an envelope from a user feedback.\n */\nfunction createUserFeedbackEnvelope(\n feedback,\n {\n metadata,\n tunnel,\n dsn,\n }\n\n,\n) {\n const headers = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback) {\n const feedbackHeaders = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n\nexport { createUserFeedbackEnvelope };\n//# sourceMappingURL=userfeedback.js.map\n","import { BaseClient, getSDKSource, applySdkMetadata, logger } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { eventFromException, eventFromMessage } from './eventbuilder.js';\nimport { WINDOW } from './helpers.js';\nimport { createUserFeedbackEnvelope } from './userfeedback.js';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/core Options for more information.\n */\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nclass BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n constructor(options) {\n const opts = {\n // We default this to true, as it is the safer scenario\n parentSpanIsAlwaysRootSpan: true,\n ...options,\n };\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(opts, 'browser', ['browser'], sdkSource);\n\n super(opts);\n\n if (opts.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n eventFromException(exception, hint) {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n eventFromMessage(\n message,\n level = 'info',\n hint,\n ) {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * Sends user feedback to Sentry.\n *\n * @deprecated Use `captureFeedback` instead.\n */\n captureUserFeedback(feedback) {\n if (!this._isEnabled()) {\n DEBUG_BUILD && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n _prepareEvent(event, hint, scope) {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n}\n\nexport { BrowserClient };\n//# sourceMappingURL=client.js.map\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 */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","const getRating = (value, thresholds) => {\n if (value > thresholds[1]) {\n return 'poor';\n }\n if (value > thresholds[0]) {\n return 'needs-improvement';\n }\n return 'good';\n};\n\nconst bindReporter = (\n callback,\n metric,\n thresholds,\n reportAllChanges,\n) => {\n let prevValue;\n let delta;\n return (forceReport) => {\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\nexport { bindReporter };\n//# sourceMappingURL=bindReporter.js.map\n","import { GLOBAL_OBJ } from '@sentry/core';\n\nconst WINDOW = GLOBAL_OBJ\n\n;\n\nexport { WINDOW };\n//# sourceMappingURL=types.js.map\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 */\nconst generateUniqueID = () => {\n return `v4-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n\nexport { generateUniqueID };\n//# sourceMappingURL=generateUniqueID.js.map\n","import { WINDOW } from '../../../types.js';\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\n\n// sentry-specific change:\n// add optional param to not check for responseStart (see comment below)\nconst getNavigationEntry = (checkResponseStart = true) => {\n const navigationEntry =\n WINDOW.performance && WINDOW.performance.getEntriesByType && WINDOW.performance.getEntriesByType('navigation')[0];\n // Check to ensure the `responseStart` property is present and valid.\n // In some cases no 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\nexport { getNavigationEntry };\n//# sourceMappingURL=getNavigationEntry.js.map\n","import { getNavigationEntry } from './getNavigationEntry.js';\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\n\nconst getActivationStart = () => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n\nexport { getActivationStart };\n//# sourceMappingURL=getActivationStart.js.map\n","import { WINDOW } from '../../../types.js';\nimport { generateUniqueID } from './generateUniqueID.js';\nimport { getActivationStart } from './getActivationStart.js';\nimport { getNavigationEntry } from './getNavigationEntry.js';\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\nconst initMetric = (name, value) => {\n const navEntry = getNavigationEntry();\n let navigationType = 'navigate';\n\n if (navEntry) {\n if ((WINDOW.document && WINDOW.document.prerendering) || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else if (WINDOW.document && WINDOW.document.wasDiscarded) {\n navigationType = 'restore';\n } else if (navEntry.type) {\n navigationType = navEntry.type.replace(/_/g, '-') ;\n }\n }\n\n // Use `entries` type specific for the metric.\n const entries = [];\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good' , // 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\nexport { initMetric };\n//# sourceMappingURL=initMetric.js.map\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 * 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 */\nconst observe = (\n type,\n callback,\n opts,\n) => {\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() );\n });\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) ,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n\nexport { observe };\n//# sourceMappingURL=observe.js.map\n","import { WINDOW } from '../../../types.js';\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// Sentry-specific change:\n// This function's logic was NOT updated to web-vitals 4.2.4 but we continue\n// to use the web-vitals 3.5.2 due 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 12.1-14.0) don't fully support `visibilitychange`\n// or have known bugs w.r.t the `visibilitychange` event.\n// TODO (v9): If we decide to drop support for Safari 12.1-14.0, 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.\nconst onHidden = (cb) => {\n const onHiddenOrPageHide = (event) => {\n if (event.type === 'pagehide' || (WINDOW.document && WINDOW.document.visibilityState === 'hidden')) {\n cb(event);\n }\n };\n\n if (WINDOW.document) {\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n }\n};\n\nexport { onHidden };\n//# sourceMappingURL=onHidden.js.map\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\nconst runOnce = (cb) => {\n let called = false;\n return () => {\n if (!called) {\n cb();\n called = true;\n }\n };\n};\n\nexport { runOnce };\n//# sourceMappingURL=runOnce.js.map\n","import { WINDOW } from '../../../types.js';\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\nlet firstHiddenTime = -1;\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) => {\n // If the document is 'hidden' and no previous hidden timestamp has been\n // set, update it based on the current event data.\n if (WINDOW.document.visibilityState === 'hidden' && firstHiddenTime > -1) {\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' 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 // Remove all listeners now that a `firstHiddenTime` value has been set.\n removeChangeListeners();\n }\n};\n\nconst addChangeListeners = () => {\n addEventListener('visibilitychange', onVisibilityUpdate, true);\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 addEventListener('prerenderingchange', onVisibilityUpdate, true);\n};\n\nconst removeChangeListeners = () => {\n removeEventListener('visibilitychange', onVisibilityUpdate, true);\n removeEventListener('prerenderingchange', onVisibilityUpdate, true);\n};\n\nconst getVisibilityWatcher = () => {\n if (WINDOW.document && firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n firstHiddenTime = initHiddenTime();\n addChangeListeners();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n\nexport { getVisibilityWatcher };\n//# sourceMappingURL=getVisibilityWatcher.js.map\n","import { WINDOW } from '../../../types.js';\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\n\nconst whenActivated = (callback) => {\n if (WINDOW.document && WINDOW.document.prerendering) {\n addEventListener('prerenderingchange', () => callback(), true);\n } else {\n callback();\n }\n};\n\nexport { whenActivated };\n//# sourceMappingURL=whenActivated.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { getActivationStart } from './lib/getActivationStart.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { whenActivated } from './lib/whenActivated.js';\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/** Thresholds for FCP. See https://web.dev/articles/fcp#what_is_a_good_fcp_score */\nconst FCPThresholds = [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 */\nconst onFCP = (onReport, opts = {}) => {\n whenActivated(() => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FCP');\n let report;\n\n const handleEntries = (entries) => {\n entries.forEach(entry => {\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\nexport { FCPThresholds, onFCP };\n//# sourceMappingURL=onFCP.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\nimport { runOnce } from './lib/runOnce.js';\nimport { onFCP } from './onFCP.js';\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/** Thresholds for CLS. See https://web.dev/articles/cls#what_is_a_good_cls_score */\nconst CLSThresholds = [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 */\nconst onCLS = (onReport, opts = {}) => {\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;\n\n let sessionValue = 0;\n let sessionEntries = [];\n\n const handleEntries = (entries) => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry\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 sessionValue &&\n firstSessionEntry &&\n lastSessionEntry &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n }\n });\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n report();\n }\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric, CLSThresholds, opts.reportAllChanges);\n\n onHidden(() => {\n handleEntries(po.takeRecords() );\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 setTimeout(report, 0);\n }\n }),\n );\n};\n\nexport { CLSThresholds, onCLS };\n//# sourceMappingURL=getCLS.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\nimport { runOnce } from './lib/runOnce.js';\nimport { whenActivated } from './lib/whenActivated.js';\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/** Thresholds for FID. See https://web.dev/articles/fid#what_is_a_good_fid_score */\nconst FIDThresholds = [100, 300];\n\n/**\n * Calculates the [FID](https://web.dev/articles/fid) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nconst onFID = (onReport, opts = {}) => {\n whenActivated(() => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report;\n\n const handleEntry = (entry) => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries) => {\n (entries ).forEach(handleEntry);\n };\n\n const po = observe('first-input', handleEntries);\n\n report = bindReporter(onReport, metric, FIDThresholds, opts.reportAllChanges);\n\n if (po) {\n onHidden(\n runOnce(() => {\n handleEntries(po.takeRecords() );\n po.disconnect();\n }),\n );\n }\n });\n};\n\nexport { FIDThresholds, onFID };\n//# sourceMappingURL=getFID.js.map\n","import { observe } from '../observe.js';\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\n\nlet interactionCountEstimate = 0;\nlet minKnownInteractionId = Infinity;\nlet maxKnownInteractionId = 0;\n\nconst updateEstimate = (entries) => {\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;\n\n/**\n * Returns the `interactionCount` value using the native API (if available)\n * or the polyfill estimate in this module.\n */\nconst getInteractionCount = () => {\n return po ? interactionCountEstimate : performance.interactionCount || 0;\n};\n\n/**\n * Feature detects native support or initializes the polyfill if needed.\n */\nconst initInteractionCountPolyfill = () => {\n if ('interactionCount' in performance || po) return;\n\n po = observe('event', updateEstimate, {\n type: 'event',\n buffered: true,\n durationThreshold: 0,\n } );\n};\n\nexport { getInteractionCount, initInteractionCountPolyfill };\n//# sourceMappingURL=interactionCountPolyfill.js.map\n","import { getInteractionCount } from './polyfills/interactionCountPolyfill.js';\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\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 long.\nconst longestInteractionList = [];\n\n// A mapping of longest interactions by their interaction ID.\n// This is used for faster lookup.\nconst longestInteractionMap = new Map();\n\n// The default `durationThreshold` used across this library for observing\n// `event` entries via PerformanceObserver.\nconst DEFAULT_DURATION_THRESHOLD = 40;\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 * Returns the estimated p98 longest interaction based on the stored\n * interaction candidates and the interaction count for the current page.\n */\nconst estimateP98LongestInteraction = () => {\n const candidateInteractionIndex = Math.min(\n longestInteractionList.length - 1,\n Math.floor(getInteractionCountForNavigation() / 50),\n );\n\n return longestInteractionList[candidateInteractionIndex];\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/**\n * A list of callback functions to run before each entry is processed.\n * Exposing this list allows the attribution build to hook into the\n * entry processing pipeline.\n */\nconst entryPreProcessingCallbacks = [];\n\n/**\n * Takes a performance entry and adds it to the list of worst interactions\n * if its duration is long enough to make it among the worst. If the\n * entry is part of an existing interaction, it is merged and the latency\n * and entries list is updated as needed.\n */\nconst processInteractionEntry = (entry) => {\n entryPreProcessingCallbacks.forEach(cb => cb(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 = longestInteractionList[longestInteractionList.length - 1];\n\n const existingInteraction = 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 existingInteraction ||\n longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER ||\n (minLongestInteraction && entry.duration > minLongestInteraction.latency)\n ) {\n // If the interaction already exists, update it. Otherwise create one.\n if (existingInteraction) {\n // If the new entry has a longer duration, replace the old entries,\n // otherwise add to the array.\n if (entry.duration > existingInteraction.latency) {\n existingInteraction.entries = [entry];\n existingInteraction.latency = entry.duration;\n } else if (\n entry.duration === existingInteraction.latency &&\n entry.startTime === (existingInteraction.entries[0] && existingInteraction.entries[0].startTime)\n ) {\n existingInteraction.entries.push(entry);\n }\n } else {\n const interaction = {\n id: entry.interactionId,\n latency: entry.duration,\n entries: [entry],\n };\n longestInteractionMap.set(interaction.id, interaction);\n longestInteractionList.push(interaction);\n }\n\n // Sort the entries by latency (descending) and keep only the top ten.\n longestInteractionList.sort((a, b) => b.latency - a.latency);\n if (longestInteractionList.length > MAX_INTERACTIONS_TO_CONSIDER) {\n longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER).forEach(i => longestInteractionMap.delete(i.id));\n }\n }\n};\n\nexport { DEFAULT_DURATION_THRESHOLD, entryPreProcessingCallbacks, estimateP98LongestInteraction, longestInteractionList, longestInteractionMap, processInteractionEntry };\n//# sourceMappingURL=interactions.js.map\n","import { WINDOW } from '../../../types.js';\nimport { onHidden } from './onHidden.js';\nimport { runOnce } from './runOnce.js';\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\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 */\nconst whenIdle = (cb) => {\n const rIC = WINDOW.requestIdleCallback || WINDOW.setTimeout;\n\n let handle = -1;\n // eslint-disable-next-line no-param-reassign\n cb = runOnce(cb) ;\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 && WINDOW.document.visibilityState === 'hidden') {\n cb();\n } else {\n handle = rIC(cb);\n onHidden(cb);\n }\n return handle;\n};\n\nexport { whenIdle };\n//# sourceMappingURL=whenIdle.js.map\n","import { WINDOW } from '../../types.js';\nimport { bindReporter } from './lib/bindReporter.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { DEFAULT_DURATION_THRESHOLD, processInteractionEntry, estimateP98LongestInteraction } from './lib/interactions.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\nimport { initInteractionCountPolyfill } from './lib/polyfills/interactionCountPolyfill.js';\nimport { whenActivated } from './lib/whenActivated.js';\nimport { whenIdle } from './lib/whenIdle.js';\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\n\n/** Thresholds for INP. See https://web.dev/articles/inp#what_is_a_good_inp_score */\nconst INPThresholds = [200, 500];\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 to\n * control what `event-timing` entries are considered for INP reporting. The\n * default threshold is `40`, which means INP scores of less than 40 are\n * reported as 0. Note that this will not affect your 75th percentile INP value\n * unless that value is also less than 40 (well below the recommended\n * [good](https://web.dev/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 */\nconst onINP = (onReport, opts = {}) => {\n // Return if the browser doesn't support all APIs needed to measure INP.\n if (!('PerformanceEventTiming' in WINDOW && 'interactionId' in PerformanceEventTiming.prototype)) {\n return;\n }\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;\n\n const handleEntries = (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 whenIdle(() => {\n entries.forEach(processInteractionEntry);\n\n const inp = estimateP98LongestInteraction();\n\n if (inp && inp.latency !== metric.value) {\n metric.value = inp.latency;\n metric.entries = inp.entries;\n report();\n }\n });\n };\n\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 != null ? 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 onHidden(() => {\n handleEntries(po.takeRecords() );\n report(true);\n });\n }\n });\n};\n\nexport { INPThresholds, onINP };\n//# sourceMappingURL=getINP.js.map\n","import { WINDOW } from '../../types.js';\nimport { bindReporter } from './lib/bindReporter.js';\nimport { getActivationStart } from './lib/getActivationStart.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\nimport { runOnce } from './lib/runOnce.js';\nimport { whenActivated } from './lib/whenActivated.js';\nimport { whenIdle } from './lib/whenIdle.js';\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/** Thresholds for LCP. See https://web.dev/articles/lcp#what_is_a_good_lcp_score */\nconst LCPThresholds = [2500, 4000];\n\nconst reportedMetricIDs = {};\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 */\nconst onLCP = (onReport, opts = {}) => {\n whenActivated(() => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report;\n\n const handleEntries = (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 entries.forEach(entry => {\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 pre-rendered. 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 const stopListening = runOnce(() => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() );\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n });\n\n // Stop listening after input. Note: while scrolling is an input that\n // stops LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n // Wrap in a setTimeout so the callback is run in a separate task\n // to avoid extending the keyboard/click handler to reduce INP impact\n // https://github.com/GoogleChrome/web-vitals/issues/383\n if (WINDOW.document) {\n addEventListener(type, () => whenIdle(stopListening ), {\n once: true,\n capture: true,\n });\n }\n });\n\n onHidden(stopListening);\n }\n });\n};\n\nexport { LCPThresholds, onLCP };\n//# sourceMappingURL=getLCP.js.map\n","import { WINDOW } from '../../types.js';\nimport { bindReporter } from './lib/bindReporter.js';\nimport { getActivationStart } from './lib/getActivationStart.js';\nimport { getNavigationEntry } from './lib/getNavigationEntry.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { whenActivated } from './lib/whenActivated.js';\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/** Thresholds for TTFB. See https://web.dev/articles/ttfb#what_is_a_good_ttfb_score */\nconst TTFBThresholds = [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) => {\n if (WINDOW.document && WINDOW.document.prerendering) {\n whenActivated(() => whenReady(callback));\n } else if (WINDOW.document && WINDOW.document.readyState !== 'complete') {\n addEventListener('load', () => whenReady(callback), true);\n } else {\n // Queue a task so the callback runs after `loadEventEnd`.\n setTimeout(callback, 0);\n }\n};\n\n/**\n * Calculates the [TTFB](https://web.dev/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 */\nconst onTTFB = (onReport, opts = {}) => {\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\nexport { TTFBThresholds, onTTFB };\n//# sourceMappingURL=onTTFB.js.map\n","import { logger, getFunctionName } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { onCLS } from './web-vitals/getCLS.js';\nimport { onFID } from './web-vitals/getFID.js';\nimport { onINP } from './web-vitals/getINP.js';\nimport { onLCP } from './web-vitals/getLCP.js';\nimport { observe } from './web-vitals/lib/observe.js';\nimport { onTTFB } from './web-vitals/onTTFB.js';\n\nconst handlers = {};\nconst instrumented = {};\n\nlet _previousCls;\nlet _previousFid;\nlet _previousLcp;\nlet _previousTtfb;\nlet _previousInp;\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 */\nfunction addClsInstrumentationHandler(\n callback,\n stopOnCallback = false,\n) {\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 */\nfunction addLcpInstrumentationHandler(\n callback,\n stopOnCallback = false,\n) {\n return addMetricObserver('lcp', callback, instrumentLcp, _previousLcp, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nfunction addFidInstrumentationHandler(callback) {\n return addMetricObserver('fid', callback, instrumentFid, _previousFid);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n */\nfunction addTtfbInstrumentationHandler(callback) {\n return addMetricObserver('ttfb', callback, instrumentTtfb, _previousTtfb);\n}\n\n/**\n * Add a callback that will be triggered when a INP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nfunction addInpInstrumentationHandler(\n callback,\n) {\n return addMetricObserver('inp', callback, instrumentInp, _previousInp);\n}\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 */\nfunction addPerformanceInstrumentationHandler(\n type,\n callback,\n) {\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, data) {\n const typeHandlers = handlers[type];\n\n if (!typeHandlers || !typeHandlers.length) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nfunction instrumentCls() {\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 instrumentFid() {\n return onFID(metric => {\n triggerHandlers('fid', {\n metric,\n });\n _previousFid = metric;\n });\n}\n\nfunction instrumentLcp() {\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() {\n return onTTFB(metric => {\n triggerHandlers('ttfb', {\n metric,\n });\n _previousTtfb = metric;\n });\n}\n\nfunction instrumentInp() {\n return onINP(metric => {\n triggerHandlers('inp', {\n metric,\n });\n _previousInp = metric;\n });\n}\n\nfunction addMetricObserver(\n type,\n callback,\n instrumentFn,\n previousValue,\n stopOnCallback = false,\n) {\n addHandler(type, callback);\n\n let stopListening;\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) {\n const options = {};\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, handler) {\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,\n callback,\n stopListening,\n) {\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 */\nfunction isPerformanceEventTiming(entry) {\n return 'duration' in entry;\n}\n\nexport { addClsInstrumentationHandler, addFidInstrumentationHandler, addInpInstrumentationHandler, addLcpInstrumentationHandler, addPerformanceInstrumentationHandler, addTtfbInstrumentationHandler, isPerformanceEventTiming };\n//# sourceMappingURL=instrument.js.map\n","import { spanToJSON, withActiveSpan, startInactiveSpan, getClient, getCurrentScope } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nfunction isMeasurementValue(value) {\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 */\nfunction startAndEndSpan(\n parentSpan,\n startTimeInSeconds,\n endTime,\n { ...ctx },\n) {\n const parentStartTime = spanToJSON(parentSpan).start_timestamp;\n if (parentStartTime && parentStartTime > startTimeInSeconds) {\n // We can only do this for SentrySpans...\n if (typeof (parentSpan ).updateStartTime === 'function') {\n (parentSpan ).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\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 */\nfunction startStandaloneWebVitalSpan(options) {\n const client = getClient();\n if (!client) {\n return;\n }\n\n const { name, transaction, attributes: passedAttributes, startTime } = options;\n\n const { release, environment } = 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('Replay');\n const replayId = replay && 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;\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 (e) {\n // do nothing\n }\n\n const attributes = {\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 && WINDOW.navigator.userAgent,\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. */\nfunction getBrowserPerformanceAPI() {\n // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are\n return WINDOW && WINDOW.addEventListener && WINDOW.performance;\n}\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time) {\n return time / 1000;\n}\n\nexport { getBrowserPerformanceAPI, isMeasurementValue, msToSec, startAndEndSpan, startStandaloneWebVitalSpan };\n//# sourceMappingURL=utils.js.map\n","import { getClient, getActiveSpan, getRootSpan, spanToJSON, logger, browserPerformanceTimeOrigin, getCurrentScope, htmlTreeAsString, dropUndefinedKeys, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { addClsInstrumentationHandler } from './instrument.js';\nimport { msToSec, startStandaloneWebVitalSpan } from './utils.js';\nimport { onHidden } from './web-vitals/lib/onHidden.js';\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 */\nfunction trackClsAsStandaloneSpan() {\n let standaloneCLsValue = 0;\n let standaloneClsEntry;\n let pageloadSpanId;\n\n if (!supportsLayoutShift()) {\n return;\n }\n\n let sentSpan = false;\n function _collectClsOnce() {\n if (sentSpan) {\n return;\n }\n sentSpan = true;\n if (pageloadSpanId) {\n sendStandaloneClsSpan(standaloneCLsValue, standaloneClsEntry, pageloadSpanId);\n }\n cleanupClsHandler();\n }\n\n const cleanupClsHandler = addClsInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1] ;\n if (!entry) {\n return;\n }\n standaloneCLsValue = metric.value;\n standaloneClsEntry = entry;\n }, true);\n\n // use pagehide event from web-vitals\n onHidden(() => {\n _collectClsOnce();\n });\n\n // Since the call chain of this function is synchronous and evaluates before the SDK client is created,\n // we need to wait with subscribing to a client hook until the client is created. Therefore, we defer\n // to the next tick after the SDK setup.\n setTimeout(() => {\n const client = getClient();\n\n if (!client) {\n return;\n }\n\n const unsubscribeStartNavigation = client.on('startNavigationSpan', () => {\n _collectClsOnce();\n unsubscribeStartNavigation && unsubscribeStartNavigation();\n });\n\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n const spanJSON = rootSpan && spanToJSON(rootSpan);\n if (spanJSON && spanJSON.op === 'pageload') {\n pageloadSpanId = rootSpan.spanContext().spanId;\n }\n }, 0);\n}\n\nfunction sendStandaloneClsSpan(clsValue, entry, pageloadSpanId) {\n DEBUG_BUILD && logger.log(`Sending CLS span (${clsValue})`);\n\n const startTime = msToSec((browserPerformanceTimeOrigin || 0) + ((entry && entry.startTime) || 0));\n const routeName = getCurrentScope().getScopeData().transactionName;\n\n const name = entry ? htmlTreeAsString(entry.sources[0] && entry.sources[0].node) : 'Layout shift';\n\n const attributes = dropUndefinedKeys({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser.cls',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'ui.webvital.cls',\n [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: (entry && entry.duration) || 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 });\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\nfunction supportsLayoutShift() {\n try {\n return PerformanceObserver.supportedEntryTypes.includes('layout-shift');\n } catch (e) {\n return false;\n }\n}\n\nexport { trackClsAsStandaloneSpan };\n//# sourceMappingURL=cls.js.map\n","import { browserPerformanceTimeOrigin, getActiveSpan, spanToJSON, setMeasurement, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, parseUrl, htmlTreeAsString, getComponentName } from '@sentry/core';\nimport { WINDOW } from '../types.js';\nimport { trackClsAsStandaloneSpan } from './cls.js';\nimport { addPerformanceInstrumentationHandler, addClsInstrumentationHandler, addLcpInstrumentationHandler, addFidInstrumentationHandler, addTtfbInstrumentationHandler } from './instrument.js';\nimport { getBrowserPerformanceAPI, msToSec, startAndEndSpan, isMeasurementValue } from './utils.js';\nimport { getActivationStart } from './web-vitals/lib/getActivationStart.js';\nimport { getNavigationEntry } from './web-vitals/lib/getNavigationEntry.js';\nimport { getVisibilityWatcher } from './web-vitals/lib/getVisibilityWatcher.js';\n\nconst MAX_INT_AS_BYTES = 2147483647;\n\nlet _performanceCursor = 0;\n\nlet _measurements = {};\nlet _lcpEntry;\nlet _clsEntry;\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 */\nfunction startTrackingWebVitals({ recordClsStandaloneSpans }) {\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 fidCleanupCallback = _trackFID();\n const lcpCleanupCallback = _trackLCP();\n const ttfbCleanupCallback = _trackTtfb();\n const clsCleanupCallback = recordClsStandaloneSpans ? trackClsAsStandaloneSpan() : _trackCLS();\n\n return () => {\n fidCleanupCallback();\n lcpCleanupCallback();\n ttfbCleanupCallback();\n clsCleanupCallback && clsCleanupCallback();\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nfunction startTrackingLongTasks() {\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 ) + 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 */\nfunction startTrackingLongAnimationFrames() {\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() ) {\n if (!entry.scripts[0]) {\n continue;\n }\n\n const startTime = msToSec((browserPerformanceTimeOrigin ) + 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\n const duration = msToSec(entry.duration);\n\n const attributes = {\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 */\nfunction startTrackingInteractions() {\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 ) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n const spanOptions = {\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\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() {\n return addClsInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1] ;\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() {\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 ;\n }, true);\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID() {\n return addFidInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin );\n const startTime = msToSec(entry.startTime);\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\nfunction _trackTtfb() {\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\n/** Add performance related spans to a transaction */\nfunction addPerformanceEntries(span, options) {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\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 , timeOrigin);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(span, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n _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(span, entry , entry.name, startTime, duration, timeOrigin);\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 const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n startAndEndSpan(span, fidMark.value, fidMark.value + msToSec(_measurements['fid'].value), {\n name: 'first input delay',\n op: 'ui.action',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n },\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n // TODO: Check if the first condition is still necessary: `onCLS` already only fires once `onFCP` was called.\n if (!('fcp' in _measurements) || !options.recordClsOnPageloadSpan) {\n delete _measurements.cls;\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);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/**\n * Create measure related spans.\n * Exported only for tests.\n */\nfunction _addMeasureSpans(\n span,\n entry,\n startTime,\n duration,\n timeOrigin,\n) {\n const navEntry = getNavigationEntry(false);\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 = {\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 startAndEndSpan(span, measureStartTimestamp, measureEndTimestamp, {\n name: entry.name ,\n op: entry.entryType ,\n attributes,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\nfunction _addNavigationSpans(span, entry, timeOrigin) {\n (['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'] ).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\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n span,\n entry,\n event,\n timeOrigin,\n name = event,\n) {\n const eventEnd = _getEndPropertyNameForNavigationTiming(event) ;\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 },\n });\n}\n\nfunction _getEndPropertyNameForNavigationTiming(event) {\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, entry, timeOrigin) {\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 */\nfunction _addResourceSpans(\n span,\n entry,\n resourceUrl,\n startTime,\n duration,\n timeOrigin,\n) {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n const parsedUrl = parseUrl(resourceUrl);\n\n const attributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.resource.browser.metrics',\n };\n setResourceEntrySizeData(attributes, entry, 'transferSize', 'http.response_transfer_size');\n setResourceEntrySizeData(attributes, entry, 'encodedBodySize', 'http.response_content_length');\n setResourceEntrySizeData(attributes, entry, 'decodedBodySize', 'http.decoded_response_content_length');\n\n // `deliveryType` is experimental and does not exist everywhere\n const deliveryType = (entry ).deliveryType;\n if (deliveryType != null) {\n attributes['http.response_delivery_type'] = deliveryType;\n }\n\n // Types do not reflect this property yet\n const renderBlockingStatus = (entry )\n .renderBlockingStatus;\n if (renderBlockingStatus) {\n attributes['resource.render_blocking_status'] = renderBlockingStatus;\n }\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 const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n startAndEndSpan(span, startTimestamp, endTimestamp, {\n name: resourceUrl.replace(WINDOW.location.origin, ''),\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n attributes,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(span) {\n const navigator = WINDOW.navigator ;\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) {\n if (_lcpEntry) {\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 // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n _clsEntry.sources.forEach((source, index) =>\n span.setAttribute(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n\nfunction setResourceEntrySizeData(\n attributes,\n entry,\n key,\n dataKey,\n) {\n const entryVal = entry[key];\n if (entryVal != null && entryVal < MAX_INT_AS_BYTES) {\n attributes[dataKey] = entryVal;\n }\n}\n\n/**\n * Add ttfb request time information to measurements.\n *\n * ttfb information is added via vendored web vitals library.\n */\nfunction _addTtfbRequestTimeToMeasurements(_measurements) {\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\nexport { _addMeasureSpans, _addResourceSpans, addPerformanceEntries, startTrackingInteractions, startTrackingLongAnimationFrames, startTrackingLongTasks, startTrackingWebVitals };\n//# sourceMappingURL=browserMetrics.js.map\n","import { addHandler, maybeInstrument, triggerHandlers, fill, addNonEnumerableProperty, uuid4 } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\nconst DEBOUNCE_DURATION = 1000;\n\nlet debounceTimerID;\nlet lastCapturedEventType;\nlet lastCapturedEventTargetId;\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 */\nfunction addClickKeypressInstrumentationHandler(handler) {\n const type = 'dom';\n addHandler(type, handler);\n maybeInstrument(type, instrumentDOM);\n}\n\n/** Exported for tests only. */\nfunction instrumentDOM() {\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) => {\n const globalObject = WINDOW ;\n const targetObj = globalObject[target];\n const proto = targetObj && targetObj.prototype;\n\n // eslint-disable-next-line no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener) {\n return function ( type, listener, options) {\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 (e) {\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) {\n return function ( type, listener, options) {\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 (e) {\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) {\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 )._sentryId !== lastCapturedEventTargetId) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return true;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(eventType, target) {\n // We are only interested in filtering `keypress` events for now.\n if (eventType !== 'keypress') {\n return false;\n }\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n */\nfunction makeDOMEventHandler(\n handler,\n globalListener = false,\n) {\n return (event) => {\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 = { 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) {\n try {\n return event.target ;\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n return null;\n }\n}\n\nexport { addClickKeypressInstrumentationHandler, instrumentDOM };\n//# sourceMappingURL=dom.js.map\n","import { addHandler, maybeInstrument, supportsHistory, triggerHandlers, fill } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\nlet lastHref;\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 */\nfunction addHistoryInstrumentationHandler(handler) {\n const type = 'history';\n addHandler(type, handler);\n maybeInstrument(type, instrumentHistory);\n}\n\nfunction instrumentHistory() {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function ( ...args) {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n const handlerData = { from, to };\n triggerHandlers('history', handlerData);\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n function historyReplacementFunction(originalHistoryFunction) {\n return function ( ...args) {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n const handlerData = { from, to };\n triggerHandlers('history', handlerData);\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n\nexport { addHistoryInstrumentationHandler };\n//# sourceMappingURL=history.js.map\n","import { isNativeFunction, logger } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { WINDOW } from './types.js';\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\nconst cachedImplementations = {};\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 */\nfunction getNativeImplementation(\n name,\n) {\n const cached = cachedImplementations[name];\n if (cached) {\n return cached;\n }\n\n let impl = WINDOW[name] ;\n\n // Fast path to avoid DOM I/O\n if (isNativeFunction(impl)) {\n return (cachedImplementations[name] = impl.bind(WINDOW) );\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 && contentWindow[name]) {\n impl = contentWindow[name] ;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n // Could not create sandbox iframe, just use window.xxx\n DEBUG_BUILD && logger.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) );\n}\n\n/** Clear a cached implementation. */\nfunction clearCachedImplementation(name) {\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 */\nfunction fetch(...rest) {\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 */\nfunction setTimeout(...rest) {\n return getNativeImplementation('setTimeout')(...rest);\n}\n\nexport { clearCachedImplementation, fetch, getNativeImplementation, setTimeout };\n//# sourceMappingURL=getNativeImplementation.js.map\n","import { addHandler, maybeInstrument, timestampInSeconds, isString, triggerHandlers } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\nconst SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';\n\n/**\n * Add an instrumentation handler for when an XHR request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addXhrInstrumentationHandler(handler) {\n const type = 'xhr';\n addHandler(type, handler);\n maybeInstrument(type, instrumentXHR);\n}\n\n/** Exported only for tests. */\nfunction instrumentXHR() {\n if (!(WINDOW ).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(originalOpen, xhrOpenThisArg, xhrOpenArgArray) {\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 = parseUrl(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 = () => {\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 (e) {\n /* do nothing */\n }\n\n const handlerData = {\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) {\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,\n setRequestHeaderArgArray,\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, sendArgArray) {\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 = {\n startTimestamp: timestampInSeconds() * 1000,\n xhr: sendThisArg,\n };\n triggerHandlers('xhr', handlerData);\n\n return originalSend.apply(sendThisArg, sendArgArray);\n },\n });\n}\n\nfunction parseUrl(url) {\n if (isString(url)) {\n return url;\n }\n\n try {\n // url can be a string or URL\n // but since URL is not available in IE11, we do not check for it,\n // but simply assume it is an URL and return `toString()` from it (which returns the full URL)\n // If that fails, we just return undefined\n return (url ).toString();\n } catch (e2) {} // eslint-disable-line no-empty\n\n return undefined;\n}\n\nexport { SENTRY_XHR_DATA_KEY, addXhrInstrumentationHandler, instrumentXHR };\n//# sourceMappingURL=xhr.js.map\n","import { browserPerformanceTimeOrigin, getActiveSpan, getRootSpan, spanToJSON, getCurrentScope, htmlTreeAsString, dropUndefinedKeys, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE } from '@sentry/core';\nimport { addInpInstrumentationHandler, addPerformanceInstrumentationHandler, isPerformanceEventTiming } from './instrument.js';\nimport { getBrowserPerformanceAPI, msToSec, startStandaloneWebVitalSpan } from './utils.js';\n\nconst LAST_INTERACTIONS = [];\nconst INTERACTIONS_SPAN_MAP = new Map();\n\n/**\n * Start tracking INP webvital events.\n */\nfunction startTrackingINP() {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n const inpCallback = _trackINP();\n\n return () => {\n inpCallback();\n };\n }\n\n return () => undefined;\n}\n\nconst INP_ENTRY_MAP = {\n click: 'click',\n pointerdown: 'click',\n pointerup: 'click',\n mousedown: 'click',\n mouseup: 'click',\n touchstart: 'click',\n touchend: 'click',\n mouseover: 'hover',\n mouseout: 'hover',\n mouseenter: 'hover',\n mouseleave: 'hover',\n pointerover: 'hover',\n pointerout: 'hover',\n pointerenter: 'hover',\n pointerleave: 'hover',\n dragstart: 'drag',\n dragend: 'drag',\n drag: 'drag',\n dragenter: 'drag',\n dragleave: 'drag',\n dragover: 'drag',\n drop: 'drag',\n keydown: 'press',\n keyup: 'press',\n keypress: 'press',\n input: 'press',\n};\n\n/** Starts tracking the Interaction to Next Paint on the current page. */\nfunction _trackINP() {\n return addInpInstrumentationHandler(({ metric }) => {\n if (metric.value == undefined) {\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 ) + entry.startTime);\n const duration = msToSec(metric.value);\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan ? getRootSpan(activeSpan) : undefined;\n\n // We first try to lookup the span from our INTERACTIONS_SPAN_MAP,\n // where we cache the route per interactionId\n const cachedSpan = interactionId != null ? INTERACTIONS_SPAN_MAP.get(interactionId) : undefined;\n\n const spanToUse = cachedSpan || 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 = htmlTreeAsString(entry.target);\n const attributes = dropUndefinedKeys({\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/**\n * Register a listener to cache route information for INP interactions.\n * TODO(v9): `latestRoute` no longer needs to be passed in and will be removed in v9.\n */\nfunction registerInpInteractionListener(_latestRoute) {\n const handleEntries = ({ entries }) => {\n const activeSpan = getActiveSpan();\n const activeRootSpan = activeSpan && getRootSpan(activeSpan);\n\n entries.forEach(entry => {\n if (!isPerformanceEventTiming(entry) || !activeRootSpan) {\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 // 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() ;\n INTERACTIONS_SPAN_MAP.delete(last);\n }\n\n // We add the interaction to the list of recorded interactions\n // and store the span for this interaction\n LAST_INTERACTIONS.push(interactionId);\n INTERACTIONS_SPAN_MAP.set(interactionId, activeRootSpan);\n });\n };\n\n addPerformanceInstrumentationHandler('event', handleEntries);\n addPerformanceInstrumentationHandler('first-input', handleEntries);\n}\n\nexport { registerInpInteractionListener, startTrackingINP };\n//# sourceMappingURL=inp.js.map\n","import { getNativeImplementation, clearCachedImplementation } from '@sentry-internal/browser-utils';\nimport { createTransport, rejectedSyncPromise } from '@sentry/core';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nfunction makeFetchTransport(\n options,\n nativeFetch = getNativeImplementation('fetch'),\n) {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request) {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. 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 <= 60000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n if (!nativeFetch) {\n clearCachedImplementation('fetch');\n return rejectedSyncPromise('No fetch implementation available');\n }\n\n try {\n // TODO: This may need a `suppressTracing` call in the future when we switch the browser SDK to OTEL\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedImplementation('fetch');\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n\nexport { makeFetchTransport };\n//# sourceMappingURL=fetch.js.map\n","import { createStackParser, UNKNOWN_FUNCTION } from '@sentry/core';\n\n// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename, func, lineno, colno) {\n const frame = {\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// 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 = line => {\n // If the stack line has no function name, we need to parse it differently\n const noFnParts = chromeRegexNoFnName.exec(line) ;\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) ;\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]) ;\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nconst chromeStackLineParser = [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 = line => {\n const parts = geckoREgex.exec(line) ;\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]) ;\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nconst geckoStackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs = line => {\n const parts = winjsRegex.exec(line) ;\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nconst winjsStackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10 = line => {\n const parts = opera10Regex.exec(line) ;\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nconst opera10StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11 = line => {\n const parts = opera11Regex.exec(line) ;\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nconst opera11StackLineParser = [OPERA11_PRIORITY, opera11];\n\nconst defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser];\n\nconst 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, filename) => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? (func.split('@')[0] ) : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n\nexport { chromeStackLineParser, defaultStackLineParsers, defaultStackParser, geckoStackLineParser, opera10StackLineParser, opera11StackLineParser, winjsStackLineParser };\n//# sourceMappingURL=stack-parsers.js.map\n","import { addClickKeypressInstrumentationHandler, addXhrInstrumentationHandler, addHistoryInstrumentationHandler, SENTRY_XHR_DATA_KEY } from '@sentry-internal/browser-utils';\nimport { defineIntegration, addConsoleInstrumentationHandler, addFetchInstrumentationHandler, getClient, addBreadcrumb, getEventDescription, logger, htmlTreeAsString, getComponentName, severityLevelFromString, safeJoin, getBreadcrumbLogLevelFromHttpStatusCode, parseUrl } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\n\n/* eslint-disable max-lines */\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 = {}) => {\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 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}) ;\n\nconst breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction _getSentryBreadcrumbHandler(client) {\n return function addSentryBreadcrumb(event) {\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,\n dom,\n) {\n return function _innerDomBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n let target;\n let componentName;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event ;\n const element = _isEvent(event) ? event.target : event;\n\n target = htmlTreeAsString(element, { keyAttrs, maxStringLength });\n componentName = getComponentName(element);\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n const breadcrumb = {\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) {\n return function _consoleBreadcrumb(handlerData) {\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) {\n return function _xhrBreadcrumb(handlerData) {\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 = {\n method,\n url,\n status_code,\n };\n\n const hint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n const level = getBreadcrumbLogLevelFromHttpStatusCode(status_code);\n\n addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n level,\n },\n hint,\n );\n };\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _getFetchBreadcrumbHandler(client) {\n return function _fetchBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data = handlerData.fetchData;\n const hint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const response = handlerData.response ;\n const data = {\n ...handlerData.fetchData,\n status_code: response && response.status,\n };\n const hint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n const level = getBreadcrumbLogLevelFromHttpStatusCode(data.status_code);\n\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n level,\n },\n hint,\n );\n }\n };\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _getHistoryBreadcrumbHandler(client) {\n return function _historyBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n let from = handlerData.from;\n let to = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = from ? parseUrl(from) : undefined;\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom || !parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n };\n}\n\nfunction _isEvent(event) {\n return !!event && !!(event ).target;\n}\n\nexport { breadcrumbsIntegration };\n//# sourceMappingURL=breadcrumbs.js.map\n","import { defineIntegration, fill, getFunctionName, getOriginalFunction } from '@sentry/core';\nimport { WINDOW, wrap } from '../helpers.js';\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\nconst _browserApiErrorsIntegration = ((options = {}) => {\n const _options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO: This currently only works for the first client this is setup\n // We may want to adjust this to check for client etc.\n setupOnce() {\n if (_options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (_options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (_options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (_options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = _options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n },\n };\n}) ;\n\n/**\n * Wrap timer functions and event targets to catch errors and provide better meta data.\n */\nconst browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration);\n\nfunction _wrapTimeFunction(original) {\n return function ( ...args) {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: false,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\nfunction _wrapRAF(original) {\n return function ( callback) {\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\nfunction _wrapXHR(originalSend) {\n return function ( ...args) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps = ['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 function: prop,\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\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) {\n const globalObject = WINDOW ;\n const targetObj = globalObject[target];\n const proto = targetObj && targetObj.prototype;\n\n // eslint-disable-next-line no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original)\n\n {\n return function ( eventName, fn, options) {\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 function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n });\n }\n } catch (e2) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n wrap(fn, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(proto, 'removeEventListener', function (originalRemoveEventListener)\n\n {\n return function ( eventName, fn, options) {\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 ).__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, fn, options);\n };\n });\n}\n\nfunction isEventListenerObject(obj) {\n return typeof (obj ).handleEvent === 'function';\n}\n\nexport { browserApiErrorsIntegration };\n//# sourceMappingURL=browserapierrors.js.map\n","import { addHistoryInstrumentationHandler } from '@sentry-internal/browser-utils';\nimport { defineIntegration, logger, startSession, captureSession } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\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 */\nconst browserSessionIntegration = defineIntegration(() => {\n return {\n name: 'BrowserSession',\n setupOnce() {\n if (typeof WINDOW.document === 'undefined') {\n DEBUG_BUILD &&\n logger.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\nexport { browserSessionIntegration };\n//# sourceMappingURL=browsersession.js.map\n","import { defineIntegration, addGlobalErrorInstrumentationHandler, getClient, captureEvent, addGlobalUnhandledRejectionInstrumentationHandler, isPrimitive, isString, getLocationHref, UNKNOWN_FUNCTION, logger } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { eventFromUnknownInput } from '../eventbuilder.js';\nimport { shouldIgnoreOnError } from '../helpers.js';\n\nconst INTEGRATION_NAME = 'GlobalHandlers';\n\nconst _globalHandlersIntegration = ((options = {}) => {\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}) ;\n\nconst globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);\n\nfunction _installGlobalOnErrorHandler(client) {\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: 'onerror',\n },\n });\n });\n}\n\nfunction _installGlobalOnUnhandledRejectionHandler(client) {\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: 'onunhandledrejection',\n },\n });\n });\n}\n\nfunction _getUnhandledRejectionError(error) {\n if (isPrimitive(error)) {\n return error;\n }\n\n // dig the object of the rejection out of known event types\n try {\n\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 )) {\n return (error ).reason;\n }\n\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n if ('detail' in (error ) && 'reason' in (error ).detail) {\n return (error ).detail.reason;\n }\n } catch (e2) {} // eslint-disable-line no-empty\n\n return error;\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason) {\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,\n url,\n line,\n column,\n) {\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 = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: UNKNOWN_FUNCTION,\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type) {\n DEBUG_BUILD && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction getOptions() {\n const client = getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return options;\n}\n\nexport { globalHandlersIntegration };\n//# sourceMappingURL=globalhandlers.js.map\n","import { defineIntegration } from '@sentry/core';\nimport { WINDOW } from '../helpers.js';\n\n/**\n * Collects information about HTTP request headers and\n * attaches them to the event.\n */\nconst 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 // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n event.request = request;\n },\n };\n});\n\nexport { httpContextIntegration };\n//# sourceMappingURL=httpcontext.js.map\n","import { defineIntegration, applyAggregateErrorsToEvent } from '@sentry/core';\nimport { exceptionFromError } from '../eventbuilder.js';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options = {}) => {\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 options.maxValueLength,\n key,\n limit,\n event,\n hint,\n );\n },\n };\n}) ;\n\n/**\n * Aggregrate linked errors in an event.\n */\nconst linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n\nexport { linkedErrorsIntegration };\n//# sourceMappingURL=linkederrors.js.map\n","import { inboundFiltersIntegration, functionToStringIntegration, dedupeIntegration, consoleSandbox, supportsFetch, logger, stackParserFromStackParserOptions, getIntegrationsToSetup, initAndBind, getCurrentScope, lastEventId, getReportDialogEndpoint, getClient } from '@sentry/core';\nimport { BrowserClient } from './client.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { WINDOW } from './helpers.js';\nimport { breadcrumbsIntegration } from './integrations/breadcrumbs.js';\nimport { browserApiErrorsIntegration } from './integrations/browserapierrors.js';\nimport { browserSessionIntegration } from './integrations/browsersession.js';\nimport { globalHandlersIntegration } from './integrations/globalhandlers.js';\nimport { httpContextIntegration } from './integrations/httpcontext.js';\nimport { linkedErrorsIntegration } from './integrations/linkederrors.js';\nimport { defaultStackParser } from './stack-parsers.js';\nimport { makeFetchTransport } from './transports/fetch.js';\n\n/** Get the default integrations for the browser SDK. */\nfunction getDefaultIntegrations(options) {\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 const integrations = [\n inboundFiltersIntegration(),\n functionToStringIntegration(),\n browserApiErrorsIntegration(),\n breadcrumbsIntegration(),\n globalHandlersIntegration(),\n linkedErrorsIntegration(),\n dedupeIntegration(),\n httpContextIntegration(),\n ];\n\n // eslint-disable-next-line deprecation/deprecation\n if (options.autoSessionTracking !== false) {\n integrations.push(browserSessionIntegration());\n }\n\n return integrations;\n}\n\nfunction applyDefaultOptions(optionsArg = {}) {\n const defaultOptions = {\n defaultIntegrations: getDefaultIntegrations(optionsArg),\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 && WINDOW.SENTRY_RELEASE.id // This supports the variable that sentry-webpack-plugin injects\n ? WINDOW.SENTRY_RELEASE.id\n : undefined,\n autoSessionTracking: true,\n sendClientReports: true,\n };\n\n // TODO: Instead of dropping just `defaultIntegrations`, we should simply\n // call `dropUndefinedKeys` on the entire `optionsArg`.\n // However, for this to work we need to adjust the `hasTracingEnabled()` logic\n // first as it differentiates between `undefined` and the key not being in the object.\n if (optionsArg.defaultIntegrations == null) {\n delete optionsArg.defaultIntegrations;\n }\n\n return { ...defaultOptions, ...optionsArg };\n}\n\nfunction shouldShowBrowserExtensionError() {\n const windowWithMaybeExtension =\n typeof WINDOW.window !== 'undefined' && (WINDOW );\n if (!windowWithMaybeExtension) {\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 extensionKey = windowWithMaybeExtension.chrome ? 'chrome' : 'browser';\n const extensionObject = windowWithMaybeExtension[extensionKey];\n\n const runtimeId = extensionObject && extensionObject.runtime && extensionObject.runtime.id;\n const href = (WINDOW.location && WINDOW.location.href) || '';\n\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 !!runtimeId && WINDOW === WINDOW.top && extensionProtocols.some(protocol => href.startsWith(`${protocol}//`));\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 const isNWjs = typeof windowWithMaybeExtension.nw !== 'undefined';\n\n return !!runtimeId && !isDedicatedExtensionPage && !isNWjs;\n}\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\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 */\nfunction init(browserOptions = {}) {\n const options = applyDefaultOptions(browserOptions);\n\n if (!options.skipBrowserExtensionCheck && shouldShowBrowserExtensionError()) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(\n '[Sentry] You cannot run Sentry this way in a browser extension, check: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/',\n );\n });\n return;\n }\n\n if (DEBUG_BUILD) {\n if (!supportsFetch()) {\n logger.warn(\n 'No Fetch API detected. The Sentry SDK requires a Fetch API compatible environment to send events. Please add a Fetch API polyfill.',\n );\n }\n }\n const clientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || makeFetchTransport,\n };\n\n return initAndBind(BrowserClient, clientOptions);\n}\n\n/**\n * All properties the report dialog supports\n */\n\n/**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\nfunction showReportDialog(options = {}) {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n DEBUG_BUILD && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n const scope = getCurrentScope();\n const client = scope.getClient();\n const dsn = client && client.getDsn();\n\n if (!dsn) {\n DEBUG_BUILD && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n const eventId = lastEventId();\n if (eventId) {\n options.eventId = eventId;\n }\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.crossOrigin = 'anonymous';\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const { onClose } = options;\n if (onClose) {\n const reportDialogClosedMessageHandler = (event) => {\n if (event.data === '__sentry_reportdialog_closed__') {\n try {\n onClose();\n } finally {\n WINDOW.removeEventListener('message', reportDialogClosedMessageHandler);\n }\n }\n };\n WINDOW.addEventListener('message', reportDialogClosedMessageHandler);\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n DEBUG_BUILD && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nfunction forceLoad() {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nfunction onLoad(callback) {\n callback();\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n *\n * @deprecated Use `captureFeedback` instead.\n */\nfunction captureUserFeedback(feedback) {\n const client = getClient();\n if (client) {\n // eslint-disable-next-line deprecation/deprecation\n client.captureUserFeedback(feedback);\n }\n}\n\nexport { captureUserFeedback, forceLoad, getDefaultIntegrations, init, onLoad, showReportDialog };\n//# sourceMappingURL=sdk.js.map\n","import { _nullishCoalesce, _optionalChain } from '@sentry/core';\nimport { GLOBAL_OBJ, normalize, fill, htmlTreeAsString, browserPerformanceTimeOrigin, logger as logger$1, severityLevelFromString, captureException, addBreadcrumb, uuid4, getClient, getLocationHref, getCurrentScope, getActiveSpan, getDynamicSamplingContextFromSpan, isSentryRequestUrl, dropUndefinedKeys, stringMatchesSomePattern, addEventProcessor, createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader, prepareEvent, getIsolationScope, resolvedSyncPromise, updateRateLimits, isRateLimited, setContext, getRootSpan, spanToJSON, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, isBrowser, parseSampleRate, consoleSandbox } from '@sentry/core';\nimport { setTimeout as setTimeout$3, addPerformanceInstrumentationHandler, addLcpInstrumentationHandler, addClsInstrumentationHandler, addFidInstrumentationHandler, addInpInstrumentationHandler, SENTRY_XHR_DATA_KEY, addClickKeypressInstrumentationHandler, addHistoryInstrumentationHandler } from '@sentry-internal/browser-utils';\n\n// exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`\n// prevents the browser package from being bundled in the CDN bundle, and avoids a\n// circular dependency between the browser and replay packages should `@sentry/browser` import\n// from `@sentry/replay` in the future\nconst WINDOW = GLOBAL_OBJ ;\n\nconst REPLAY_SESSION_KEY = 'sentryReplaySession';\nconst REPLAY_EVENT_NAME = 'replay_event';\nconst UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';\n\n// The idle limit for a session after which recording is paused.\nconst SESSION_IDLE_PAUSE_DURATION = 300000; // 5 minutes in ms\n\n// The idle limit for a session after which the session expires.\nconst SESSION_IDLE_EXPIRE_DURATION = 900000; // 15 minutes in ms\n\n/** Default flush delays */\nconst DEFAULT_FLUSH_MIN_DELAY = 5000;\n// XXX: Temp fix for our debounce logic where `maxWait` would never occur if it\n// was the same as `wait`\nconst DEFAULT_FLUSH_MAX_DELAY = 5500;\n\n/* How long to wait for error checkouts */\nconst BUFFER_CHECKOUT_TIME = 60000;\n\nconst RETRY_BASE_INTERVAL = 5000;\nconst RETRY_MAX_COUNT = 3;\n\n/* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */\nconst NETWORK_BODY_MAX_SIZE = 150000;\n\n/* The max size of a single console arg that is captured. Any arg larger than this will be truncated. */\nconst CONSOLE_ARG_MAX_SIZE = 5000;\n\n/* Min. time to wait before we consider something a slow click. */\nconst SLOW_CLICK_THRESHOLD = 3000;\n/* For scroll actions after a click, we only look for a very short time period to detect programmatic scrolling. */\nconst 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). */\nconst REPLAY_MAX_EVENT_BUFFER_SIZE = 20000000; // ~20MB\n\n/** Replays must be min. 5s long before we send them. */\nconst MIN_REPLAY_DURATION = 4999;\n/* The max. allowed value that the minReplayDuration can be set to. */\nconst MIN_REPLAY_DURATION_LIMIT = 15000;\n\n/** The max. length of a replay. */\nconst MAX_REPLAY_DURATION = 3600000; // 60 minutes in ms;\n\nfunction _nullishCoalesce$1(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }function _optionalChain$5(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var NodeType$3;\n(function (NodeType) {\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n})(NodeType$3 || (NodeType$3 = {}));\n\nfunction isElement$1(n) {\n return n.nodeType === n.ELEMENT_NODE;\n}\nfunction isShadowRoot(n) {\n const host = _optionalChain$5([n, 'optionalAccess', _ => _.host]);\n return Boolean(_optionalChain$5([host, 'optionalAccess', _2 => _2.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;') &&\n !cssText.includes(' -webkit-background-clip: text;')) {\n cssText = cssText.replace(/\\sbackground-clip:\\s*text;/g, ' -webkit-background-clip: text; background-clip: text;');\n }\n return cssText;\n}\nfunction escapeImportStatement(rule) {\n const { cssText } = rule;\n if (cssText.split('\"').length < 3)\n return cssText;\n const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\n if (rule.layerName === '') {\n statement.push(`layer`);\n }\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\n ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join(''))\n : null;\n }\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 =\n stringifyStylesheet(rule.styleSheet) ||\n escapeImportStatement(rule);\n }\n catch (error) {\n }\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 this.idNodeMap = new Map();\n this.nodeMetaMap = new WeakMap();\n }\n getId(n) {\n if (!n)\n return -1;\n const id = _optionalChain$5([this, 'access', _3 => _3.getMeta, 'call', _4 => _4(n), 'optionalAccess', _5 => _5.id]);\n return _nullishCoalesce$1(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 removeNodeFromMap(n) {\n const id = this.getId(n);\n this.idNodeMap.delete(id);\n if (n.childNodes) {\n n.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(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)\n this.nodeMetaMap.set(n, meta);\n }\n this.idNodeMap.set(id, n);\n }\n reset() {\n this.idNodeMap = new Map();\n this.nodeMetaMap = new WeakMap();\n }\n}\nfunction createMirror() {\n return new Mirror();\n}\nfunction shouldMaskInput({ maskInputOptions, tagName, type, }) {\n if (tagName === 'OPTION') {\n tagName = 'SELECT';\n }\n return Boolean(maskInputOptions[tagName.toLowerCase()] ||\n (type && maskInputOptions[type]) ||\n type === 'password' ||\n (tagName === 'INPUT' && !type && maskInputOptions['text']));\n}\nfunction maskInputValue({ isMasked, element, value, maskInputFn, }) {\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)\n 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\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\n : getImageData;\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\n if (pixelBuffer.some((pixel) => pixel !== 0))\n return false;\n }\n }\n return true;\n}\nfunction getInputType(element) {\n const type = element.type;\n return element.hasAttribute('data-rr-is-password')\n ? 'password'\n : type\n ?\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, _nullishCoalesce$1(baseURL, () => ( window.location.href)));\n }\n catch (err) {\n return null;\n }\n const regex = /\\.([0-9a-z]+)(?:$)/i;\n const match = url.pathname.match(regex);\n return _nullishCoalesce$1(_optionalChain$5([match, 'optionalAccess', _6 => _6[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 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 =\n contentWindow[name];\n }\n document.head.removeChild(sandbox);\n }\n catch (e) {\n }\n }\n return (cachedImplementations$1[name] = impl.bind(window));\n}\nfunction setTimeout$2(...rest) {\n return getImplementation$1('setTimeout')(...rest);\n}\nfunction clearTimeout$2(...rest) {\n return getImplementation$1('clearTimeout')(...rest);\n}\nfunction getIframeContentDocument(iframe) {\n try {\n return iframe.contentDocument;\n }\n catch (e) {\n }\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 }\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 absoluteToStylesheet(cssText, href) {\n return (cssText || '').replace(URL_IN_CSS_REF, (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 }\n else if (part === '..') {\n stack.pop();\n }\n else {\n stack.push(part);\n }\n }\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\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 }\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 }\n else if (!inParens) {\n if (c === ',') {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (c === '(') {\n inParens = true;\n }\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 = 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 }\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) {\n if (!value) {\n return value;\n }\n if (name === 'src' ||\n (name === 'href' && !(tagName === 'use' && value[0] === '#'))) {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'xlink:href' && value[0] !== '#') {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'background' &&\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'srcset') {\n return getAbsoluteSrcsetString(doc, value);\n }\n else if (name === 'style') {\n return absoluteToStylesheet(value, getHref(doc));\n }\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 }\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 }\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 distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\n if (!node)\n return -1;\n if (node.nodeType !== node.ELEMENT_NODE)\n return -1;\n if (distance > limit)\n return -1;\n if (matchPredicate(node))\n 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)\n return false;\n try {\n if (className) {\n if (typeof className === 'string') {\n if (el.matches(`.${className}`))\n return true;\n }\n else if (elementClassMatchesRegex(el, className)) {\n return true;\n }\n }\n if (selector && el.matches(selector))\n return true;\n return false;\n }\n catch (e2) {\n return false;\n }\n };\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\n try {\n const el = node.nodeType === node.ELEMENT_NODE\n ? node\n : node.parentElement;\n if (el === null)\n 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(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector));\n if (unmaskDistance < 0) {\n return true;\n }\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity);\n }\n else {\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector));\n if (maskDistance < 0) {\n return false;\n }\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity);\n }\n return maskDistance >= 0\n ? unmaskDistance >= 0\n ? maskDistance <= unmaskDistance\n : true\n : unmaskDistance >= 0\n ? false\n : !!maskAllText;\n }\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 }\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$2(timer);\n fired = true;\n listener();\n });\n return;\n }\n const blankUrl = 'about:blank';\n if (win.location.href !== blankUrl ||\n iframeEl.src === blankUrl ||\n 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 }\n catch (error) {\n return;\n }\n if (styleSheetLoaded)\n return;\n const timer = setTimeout$2(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, styleSheetLoadTimeout);\n link.addEventListener('load', () => {\n clearTimeout$2(timer);\n fired = true;\n listener();\n });\n}\nfunction serializeNode(n, options) {\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, } = 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$3.Document,\n childNodes: [],\n compatMode: n.compatMode,\n };\n }\n else {\n return {\n type: NodeType$3.Document,\n childNodes: [],\n };\n }\n case n.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType$3.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 });\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$3.CDATA,\n textContent: '',\n rootId,\n };\n case n.COMMENT_NODE:\n return {\n type: NodeType$3.Comment,\n textContent: n.textContent || '',\n rootId,\n };\n default:\n return false;\n }\n}\nfunction getRootId(doc, mirror) {\n if (!mirror.hasNode(doc))\n return undefined;\n const docId = mirror.getId(doc);\n return docId === 1 ? undefined : docId;\n}\nfunction serializeTextNode(n, options) {\n const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId, } = options;\n const parentTagName = n.parentNode && n.parentNode.tagName;\n let textContent = n.textContent;\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\n const isTextarea = parentTagName === 'TEXTAREA' ? true : undefined;\n if (isStyle && textContent) {\n try {\n if (n.nextSibling || n.previousSibling) {\n }\n else if (_optionalChain$5([n, 'access', _7 => _7.parentNode, 'access', _8 => _8.sheet, 'optionalAccess', _9 => _9.cssRules])) {\n textContent = stringifyStylesheet(n.parentNode.sheet);\n }\n }\n catch (err) {\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\n }\n textContent = absoluteToStylesheet(textContent, getHref(options.doc));\n }\n if (isScript) {\n textContent = 'SCRIPT_PLACEHOLDER';\n }\n const forceMask = needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText);\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\n textContent = maskTextFn\n ? maskTextFn(textContent, n.parentElement)\n : textContent.replace(/[\\S]/g, '*');\n }\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\n textContent = maskInputFn\n ? maskInputFn(textContent, n.parentNode)\n : 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, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked),\n element: n,\n value: textContent,\n maskInputFn,\n });\n }\n return {\n type: NodeType$3.Text,\n textContent: textContent || '',\n isStyle,\n rootId,\n };\n}\nfunction serializeElementNode(n, options) {\n const { doc, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, } = options;\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\n const tagName = getValidTagName(n);\n let attributes = {};\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 attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value, n, maskAttributeFn);\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 attributes.rel = null;\n attributes.href = null;\n attributes.crossorigin = null;\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\n }\n }\n if (tagName === 'style' &&\n n.sheet &&\n !(n.innerText || n.textContent || '').trim().length) {\n const cssText = stringifyStylesheet(n.sheet);\n if (cssText) {\n attributes._cssText = absoluteToStylesheet(cssText, getHref(doc));\n }\n }\n if (tagName === 'input' ||\n tagName === 'textarea' ||\n tagName === 'select' ||\n 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(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({\n type,\n tagName: toUpperCase(tagName),\n maskInputOptions,\n }));\n attributes.value = maskInputValue({\n isMasked: forceMask,\n element: el,\n value,\n maskInputFn,\n });\n }\n if (checked) {\n attributes.checked = checked;\n }\n }\n if (tagName === 'option') {\n if (n.selected && !maskInputOptions['select']) {\n attributes.selected = true;\n }\n else {\n delete attributes.selected;\n }\n }\n if (tagName === 'canvas' && recordCanvas) {\n if (n.__context === '2d') {\n if (!is2DCanvasBlank(n)) {\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n }\n else if (!('__context' in n)) {\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n const blankCanvas = doc.createElement('canvas');\n blankCanvas.width = n.width;\n blankCanvas.height = n.height;\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes.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 attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, 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\n image.addEventListener('load', recordInlineImage);\n return;\n }\n else {\n console.warn(`Cannot inline img src=${imageSrc}! Error: ${err}`);\n }\n }\n if (image.crossOrigin === 'anonymous') {\n priorCrossOrigin\n ? (attributes.crossOrigin = priorCrossOrigin)\n : image.removeAttribute('crossorigin');\n }\n };\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else\n image.addEventListener('load', recordInlineImage);\n }\n if (tagName === 'audio' || tagName === 'video') {\n attributes.rr_mediaState = n.paused\n ? 'paused'\n : 'played';\n attributes.rr_mediaCurrentTime = n.currentTime;\n }\n if (!newlyAddedElement) {\n if (n.scrollLeft) {\n attributes.rr_scrollLeft = n.scrollLeft;\n }\n if (n.scrollTop) {\n attributes.rr_scrollTop = n.scrollTop;\n }\n }\n if (needBlock) {\n const { width, height } = n.getBoundingClientRect();\n attributes = {\n class: attributes.class,\n rr_width: `${width}px`,\n rr_height: `${height}px`,\n };\n }\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\n if (!needBlock && !getIframeContentDocument(n)) {\n attributes.rr_src = attributes.src;\n }\n delete attributes.src;\n }\n let isCustomElement;\n try {\n if (customElements.get(tagName))\n isCustomElement = true;\n }\n catch (e) {\n }\n return {\n type: NodeType$3.Element,\n tagName,\n attributes,\n childNodes: [],\n isSVG: isSVGElement(n) || undefined,\n needBlock,\n rootId,\n isCustom: isCustomElement,\n };\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === undefined || maybeAttr === null) {\n return '';\n }\n else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType$3.Comment) {\n return true;\n }\n else if (sn.type === NodeType$3.Element) {\n if (slimDOMOptions.script &&\n (sn.tagName === 'script' ||\n (sn.tagName === 'link' &&\n (sn.attributes.rel === 'preload' ||\n sn.attributes.rel === 'modulepreload')) ||\n (sn.tagName === 'link' &&\n sn.attributes.rel === 'prefetch' &&\n typeof sn.attributes.href === 'string' &&\n extractFileExtension(sn.attributes.href) === 'js'))) {\n return true;\n }\n else if (slimDOMOptions.headFavicon &&\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\n (sn.tagName === 'meta' &&\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\n lowerIfExists(sn.attributes.name) === 'application-name' ||\n lowerIfExists(sn.attributes.rel) === 'icon' ||\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\n return true;\n }\n else if (sn.tagName === 'meta') {\n if (slimDOMOptions.headMetaDescKeywords &&\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n }\n else if (slimDOMOptions.headMetaSocial &&\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\n return true;\n }\n else if (slimDOMOptions.headMetaRobots &&\n (lowerIfExists(sn.attributes.name) === 'robots' ||\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\n return true;\n }\n else if (slimDOMOptions.headMetaHttpEquiv &&\n sn.attributes['http-equiv'] !== undefined) {\n return true;\n }\n else if (slimDOMOptions.headMetaAuthorship &&\n (lowerIfExists(sn.attributes.name) === 'author' ||\n lowerIfExists(sn.attributes.name) === 'generator' ||\n lowerIfExists(sn.attributes.name) === 'framework' ||\n lowerIfExists(sn.attributes.name) === 'publisher' ||\n lowerIfExists(sn.attributes.name) === 'progid' ||\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n }\n else if (slimDOMOptions.headMetaVerification &&\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\n lowerIfExists(sn.attributes.name) === 'verification' ||\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\n return true;\n }\n }\n }\n return false;\n}\nfunction serializeNodeWithId(n, options) {\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, onStylesheetLoad, stylesheetLoadTimeout = 5000, keepIframeSrcFn = () => false, newlyAddedElement = false, } = options;\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 });\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 }\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\n (!preserveWhiteSpace &&\n _serializedNode.type === NodeType$3.Text &&\n !_serializedNode.isStyle &&\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\n id = IGNORED_NODE;\n }\n else {\n id = genId();\n }\n const serializedNode = Object.assign(_serializedNode, { id });\n mirror.add(n, serializedNode);\n if (id === IGNORED_NODE) {\n return null;\n }\n if (onSerialize) {\n onSerialize(n);\n }\n let recordChild = !skipChild;\n if (serializedNode.type === NodeType$3.Element) {\n recordChild = recordChild && !serializedNode.needBlock;\n delete serializedNode.needBlock;\n const shadowRoot = n.shadowRoot;\n if (shadowRoot && isNativeShadowDom(shadowRoot))\n serializedNode.isShadowHost = true;\n }\n if ((serializedNode.type === NodeType$3.Document ||\n serializedNode.type === NodeType$3.Element) &&\n recordChild) {\n if (slimDOMOptions.headWhitespace &&\n serializedNode.type === NodeType$3.Element &&\n serializedNode.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 onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n };\n for (const childN of Array.from(n.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n if (isElement$1(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) &&\n (serializedChildNode.isShadow = true);\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n if (n.parentNode &&\n isShadowRoot(n.parentNode) &&\n isNativeShadowDom(n.parentNode)) {\n serializedNode.isShadow = true;\n }\n if (serializedNode.type === NodeType$3.Element &&\n serializedNode.tagName === 'iframe') {\n onceIframeLoaded(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 });\n if (serializedIframeNode) {\n onIframeLoad(n, serializedIframeNode);\n }\n }\n }, iframeLoadTimeout);\n }\n if (serializedNode.type === NodeType$3.Element &&\n serializedNode.tagName === 'link' &&\n typeof serializedNode.attributes.rel === 'string' &&\n (serializedNode.attributes.rel === 'stylesheet' ||\n (serializedNode.attributes.rel === 'preload' &&\n typeof serializedNode.attributes.href === 'string' &&\n extractFileExtension(serializedNode.attributes.href) === 'css'))) {\n onceStylesheetLoaded(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 });\n if (serializedLinkNode) {\n onStylesheetLoad(n, serializedLinkNode);\n }\n }\n }, stylesheetLoadTimeout);\n }\n return serializedNode;\n}\nfunction snapshot(n, options) {\n const { mirror = new Mirror(), blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\n const maskInputOptions = maskAllInputs === true\n ? {\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 }\n : maskAllInputs === false\n ? {}\n : maskAllInputs;\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\n ?\n {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaDescKeywords: slimDOM === 'all',\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaAuthorship: true,\n headMetaVerification: true,\n }\n : slimDOM === false\n ? {}\n : 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 onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n newlyAddedElement: false,\n });\n}\n\nfunction _optionalChain$4(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }\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,' +\n '\\r\\n' +\n 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\n '\\r\\n' +\n 'or 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$1(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$1(timeout);\n timeout = null;\n }\n previous = now;\n func.apply(context, args);\n }\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(target, key, isRevoked\n ? d\n : {\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 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 }\n catch (e2) {\n return () => {\n };\n }\n}\nlet nowTimestamp = Date.now;\nif (!(/[1-9][0-9]{12}/.test(Date.now().toString()))) {\n nowTimestamp = () => new Date().getTime();\n}\nfunction getWindowScroll(win) {\n const doc = win.document;\n return {\n left: doc.scrollingElement\n ? doc.scrollingElement.scrollLeft\n : win.pageXOffset !== undefined\n ? win.pageXOffset\n : _optionalChain$4([doc, 'optionalAccess', _ => _.documentElement, 'access', _2 => _2.scrollLeft]) ||\n _optionalChain$4([doc, 'optionalAccess', _3 => _3.body, 'optionalAccess', _4 => _4.parentElement, 'optionalAccess', _5 => _5.scrollLeft]) ||\n _optionalChain$4([doc, 'optionalAccess', _6 => _6.body, 'optionalAccess', _7 => _7.scrollLeft]) ||\n 0,\n top: doc.scrollingElement\n ? doc.scrollingElement.scrollTop\n : win.pageYOffset !== undefined\n ? win.pageYOffset\n : _optionalChain$4([doc, 'optionalAccess', _8 => _8.documentElement, 'access', _9 => _9.scrollTop]) ||\n _optionalChain$4([doc, 'optionalAccess', _10 => _10.body, 'optionalAccess', _11 => _11.parentElement, 'optionalAccess', _12 => _12.scrollTop]) ||\n _optionalChain$4([doc, 'optionalAccess', _13 => _13.body, 'optionalAccess', _14 => _14.scrollTop]) ||\n 0,\n };\n}\nfunction getWindowHeight() {\n return (window.innerHeight ||\n (document.documentElement && document.documentElement.clientHeight) ||\n (document.body && document.body.clientHeight));\n}\nfunction getWindowWidth() {\n return (window.innerWidth ||\n (document.documentElement && document.documentElement.clientWidth) ||\n (document.body && document.body.clientWidth));\n}\nfunction closestElementOfNode(node) {\n if (!node) {\n return null;\n }\n const el = node.nodeType === node.ELEMENT_NODE\n ? node\n : node.parentElement;\n return el;\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(el, createMatchPredicate(null, unblockSelector));\n }\n if (blockDistance > -1 && unblockDistance < 0) {\n return true;\n }\n return blockDistance < unblockDistance;\n}\nfunction isSerialized(n, mirror) {\n return mirror.getId(n) !== -1;\n}\nfunction isIgnored(n, mirror) {\n return mirror.getId(n) === IGNORED_NODE;\n}\nfunction isAncestorRemoved(target, mirror) {\n if (isShadowRoot(target)) {\n return false;\n }\n const id = mirror.getId(target);\n if (!mirror.has(id)) {\n return true;\n }\n if (target.parentNode &&\n target.parentNode.nodeType === target.DOCUMENT_NODE) {\n return false;\n }\n if (!target.parentNode) {\n return true;\n }\n return isAncestorRemoved(target.parentNode, mirror);\n}\nfunction legacy_isTouchEvent(event) {\n return Boolean(event.changedTouches);\n}\nfunction polyfill(win = window) {\n if ('NodeList' in win && !win.NodeList.prototype.forEach) {\n win.NodeList.prototype.forEach = Array.prototype\n .forEach;\n }\n if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\n win.DOMTokenList.prototype.forEach = Array.prototype\n .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 isSerializedIframe(n, mirror) {\n return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));\n}\nfunction isSerializedStylesheet(n, mirror) {\n return Boolean(n.nodeName === 'LINK' &&\n n.nodeType === n.ELEMENT_NODE &&\n n.getAttribute &&\n n.getAttribute('rel') === 'stylesheet' &&\n mirror.getMeta(n));\n}\nfunction hasShadowRoot(n) {\n return Boolean(_optionalChain$4([n, 'optionalAccess', _18 => _18.shadowRoot]));\n}\nclass StyleSheetMirror {\n constructor() {\n this.id = 1;\n this.styleIDMap = new WeakMap();\n this.idStyleMap = new Map();\n }\n getId(stylesheet) {\n return _nullishCoalesce(this.styleIDMap.get(stylesheet), () => ( -1));\n }\n has(stylesheet) {\n return this.styleIDMap.has(stylesheet);\n }\n add(stylesheet, id) {\n if (this.has(stylesheet))\n return this.getId(stylesheet);\n let newId;\n if (id === undefined) {\n newId = this.id++;\n }\n else\n 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 = new WeakMap();\n this.idStyleMap = new Map();\n this.id = 1;\n }\n generateId() {\n return this.id++;\n }\n}\nfunction getShadowHost(n) {\n let shadowHost = null;\n if (_optionalChain$4([n, 'access', _19 => _19.getRootNode, 'optionalCall', _20 => _20(), 'optionalAccess', _21 => _21.nodeType]) === Node.DOCUMENT_FRAGMENT_NODE &&\n n.getRootNode().host)\n shadowHost = n.getRootNode().host;\n return shadowHost;\n}\nfunction getRootShadowHost(n) {\n let rootShadowHost = n;\n let shadowHost;\n while ((shadowHost = getShadowHost(rootShadowHost)))\n rootShadowHost = shadowHost;\n return rootShadowHost;\n}\nfunction shadowHostInDom(n) {\n const doc = n.ownerDocument;\n if (!doc)\n return false;\n const shadowHost = getRootShadowHost(n);\n return doc.contains(shadowHost);\n}\nfunction inDom(n) {\n const doc = n.ownerDocument;\n if (!doc)\n return false;\n return doc.contains(n) || shadowHostInDom(n);\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 =\n contentWindow[name];\n }\n document.head.removeChild(sandbox);\n }\n catch (e) {\n }\n }\n return (cachedImplementations[name] = impl.bind(window));\n}\nfunction onRequestAnimationFrame(...rest) {\n return getImplementation('requestAnimationFrame')(...rest);\n}\nfunction setTimeout$1(...rest) {\n return getImplementation('setTimeout')(...rest);\n}\nfunction clearTimeout$1(...rest) {\n return getImplementation('clearTimeout')(...rest);\n}\n\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 || {});\n\nvar NodeType$1;\n(function (NodeType) {\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n})(NodeType$1 || (NodeType$1 = {}));\nvar NodeType$2;\n(function (NodeType) {\n NodeType[NodeType[\"PLACEHOLDER\"] = 0] = \"PLACEHOLDER\";\n NodeType[NodeType[\"ELEMENT_NODE\"] = 1] = \"ELEMENT_NODE\";\n NodeType[NodeType[\"ATTRIBUTE_NODE\"] = 2] = \"ATTRIBUTE_NODE\";\n NodeType[NodeType[\"TEXT_NODE\"] = 3] = \"TEXT_NODE\";\n NodeType[NodeType[\"CDATA_SECTION_NODE\"] = 4] = \"CDATA_SECTION_NODE\";\n NodeType[NodeType[\"ENTITY_REFERENCE_NODE\"] = 5] = \"ENTITY_REFERENCE_NODE\";\n NodeType[NodeType[\"ENTITY_NODE\"] = 6] = \"ENTITY_NODE\";\n NodeType[NodeType[\"PROCESSING_INSTRUCTION_NODE\"] = 7] = \"PROCESSING_INSTRUCTION_NODE\";\n NodeType[NodeType[\"COMMENT_NODE\"] = 8] = \"COMMENT_NODE\";\n NodeType[NodeType[\"DOCUMENT_NODE\"] = 9] = \"DOCUMENT_NODE\";\n NodeType[NodeType[\"DOCUMENT_TYPE_NODE\"] = 10] = \"DOCUMENT_TYPE_NODE\";\n NodeType[NodeType[\"DOCUMENT_FRAGMENT_NODE\"] = 11] = \"DOCUMENT_FRAGMENT_NODE\";\n})(NodeType$2 || (NodeType$2 = {}));\n\nfunction getIFrameContentDocument(iframe) {\n try {\n return iframe.contentDocument;\n }\n catch (e) {\n }\n}\nfunction getIFrameContentWindow(iframe) {\n try {\n return iframe.contentWindow;\n }\n catch (e) {\n }\n}\n\nfunction _optionalChain$3(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }\nfunction isNodeInLinkedList(n) {\n return '__ln' in n;\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 = _optionalChain$3([current, 'optionalAccess', _ => _.next]) || null;\n }\n return current;\n }\n addNode(n) {\n const node = {\n value: n,\n previous: null,\n next: null,\n };\n n.__ln = node;\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\n const current = n.previousSibling.__ln.next;\n node.next = current;\n node.previous = n.previousSibling.__ln;\n n.previousSibling.__ln.next = node;\n if (current) {\n current.previous = node;\n }\n }\n else if (n.nextSibling &&\n isNodeInLinkedList(n.nextSibling) &&\n n.nextSibling.__ln.previous) {\n const current = n.nextSibling.__ln.previous;\n node.previous = current;\n node.next = n.nextSibling.__ln;\n n.nextSibling.__ln.previous = node;\n if (current) {\n current.next = node;\n }\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(n) {\n const current = n.__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 }\n else {\n this.tail = null;\n }\n }\n else {\n current.previous.next = current.next;\n if (current.next) {\n current.next.previous = current.previous;\n }\n else {\n this.tail = current.previous;\n }\n }\n if (n.__ln) {\n delete n.__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 = new WeakMap();\n this.removes = [];\n this.mapRemoves = [];\n this.movedMap = {};\n this.addedSet = new Set();\n this.movedSet = new Set();\n this.droppedSet = 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 = new Set();\n const addList = new DoubleLinkedList();\n const getNextId = (n) => {\n let ns = n;\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 = (n) => {\n if (!n.parentNode || !inDom(n)) {\n return;\n }\n const parentId = isShadowRoot(n.parentNode)\n ? this.mirror.getId(getShadowHost(n))\n : this.mirror.getId(n.parentNode);\n const nextId = getNextId(n);\n if (parentId === -1 || nextId === -1) {\n return addList.addNode(n);\n }\n const sn = serializeNodeWithId(n, {\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) &&\n !isBlocked(currentN, this.blockClass, this.blockSelector, this.unblockSelector, false)) {\n this.iframeManager.addIframe(currentN);\n }\n if (isSerializedStylesheet(currentN, this.mirror)) {\n this.stylesheetManager.trackLinkElement(currentN);\n }\n if (hasShadowRoot(n)) {\n this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n if (isBlocked(iframe, this.blockClass, this.blockSelector, this.unblockSelector, false)) {\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 });\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 n of this.movedSet) {\n if (isParentRemoved(this.removes, n, this.mirror) &&\n !this.movedSet.has(n.parentNode)) {\n continue;\n }\n pushAdd(n);\n }\n for (const n of this.addedSet) {\n if (!isAncestorInSet(this.droppedSet, n) &&\n !isParentRemoved(this.removes, n, this.mirror)) {\n pushAdd(n);\n }\n else if (isAncestorInSet(this.movedSet, n)) {\n pushAdd(n);\n }\n else {\n this.droppedSet.add(n);\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)\n continue;\n else if (parentId !== -1) {\n node = _node;\n break;\n }\n else {\n const unhandledNode = _node.value;\n if (unhandledNode.parentNode &&\n unhandledNode.parentNode.nodeType ===\n Node.DOCUMENT_FRAGMENT_NODE) {\n const shadowHost = unhandledNode.parentNode\n .host;\n const parentId = this.mirror.getId(shadowHost);\n if (parentId !== -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\n .map((text) => ({\n id: this.mirror.getId(text.node),\n value: text.value,\n }))\n .filter((text) => !addedIds.has(text.id))\n .filter((text) => this.mirror.has(text.id)),\n attributes: this.attributes\n .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 ===\n attributes.style.split('var(').length) {\n attributes.style = attribute.styleDiff;\n }\n }\n }\n return {\n id: this.mirror.getId(attribute.node),\n attributes: attributes,\n };\n })\n .filter((attribute) => !addedIds.has(attribute.id))\n .filter((attribute) => this.mirror.has(attribute.id)),\n removes: this.removes,\n adds,\n };\n if (!payload.texts.length &&\n !payload.attributes.length &&\n !payload.removes.length &&\n !payload.adds.length) {\n return;\n }\n this.texts = [];\n this.attributes = [];\n this.attributeMap = new WeakMap();\n this.removes = [];\n this.addedSet = new Set();\n this.movedSet = new Set();\n this.droppedSet = 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(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) &&\n value !== m.oldValue) {\n this.texts.push({\n value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, this.maskAllText) && value\n ? this.maskTextFn\n ? this.maskTextFn(value, closestElementOfNode(m.target))\n : value.replace(/[\\S]/g, '*')\n : 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(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, isInputMasked);\n value = maskInputValue({\n isMasked: forceMask,\n element: target,\n value,\n maskInputFn: this.maskInputFn,\n });\n }\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) ||\n value === m.oldValue) {\n return;\n }\n let item = this.attributeMap.get(m.target);\n if (target.tagName === 'IFRAME' &&\n attributeName === 'src' &&\n !this.keepIframeSrcFn(value)) {\n const iframeDoc = getIFrameContentDocument(target);\n if (!iframeDoc) {\n attributeName = 'rr_src';\n }\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' &&\n target.tagName === 'INPUT' &&\n (m.oldValue || '').toLowerCase() === 'password') {\n target.setAttribute('data-rr-is-password', 'true');\n }\n if (!ignoreAttribute(target.tagName, attributeName)) {\n item.attributes[attributeName] = transformAttribute(this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value, target, this.maskAttributeFn);\n if (attributeName === 'style') {\n if (!this.unattachedDoc) {\n try {\n this.unattachedDoc =\n document.implementation.createHTMLDocument();\n }\n catch (e) {\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) ||\n newPriority !== old.style.getPropertyPriority(pname)) {\n if (newPriority === '') {\n item.styleDiff[pname] = newValue;\n }\n else {\n item.styleDiff[pname] = [newValue, newPriority];\n }\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(m.target, this.blockClass, this.blockSelector, this.unblockSelector, true)) {\n return;\n }\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\n m.removedNodes.forEach((n) => {\n const nodeId = this.mirror.getId(n);\n const parentId = isShadowRoot(m.target)\n ? this.mirror.getId(m.target.host)\n : this.mirror.getId(m.target);\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) ||\n isIgnored(n, this.mirror) ||\n !isSerialized(n, this.mirror)) {\n return;\n }\n if (this.addedSet.has(n)) {\n deepDelete(this.addedSet, n);\n this.droppedSet.add(n);\n }\n else if (this.addedSet.has(m.target) && nodeId === -1) ;\n else if (isAncestorRemoved(m.target, this.mirror)) ;\n else if (this.movedSet.has(n) &&\n this.movedMap[moveKey(nodeId, parentId)]) {\n deepDelete(this.movedSet, n);\n }\n else {\n this.removes.push({\n parentId,\n id: nodeId,\n isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target)\n ? true\n : undefined,\n });\n }\n this.mapRemoves.push(n);\n });\n break;\n }\n }\n };\n this.genAdds = (n, target) => {\n if (this.processedNodeManager.inOtherBuffer(n, this))\n return;\n if (this.addedSet.has(n) || this.movedSet.has(n))\n return;\n if (this.mirror.hasNode(n)) {\n if (isIgnored(n, this.mirror)) {\n return;\n }\n this.movedSet.add(n);\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(n), targetId)] = true;\n }\n }\n else {\n this.addedSet.add(n);\n this.droppedSet.delete(n);\n }\n if (!isBlocked(n, this.blockClass, this.blockSelector, this.unblockSelector, false)) {\n n.childNodes.forEach((childN) => this.genAdds(childN));\n if (hasShadowRoot(n)) {\n n.shadowRoot.childNodes.forEach((childN) => {\n this.processedNodeManager.add(childN, this);\n this.genAdds(childN, n);\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 ].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, n) {\n addsSet.delete(n);\n n.childNodes.forEach((childN) => deepDelete(addsSet, childN));\n}\nfunction isParentRemoved(removes, n, mirror) {\n if (removes.length === 0)\n return false;\n return _isParentRemoved(removes, n, mirror);\n}\nfunction _isParentRemoved(removes, n, mirror) {\n let node = n.parentNode;\n while (node) {\n const parentId = mirror.getId(node);\n if (removes.some((r) => r.id === parentId)) {\n return true;\n }\n node = node.parentNode;\n }\n return false;\n}\nfunction isAncestorInSet(set, n) {\n if (set.size === 0)\n return false;\n return _isAncestorInSet(set, n);\n}\nfunction _isAncestorInSet(set, n) {\n const { parentNode } = n;\n if (!parentNode) {\n return false;\n }\n if (set.has(parentNode)) {\n return true;\n }\n return _isAncestorInSet(set, parentNode);\n}\n\nlet errorHandler;\nfunction registerErrorHandler(handler) {\n errorHandler = handler;\n}\nfunction unregisterErrorHandler() {\n errorHandler = undefined;\n}\nconst callbackWrapper = (cb) => {\n if (!errorHandler) {\n return cb;\n }\n const rrwebWrapped = ((...rest) => {\n try {\n return cb(...rest);\n }\n catch (error) {\n if (errorHandler && errorHandler(error) === true) {\n return () => {\n };\n }\n throw error;\n }\n });\n return rrwebWrapped;\n};\n\nfunction _optionalChain$2(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }\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 }\n else if ('path' in event && event.path.length) {\n return event.path[0];\n }\n }\n catch (e2) {\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 window.__rrMutationObserver;\n const angularZoneSymbol = _optionalChain$2([window, 'optionalAccess', _ => _.Zone, 'optionalAccess', _2 => _2.__symbol__, 'optionalCall', _3 => _3('MutationObserver')]);\n if (angularZoneSymbol &&\n window[angularZoneSymbol]) {\n mutationObserverCtor = window[angularZoneSymbol];\n }\n const observer = new mutationObserverCtor(callbackWrapper((mutations) => {\n if (options.onMutation && options.onMutation(mutations) === false) {\n return;\n }\n mutationBuffer.processMutations.bind(mutationBuffer)(mutations);\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({ mousemoveCb, sampling, doc, mirror, }) {\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'\n ? sampling.mousemoveCallback\n : 500;\n let positions = [];\n let timeBaseline;\n const wrappedCb = throttle$1(callbackWrapper((source) => {\n const totalOffset = Date.now() - timeBaseline;\n mousemoveCb(positions.map((p) => {\n p.timeOffset -= totalOffset;\n return p;\n }), source);\n positions = [];\n timeBaseline = null;\n }), callbackThreshold);\n const updatePosition = callbackWrapper(throttle$1(callbackWrapper((evt) => {\n const target = getEventTarget(evt);\n const { clientX, clientY } = legacy_isTouchEvent(evt)\n ? evt.changedTouches[0]\n : evt;\n if (!timeBaseline) {\n timeBaseline = nowTimestamp();\n }\n positions.push({\n x: clientX,\n y: clientY,\n id: mirror.getId(target),\n timeOffset: nowTimestamp() - timeBaseline,\n });\n wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent\n ? IncrementalSource.Drag\n : evt instanceof MouseEvent\n ? IncrementalSource.MouseMove\n : IncrementalSource.TouchMove);\n }), threshold, {\n trailing: false,\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({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\n if (sampling.mouseInteraction === false) {\n return () => {\n };\n }\n const disableMap = sampling.mouseInteraction === true ||\n sampling.mouseInteraction === undefined\n ? {}\n : 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 }\n else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\n thisEventKey = 'TouchEnd';\n }\n }\n else if (pointerType === PointerTypes.Pen) ;\n }\n else if (legacy_isTouchEvent(event)) {\n pointerType = PointerTypes.Touch;\n }\n if (pointerType !== null) {\n currentPointerType = pointerType;\n if ((thisEventKey.startsWith('Touch') &&\n pointerType === PointerTypes.Touch) ||\n (thisEventKey.startsWith('Mouse') &&\n pointerType === PointerTypes.Mouse)) {\n pointerType = null;\n }\n }\n else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\n pointerType = currentPointerType;\n currentPointerType = null;\n }\n const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\n if (!e) {\n return;\n }\n const id = mirror.getId(target);\n const { clientX, clientY } = e;\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)\n .filter((key) => Number.isNaN(Number(key)) &&\n !key.endsWith('_Departed') &&\n 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('mouse', 'pointer');\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({ scrollCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\n const updatePosition = callbackWrapper(throttle$1(callbackWrapper((evt) => {\n const target = getEventTarget(evt);\n if (!target ||\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\n return;\n }\n const id = mirror.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 }\n else {\n scrollCb({\n id,\n x: target.scrollLeft,\n y: target.scrollTop,\n });\n }\n }), sampling.scroll || 100));\n return on('scroll', updatePosition, doc);\n}\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\n let lastH = -1;\n let lastW = -1;\n const updateDimension = callbackWrapper(throttle$1(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 }), 200));\n return on('resize', updateDimension, win);\n}\nconst INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\nconst lastInputValueMap = new WeakMap();\nfunction initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, unblockSelector, ignoreClass, ignoreSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, }) {\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')\n target = target.parentElement;\n if (!target ||\n !tagName ||\n INPUT_TAGS.indexOf(tagName) < 0 ||\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\n return;\n }\n const el = target;\n if (el.classList.contains(ignoreClass) ||\n (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(target, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked);\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(target, userTriggeredOnInput\n ? { text, isChecked, userTriggered }\n : { text, isChecked });\n const name = target.name;\n if (type === 'radio' && name && isChecked) {\n doc\n .querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`)\n .forEach((el) => {\n if (el !== target) {\n const text = maskInputValue({\n isMasked: forceMask,\n element: el,\n value: getInputValue(el, tagName, type),\n maskInputFn,\n });\n cbWithDedup(el, userTriggeredOnInput\n ? { text, isChecked: !isChecked, userTriggered: false }\n : { text, isChecked: !isChecked });\n }\n });\n }\n }\n function cbWithDedup(target, v) {\n const lastInputValue = lastInputValueMap.get(target);\n if (!lastInputValue ||\n lastInputValue.text !== v.text ||\n lastInputValue.isChecked !== v.isChecked) {\n lastInputValueMap.set(target, v);\n const id = mirror.getId(target);\n callbackWrapper(inputCb)({\n ...v,\n id,\n });\n }\n }\n const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\n const handlers = events.map((eventName) => on(eventName, callbackWrapper(eventHandler), doc));\n const currentWindow = doc.defaultView;\n if (!currentWindow) {\n return () => {\n handlers.forEach((h) => h());\n };\n }\n const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, 'value');\n const hookProperties = [\n [currentWindow.HTMLInputElement.prototype, 'value'],\n [currentWindow.HTMLInputElement.prototype, 'checked'],\n [currentWindow.HTMLSelectElement.prototype, 'value'],\n [currentWindow.HTMLTextAreaElement.prototype, 'value'],\n [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'],\n [currentWindow.HTMLOptionElement.prototype, 'selected'],\n ];\n if (propertyDescriptor && propertyDescriptor.set) {\n handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {\n set() {\n callbackWrapper(eventHandler)({\n target: this,\n isTrusted: false,\n });\n },\n }, false, currentWindow)));\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') &&\n childRule.parentRule instanceof CSSGroupingRule) ||\n (hasNestedCSSRule('CSSMediaRule') &&\n childRule.parentRule instanceof CSSMediaRule) ||\n (hasNestedCSSRule('CSSSupportsRule') &&\n childRule.parentRule instanceof CSSSupportsRule) ||\n (hasNestedCSSRule('CSSConditionRule') &&\n childRule.parentRule instanceof CSSConditionRule)) {\n const rules = Array.from(childRule.parentRule.cssRules);\n const index = rules.indexOf(childRule);\n pos.unshift(index);\n }\n else if (childRule.parentStyleSheet) {\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\n const index = rules.indexOf(childRule);\n pos.unshift(index);\n }\n return pos;\n }\n return recurse(rule, positions);\n}\nfunction getIdAndStyleId(sheet, mirror, styleMirror) {\n let id, styleId;\n if (!sheet)\n return {};\n if (sheet.ownerNode)\n id = mirror.getId(sheet.ownerNode);\n else\n styleId = styleMirror.getId(sheet);\n return {\n styleId,\n id,\n };\n}\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror, 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((target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\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 const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\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 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((target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\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 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((target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\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 const supportedNestedCSSRuleTypes = {};\n if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n }\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 insertRule: type.prototype.insertRule,\n deleteRule: type.prototype.deleteRule,\n };\n type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\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 ],\n },\n ],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\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 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({ mirror, stylesheetManager, }, host) {\n let hostId = null;\n if (host.nodeName === '#document')\n hostId = mirror.getId(host);\n else\n hostId = mirror.getId(host.host);\n const patchTarget = host.nodeName === '#document'\n ? _optionalChain$2([host, 'access', _4 => _4.defaultView, 'optionalAccess', _5 => _5.Document])\n : _optionalChain$2([host, 'access', _6 => _6.ownerDocument, 'optionalAccess', _7 => _7.defaultView, 'optionalAccess', _8 => _8.ShadowRoot]);\n const originalPropertyDescriptor = _optionalChain$2([patchTarget, 'optionalAccess', _9 => _9.prototype])\n ? Object.getOwnPropertyDescriptor(_optionalChain$2([patchTarget, 'optionalAccess', _10 => _10.prototype]), 'adoptedStyleSheets')\n : undefined;\n if (hostId === null ||\n hostId === -1 ||\n !patchTarget ||\n !originalPropertyDescriptor)\n return () => {\n };\n Object.defineProperty(host, 'adoptedStyleSheets', {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n get() {\n return _optionalChain$2([originalPropertyDescriptor, 'access', _11 => _11.get, 'optionalAccess', _12 => _12.call, 'call', _13 => _13(this)]);\n },\n set(sheets) {\n const result = _optionalChain$2([originalPropertyDescriptor, 'access', _14 => _14.set, 'optionalAccess', _15 => _15.call, 'call', _16 => _16(this, sheets)]);\n if (hostId !== null && hostId !== -1) {\n try {\n stylesheetManager.adoptStyleSheets(sheets, hostId);\n }\n catch (e) {\n }\n }\n return result;\n },\n });\n return callbackWrapper(() => {\n Object.defineProperty(host, 'adoptedStyleSheets', {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n get: originalPropertyDescriptor.get,\n set: originalPropertyDescriptor.set,\n });\n });\n}\nfunction initStyleDeclarationObserver({ styleDeclarationCb, mirror, ignoreCSSAttributes, stylesheetManager, }, { win }) {\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\n apply: callbackWrapper((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(_optionalChain$2([thisArg, 'access', _17 => _17.parentRule, 'optionalAccess', _18 => _18.parentStyleSheet]), mirror, stylesheetManager.styleMirror);\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\n styleDeclarationCb({\n id,\n styleId,\n set: {\n property,\n value,\n priority,\n },\n index: getNestedCSSRulePositions(thisArg.parentRule),\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [property] = argumentsList;\n if (ignoreCSSAttributes.has(property)) {\n return removeProperty.apply(thisArg, [property]);\n }\n const { id, styleId } = getIdAndStyleId(_optionalChain$2([thisArg, 'access', _19 => _19.parentRule, 'optionalAccess', _20 => _20.parentStyleSheet]), mirror, stylesheetManager.styleMirror);\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\n styleDeclarationCb({\n id,\n styleId,\n remove: {\n property,\n },\n index: getNestedCSSRulePositions(thisArg.parentRule),\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n return callbackWrapper(() => {\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n });\n}\nfunction initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, unblockSelector, mirror, sampling, doc, }) {\n const handler = callbackWrapper((type) => throttle$1(callbackWrapper((event) => {\n const target = getEventTarget(event);\n if (!target ||\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\n return;\n }\n const { currentTime, volume, muted, playbackRate } = target;\n mediaInteractionCb({\n type,\n id: mirror.getId(target),\n currentTime,\n volume,\n muted,\n playbackRate,\n });\n }), sampling.media || 500));\n const handlers = [\n on('play', handler(0), doc),\n on('pause', handler(1), doc),\n on('seeked', handler(2), doc),\n on('volumechange', handler(3), doc),\n on('ratechange', handler(4), 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 = new WeakMap();\n const originalFontFace = win.FontFace;\n win.FontFace = function FontFace(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'\n ? source\n : JSON.stringify(Array.from(new Uint8Array(source))),\n });\n return fontFace;\n };\n const restoreHandler = patch(doc.fonts, 'add', function (original) {\n return function (fontFace) {\n setTimeout$1(callbackWrapper(() => {\n const p = fontMap.get(fontFace);\n if (p) {\n fontCb(p);\n fontMap.delete(fontFace);\n }\n }), 0);\n return original.apply(this, [fontFace]);\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 { doc, mirror, blockClass, blockSelector, unblockSelector, selectionCb, } = param;\n let collapsed = true;\n const updateSelection = callbackWrapper(() => {\n const selection = doc.getSelection();\n if (!selection || (collapsed && _optionalChain$2([selection, 'optionalAccess', _21 => _21.isCollapsed])))\n return;\n collapsed = selection.isCollapsed || false;\n const ranges = [];\n const count = selection.rangeCount || 0;\n for (let i = 0; i < count; i++) {\n const range = selection.getRangeAt(i);\n const { startContainer, startOffset, endContainer, endOffset } = range;\n const blocked = isBlocked(startContainer, blockClass, blockSelector, unblockSelector, true) ||\n isBlocked(endContainer, blockClass, blockSelector, unblockSelector, true);\n if (blocked)\n continue;\n ranges.push({\n start: mirror.getId(startContainer),\n startOffset,\n end: mirror.getId(endContainer),\n endOffset,\n });\n }\n selectionCb({ ranges });\n });\n updateSelection();\n return on('selectionchange', updateSelection);\n}\nfunction initCustomElementObserver({ doc, customElementCb, }) {\n const win = doc.defaultView;\n if (!win || !win.customElements)\n return () => { };\n const restoreHandler = patch(win.customElements, 'define', function (original) {\n return function (name, constructor, options) {\n try {\n customElementCb({\n define: {\n name,\n },\n });\n }\n catch (e) {\n }\n return original.apply(this, [name, constructor, options]);\n };\n });\n return restoreHandler;\n}\nfunction initObservers(o, _hooks = {}) {\n const currentWindow = o.doc.defaultView;\n if (!currentWindow) {\n return () => {\n };\n }\n let mutationObserver;\n if (o.recordDOM) {\n mutationObserver = initMutationObserver(o, o.doc);\n }\n const mousemoveHandler = initMoveObserver(o);\n const mouseInteractionHandler = initMouseInteractionObserver(o);\n const scrollHandler = initScrollObserver(o);\n const viewportResizeHandler = initViewportResizeObserver(o, {\n win: currentWindow,\n });\n const inputHandler = initInputObserver(o);\n const mediaInteractionHandler = initMediaInteractionObserver(o);\n let styleSheetObserver = () => { };\n let adoptedStyleSheetObserver = () => { };\n let styleDeclarationObserver = () => { };\n let fontObserver = () => { };\n if (o.recordDOM) {\n styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\n adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);\n styleDeclarationObserver = initStyleDeclarationObserver(o, {\n win: currentWindow,\n });\n if (o.collectFonts) {\n fontObserver = initFontObserver(o);\n }\n }\n const selectionObserver = initSelectionObserver(o);\n const customElementObserver = initCustomElementObserver(o);\n const pluginHandlers = [];\n for (const plugin of o.plugins) {\n pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));\n }\n return callbackWrapper(() => {\n mutationBuffers.forEach((b) => b.reset());\n _optionalChain$2([mutationObserver, 'optionalAccess', _22 => _22.disconnect, 'call', _23 => _23()]);\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(typeof window[prop] !== 'undefined' &&\n window[prop].prototype &&\n 'insertRule' in window[prop].prototype &&\n 'deleteRule' in window[prop].prototype);\n}\n\nclass CrossOriginIframeMirror {\n constructor(generateIdFn) {\n this.generateIdFn = generateIdFn;\n this.iframeIdToRemoteIdMap = new WeakMap();\n this.iframeRemoteIdToIdMap = 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((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));\n }\n getRemoteId(iframe, id, map) {\n const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\n if (typeof id !== 'number')\n return id;\n const remoteId = remoteIdToIdMap.get(id);\n if (!remoteId)\n 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 = new WeakMap();\n this.iframeRemoteIdToIdMap = 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 = 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 = new Map();\n this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\n }\n return remoteIdToIdMap;\n }\n}\n\nfunction _optionalChain$1(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }\nclass IframeManagerNoop {\n constructor() {\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\n this.crossOriginIframeRootIdMap = new WeakMap();\n }\n addIframe() {\n }\n addLoadListener() {\n }\n attachIframe() {\n }\n}\nclass IframeManager {\n constructor(options) {\n this.iframes = new WeakMap();\n this.crossOriginIframeMap = new WeakMap();\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\n this.crossOriginIframeRootIdMap = 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(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));\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 _optionalChain$1([this, 'access', _ => _.loadListener, 'optionalCall', _2 => _2(iframeEl)]);\n const iframeDoc = getIFrameContentDocument(iframeEl);\n if (iframeDoc &&\n iframeDoc.adoptedStyleSheets &&\n iframeDoc.adoptedStyleSheets.length > 0)\n this.stylesheetManager.adoptStyleSheets(iframeDoc.adoptedStyleSheets, this.mirror.getId(iframeDoc));\n }\n handleMessage(message) {\n const crossOriginMessageEvent = message;\n if (crossOriginMessageEvent.data.type !== 'rrweb' ||\n crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\n return;\n const iframeSourceWindow = message.source;\n if (!iframeSourceWindow)\n return;\n const iframeEl = this.crossOriginIframeMap.get(message.source);\n if (!iframeEl)\n return;\n const transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);\n if (transformedEvent)\n this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);\n }\n transformCrossOriginEvent(iframeEl, e) {\n switch (e.type) {\n case EventType.FullSnapshot: {\n this.crossOriginIframeMirror.reset(iframeEl);\n this.crossOriginIframeStyleMirror.reset(iframeEl);\n this.replaceIdOnNode(e.data.node, iframeEl);\n const rootId = e.data.node.id;\n this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\n this.patchRootIdOnNode(e.data.node, rootId);\n return {\n timestamp: e.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: e.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 e;\n }\n case EventType.Custom: {\n this.replaceIds(e.data.payload, iframeEl, ['id', 'parentId', 'previousId', 'nextId']);\n return e;\n }\n case EventType.IncrementalSnapshot: {\n switch (e.data.source) {\n case IncrementalSource.Mutation: {\n e.data.adds.forEach((n) => {\n this.replaceIds(n, iframeEl, [\n 'parentId',\n 'nextId',\n 'previousId',\n ]);\n this.replaceIdOnNode(n.node, iframeEl);\n const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\n rootId && this.patchRootIdOnNode(n.node, rootId);\n });\n e.data.removes.forEach((n) => {\n this.replaceIds(n, iframeEl, ['parentId', 'id']);\n });\n e.data.attributes.forEach((n) => {\n this.replaceIds(n, iframeEl, ['id']);\n });\n e.data.texts.forEach((n) => {\n this.replaceIds(n, iframeEl, ['id']);\n });\n return e;\n }\n case IncrementalSource.Drag:\n case IncrementalSource.TouchMove:\n case IncrementalSource.MouseMove: {\n e.data.positions.forEach((p) => {\n this.replaceIds(p, iframeEl, ['id']);\n });\n return e;\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(e.data, iframeEl, ['id']);\n return e;\n }\n case IncrementalSource.StyleSheetRule:\n case IncrementalSource.StyleDeclaration: {\n this.replaceIds(e.data, iframeEl, ['id']);\n this.replaceStyleIds(e.data, iframeEl, ['styleId']);\n return e;\n }\n case IncrementalSource.Font: {\n return e;\n }\n case IncrementalSource.Selection: {\n e.data.ranges.forEach((range) => {\n this.replaceIds(range, iframeEl, ['start', 'end']);\n });\n return e;\n }\n case IncrementalSource.AdoptedStyleSheet: {\n this.replaceIds(e.data, iframeEl, ['id']);\n this.replaceStyleIds(e.data, iframeEl, ['styleIds']);\n _optionalChain$1([e, 'access', _3 => _3.data, 'access', _4 => _4.styles, 'optionalAccess', _5 => _5.forEach, 'call', _6 => _6((style) => {\n this.replaceStyleIds(style, iframeEl, ['styleId']);\n })]);\n return e;\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')\n continue;\n if (Array.isArray(obj[key])) {\n obj[key] = iframeMirror.getIds(iframeEl, 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$3.Document && !node.rootId)\n node.rootId = rootId;\n if ('childNodes' in node) {\n node.childNodes.forEach((child) => {\n this.patchRootIdOnNode(child, rootId);\n });\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 = 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))\n return;\n if (this.shadowDoms.has(shadowRoot))\n return;\n this.shadowDoms.add(shadowRoot);\n this.bypassOptions.canvasManager.addShadowRoot(shadowRoot);\n const observer = initMutationObserver({\n ...this.bypassOptions,\n doc,\n mutationCb: this.mutationCb,\n mirror: this.mirror,\n shadowDomManager: this,\n }, shadowRoot);\n this.restoreHandlers.push(() => observer.disconnect());\n this.restoreHandlers.push(initScrollObserver({\n ...this.bypassOptions,\n scrollCb: this.scrollCb,\n doc: shadowRoot,\n mirror: this.mirror,\n }));\n setTimeout$1(() => {\n if (shadowRoot.adoptedStyleSheets &&\n shadowRoot.adoptedStyleSheets.length > 0)\n this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));\n this.restoreHandlers.push(initAdoptedStyleSheetObserver({\n mirror: this.mirror,\n stylesheetManager: this.bypassOptions.stylesheetManager,\n }, shadowRoot));\n }, 0);\n }\n observeAttachShadow(iframeElement) {\n const iframeDoc = getIFrameContentDocument(iframeElement);\n const iframeWindow = getIFrameContentWindow(iframeElement);\n if (!iframeDoc || !iframeWindow)\n return;\n this.patchAttachShadow(iframeWindow.Element, iframeDoc);\n }\n patchAttachShadow(element, doc) {\n const manager = this;\n this.restoreHandlers.push(patch(element.prototype, 'attachShadow', 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 reset() {\n this.restoreHandlers.forEach((handler) => {\n try {\n handler();\n }\n catch (e) {\n }\n });\n this.restoreHandlers = [];\n this.shadowDoms = new WeakSet();\n this.bypassOptions.canvasManager.resetShadowRoots();\n }\n}\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}\n\nclass StylesheetManager {\n constructor(options) {\n this.trackedLinkElements = 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\n .attributes,\n },\n ],\n });\n this.trackLinkElement(linkEl);\n }\n trackLinkElement(linkEl) {\n if (this.trackedLinkElements.has(linkEl))\n return;\n this.trackedLinkElements.add(linkEl);\n this.trackStylesheetInLinkElement(linkEl);\n }\n adoptStyleSheets(sheets, hostId) {\n if (sheets.length === 0)\n 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, (r, index) => ({\n rule: stringifyRule(r),\n index,\n })),\n });\n }\n else\n styleId = this.styleMirror.getId(sheet);\n adoptedStyleSheetData.styleIds.push(styleId);\n }\n if (styles.length > 0)\n adoptedStyleSheetData.styles = styles;\n this.adoptedStyleSheetCb(adoptedStyleSheetData);\n }\n reset() {\n this.styleMirror.reset();\n this.trackedLinkElements = new WeakSet();\n }\n trackStylesheetInLinkElement(linkEl) {\n }\n}\n\nclass ProcessedNodeManager {\n constructor() {\n this.nodeMap = 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 = new WeakMap();\n this.active = false;\n });\n }\n this.nodeMap.set(node, (this.nodeMap.get(node) || new Set()).add(buffer));\n }\n destroy() {\n }\n}\n\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 = _optionalChain([cleanFrame, 'access', _ => _.contentWindow, 'optionalAccess', _2 => _2.Array, 'access', _3 => _3.from]) || Array.from;\n document.body.removeChild(cleanFrame);\n }\n}\ncatch (err) {\n console.debug('Unable to override Array.from', err);\n}\nconst mirror = createMirror();\nfunction record(options = {}) {\n const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, unblockSelector = null, ignoreClass = 'rr-ignore', ignoreSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskAttributeFn, maskInputFn, maskTextFn, maxCanvasSize = null, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordDOM = true, recordCanvas = false, recordCrossOriginIframes = false, recordAfter = options.recordAfter === 'DOMContentLoaded'\n ? options.recordAfter\n : 'load', userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, ignoreCSSAttributes = new Set([]), errorHandler, onMutation, getCanvasManager, } = options;\n registerErrorHandler(errorHandler);\n const inEmittingFrame = recordCrossOriginIframes\n ? window.parent === window\n : true;\n let passEmitsToParent = false;\n if (!inEmittingFrame) {\n try {\n if (window.parent.document) {\n passEmitsToParent = false;\n }\n }\n catch (e) {\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 !== undefined && sampling.mousemove === undefined) {\n sampling.mousemove = mousemoveWait;\n }\n mirror.reset();\n const maskInputOptions = maskAllInputs === true\n ? {\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 }\n : _maskInputOptions !== undefined\n ? _maskInputOptions\n : {};\n const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'\n ? {\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 headMetaAuthorship: _slimDOMOptions === 'all',\n headMetaDescKeywords: _slimDOMOptions === 'all',\n }\n : _slimDOMOptions\n ? _slimDOMOptions\n : {};\n polyfill();\n let lastFullSnapshotEvent;\n let incrementalSnapshotCount = 0;\n const eventProcessor = (e) => {\n for (const plugin of plugins || []) {\n if (plugin.eventProcessor) {\n e = plugin.eventProcessor(e);\n }\n }\n if (packFn &&\n !passEmitsToParent) {\n e = packFn(e);\n }\n return e;\n };\n wrappedEmit = (r, isCheckout) => {\n const e = r;\n e.timestamp = nowTimestamp();\n if (_optionalChain([mutationBuffers, 'access', _4 => _4[0], 'optionalAccess', _5 => _5.isFrozen, 'call', _6 => _6()]) &&\n e.type !== EventType.FullSnapshot &&\n !(e.type === EventType.IncrementalSnapshot &&\n e.data.source === IncrementalSource.Mutation)) {\n mutationBuffers.forEach((buf) => buf.unfreeze());\n }\n if (inEmittingFrame) {\n _optionalChain([emit, 'optionalCall', _7 => _7(eventProcessor(e), isCheckout)]);\n }\n else if (passEmitsToParent) {\n const message = {\n type: 'rrweb',\n event: eventProcessor(e),\n origin: window.location.origin,\n isCheckout,\n };\n window.parent.postMessage(message, '*');\n }\n if (e.type === EventType.FullSnapshot) {\n lastFullSnapshotEvent = e;\n incrementalSnapshotCount = 0;\n }\n else if (e.type === EventType.IncrementalSnapshot) {\n if (e.data.source === IncrementalSource.Mutation &&\n e.data.isAttachIframe) {\n return;\n }\n incrementalSnapshotCount++;\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n const exceedTime = checkoutEveryNms &&\n lastFullSnapshotEvent &&\n e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n if (exceedCount || exceedTime) {\n takeFullSnapshot(true);\n }\n }\n };\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 = (a) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.AdoptedStyleSheet,\n ...a,\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__\n ? new IframeManagerNoop()\n : new IframeManager({\n mirror,\n mutationCb: wrappedMutationEmit,\n stylesheetManager: 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(getCanvasManager, {\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,\n });\n const shadowDomManager = typeof __RRWEB_EXCLUDE_SHADOW_DOM__ === 'boolean' &&\n __RRWEB_EXCLUDE_SHADOW_DOM__\n ? new ShadowDomManagerNoop()\n : 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 },\n mirror,\n });\n const takeFullSnapshot = (isCheckout = false) => {\n if (!recordDOM) {\n return;\n }\n wrappedEmit({\n type: EventType.Meta,\n data: {\n href: window.location.href,\n width: getWindowWidth(),\n height: getWindowHeight(),\n },\n }, isCheckout);\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: (n) => {\n if (isSerializedIframe(n, mirror)) {\n iframeManager.addIframe(n);\n }\n if (isSerializedStylesheet(n, mirror)) {\n stylesheetManager.trackLinkElement(n);\n }\n if (hasShadowRoot(n)) {\n shadowDomManager.addShadowRoot(n.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 keepIframeSrcFn,\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(document.adoptedStyleSheets, mirror.getId(document));\n };\n _takeFullSnapshot = takeFullSnapshot;\n try {\n const handlers = [];\n const observe = (doc) => {\n return callbackWrapper(initObservers)({\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: (v) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Input,\n ...v,\n },\n }),\n mediaInteractionCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.MediaInteraction,\n ...p,\n },\n }),\n styleSheetRuleCb: (r) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleSheetRule,\n ...r,\n },\n }),\n styleDeclarationCb: (r) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleDeclaration,\n ...r,\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: (c) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CustomElement,\n ...c,\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: _optionalChain([plugins\n, 'optionalAccess', _8 => _8.filter, 'call', _9 => _9((p) => p.observer)\n, 'optionalAccess', _10 => _10.map, 'call', _11 => _11((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 iframeManager.addLoadListener((iframeEl) => {\n try {\n handlers.push(observe(iframeEl.contentDocument));\n }\n catch (error) {\n console.warn(error);\n }\n });\n const init = () => {\n takeFullSnapshot();\n handlers.push(observe(document));\n };\n if (document.readyState === 'interactive' ||\n document.readyState === 'complete') {\n init();\n }\n else {\n handlers.push(on('DOMContentLoaded', () => {\n wrappedEmit({\n type: EventType.DomContentLoaded,\n data: {},\n });\n if (recordAfter === 'DOMContentLoaded')\n init();\n }));\n handlers.push(on('load', () => {\n wrappedEmit({\n type: EventType.Load,\n data: {},\n });\n if (recordAfter === 'load')\n init();\n }, window));\n }\n return () => {\n handlers.forEach((h) => h());\n processedNodeManager.destroy();\n _takeFullSnapshot = undefined;\n unregisterErrorHandler();\n };\n }\n catch (error) {\n console.warn(error);\n }\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\n ? getCanvasManagerFn(options)\n : new CanvasManagerNoop();\n }\n catch (e2) {\n console.warn('Unable to initialize CanvasManager');\n return new CanvasManagerNoop();\n }\n}\n\nconst ReplayEventTypeIncrementalSnapshot = 3;\nconst ReplayEventTypeCustom = 5;\n\n/**\n * Converts a timestamp to ms, if it was in s, or keeps it as ms.\n */\nfunction timestampToMs(timestamp) {\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 */\nfunction timestampToS(timestamp) {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Add a breadcrumb event to replay.\n */\nfunction addBreadcrumbEvent(replay, breadcrumb) {\n if (breadcrumb.category === 'sentry.transaction') {\n return;\n }\n\n if (['ui.click', 'ui.input'].includes(breadcrumb.category )) {\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, 1000),\n },\n });\n\n // Do not flush after console log messages\n return breadcrumb.category === 'console';\n });\n}\n\nconst INTERACTIVE_SELECTOR = 'button,a';\n\n/** Get the closest interactive parent element, or else return the given element. */\nfunction getClosestInteractive(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 */\nfunction getClickTargetNode(event) {\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. */\nfunction getTargetNode(event) {\n if (isEventWithTarget(event)) {\n return event.target ;\n }\n\n return event;\n}\n\nfunction isEventWithTarget(event) {\n return typeof event === 'object' && !!event && 'target' in event;\n}\n\nlet handlers;\n\n/**\n * Register a handler to be called when `window.open()` is called.\n * Returns a cleanup function.\n */\nfunction onWindowOpen(cb) {\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 ).splice(pos, 1);\n }\n };\n}\n\nfunction monkeyPatchWindowOpen() {\n fill(WINDOW, 'open', function (originalWindowOpen) {\n return function (...args) {\n if (handlers) {\n try {\n handlers.forEach(handler => handler());\n } catch (e) {\n // ignore errors in here\n }\n }\n\n return originalWindowOpen.apply(WINDOW, args);\n };\n });\n}\n\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. */\nfunction handleClick(clickDetector, clickBreadcrumb, node) {\n clickDetector.handleClick(clickBreadcrumb, node);\n}\n\n/** A click detector class that can be used to detect slow or rage clicks on elements. */\nclass ClickDetector {\n // protected for testing\n\n constructor(\n replay,\n 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 addListeners() {\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 removeListeners() {\n if (this._teardown) {\n this._teardown();\n }\n\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n }\n\n /** @inheritDoc */\n handleClick(breadcrumb, node) {\n if (ignoreElement(node, this._ignoreSelector) || !isClickBreadcrumb(breadcrumb)) {\n return;\n }\n\n const newClick = {\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 registerMutation(timestamp = Date.now()) {\n this._lastMutation = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n registerScroll(timestamp = Date.now()) {\n this._lastScroll = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n registerClick(element) {\n const node = getClosestInteractive(element);\n this._handleMultiClick(node );\n }\n\n /** Count multiple clicks on elements. */\n _handleMultiClick(node) {\n this._getClicks(node).forEach(click => {\n click.clickCount++;\n });\n }\n\n /** Get all pending clicks for a given node. */\n _getClicks(node) {\n return this._clicks.filter(click => click.node === node);\n }\n\n /** Check the clicks that happened. */\n _checkClicks() {\n const timedOutClicks = [];\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 _generateBreadcrumbs(click) {\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 = {\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 = {\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 _scheduleCheckClicks() {\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n\n this._checkClickTimeout = setTimeout$3(() => this._checkClicks(), 1000);\n }\n}\n\nconst SLOW_CLICK_TAGS = ['A', 'BUTTON', 'INPUT'];\n\n/** exported for tests only */\nfunction ignoreElement(node, ignoreSelector) {\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) {\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() {\n return Date.now() / 1000;\n}\n\n/** Update the click detector based on a recording event of rrweb. */\nfunction updateClickDetectorForRecordingEvent(clickDetector, event) {\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 (e) {\n // ignore errors here, e.g. if accessing something that does not exist\n }\n}\n\nfunction isIncrementalEvent(event) {\n return event.type === ReplayEventTypeIncrementalSnapshot;\n}\n\nfunction isIncrementalMouseInteraction(\n event,\n) {\n return event.data.source === IncrementalSource.MouseInteraction;\n}\n\n/**\n * Create a breadcrumb for a replay.\n */\nfunction createBreadcrumb(\n breadcrumb,\n) {\n return {\n timestamp: Date.now() / 1000,\n type: 'default',\n ...breadcrumb,\n };\n}\n\nvar NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n})(NodeType || (NodeType = {}));\n\n// Note that these are the serialized attributes and not attributes directly on\n// the DOM Node. Attributes we are interested in:\nconst ATTRIBUTES_TO_RECORD = new Set([\n 'id',\n 'class',\n 'aria-label',\n 'role',\n 'name',\n 'alt',\n 'title',\n 'data-test-id',\n 'data-testid',\n 'disabled',\n 'aria-disabled',\n 'data-sentry-component',\n]);\n\n/**\n * Inclusion list of attributes that we want to record from the DOM element\n */\nfunction getAttributesToRecord(attributes) {\n const obj = {};\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\nconst handleDomListener = (\n replay,\n) => {\n return (handlerData) => {\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 ) : undefined;\n // Ignore clicks if ctrl/alt/meta/shift keys are held down as they alter behavior of clicks (e.g. open in new tab)\n if (\n isClick &&\n replay.clickDetector &&\n event &&\n event.target &&\n !event.altKey &&\n !event.metaKey &&\n !event.ctrlKey &&\n !event.shiftKey\n ) {\n handleClick(\n replay.clickDetector,\n result ,\n getClickTargetNode(handlerData.event ) ,\n );\n }\n\n addBreadcrumbEvent(replay, result);\n };\n};\n\n/** Get the base DOM breadcrumb. */\nfunction getBaseDomBreadcrumb(target, message) {\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) => node.type === NodeType.Text && node.textContent)\n .filter(Boolean) // filter out empty values\n .map(text => (text ).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 */\nfunction handleDom(handlerData) {\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) {\n const isClick = handlerData.name === 'click';\n\n let message;\n let target = null;\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n target = isClick ? getClickTargetNode(handlerData.event ) : getTargetNode(handlerData.event );\n message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n } catch (e) {\n message = '';\n }\n\n return { target, message };\n}\n\nfunction isElement(node) {\n return node.type === NodeType.Element;\n}\n\n/** Handle keyboard events & create breadcrumbs. */\nfunction handleKeyboardEvent(replay, event) {\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 */\nfunction getKeyboardBreadcrumb(event) {\n const { metaKey, shiftKey, ctrlKey, altKey, key, target } = event;\n\n // never capture for input fields\n if (!target || isInputElement(target ) || !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 , 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) {\n return target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable;\n}\n\n// Map entryType -> function to normalize data for event\nconst ENTRY_TYPES\n\n = {\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n resource: createResourceEntry,\n paint: createPaintEntry,\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n navigation: createNavigationEntry,\n};\n\n/**\n * Handler creater for web vitals\n */\nfunction webVitalHandler(\n getter,\n replay,\n) {\n return ({ metric }) => void replay.replayPerformanceEntries.push(getter(metric));\n}\n\n/**\n * Create replay performance entries from the browser performance entries.\n */\nfunction createPerformanceEntries(\n entries,\n) {\n return entries.map(createPerformanceEntry).filter(Boolean) ;\n}\n\nfunction createPerformanceEntry(entry) {\n const entryType = ENTRY_TYPES[entry.entryType];\n if (!entryType) {\n return null;\n }\n\n return entryType(entry);\n}\n\nfunction getAbsoluteTime(time) {\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) {\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) {\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,\n) {\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 */\nfunction getLargestContentfulPaint(metric) {\n const lastEntry = metric.entries[metric.entries.length - 1] ;\n const node = lastEntry && lastEntry.element ? [lastEntry.element] : undefined;\n return getWebVital(metric, 'largest-contentful-paint', node);\n}\n\nfunction isLayoutShift(entry) {\n return (entry ).sources !== undefined;\n}\n\n/**\n * Add a CLS event to the replay based on a CLS metric.\n */\nfunction getCumulativeLayoutShift(metric) {\n const layoutShifts = [];\n const nodes = [];\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 a FID event to the replay based on a FID metric.\n */\nfunction getFirstInputDelay(metric) {\n const lastEntry = metric.entries[metric.entries.length - 1] ;\n const node = lastEntry && lastEntry.target ? [lastEntry.target] : undefined;\n return getWebVital(metric, 'first-input-delay', node);\n}\n\n/**\n * Add an INP event to the replay based on an INP metric.\n */\nfunction getInteractionToNextPaint(metric) {\n const lastEntry = metric.entries[metric.entries.length - 1] ;\n const node = lastEntry && 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,\n name,\n nodes,\n attributions,\n) {\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\n/**\n * Sets up a PerformanceObserver to listen to all performance entry types.\n * Returns a callback to stop observing.\n */\nfunction setupPerformanceObserver(replay) {\n function addPerformanceEntry(entry) {\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 }) {\n entries.forEach(addPerformanceEntry);\n }\n\n const clearCallbacks = [];\n\n (['navigation', 'paint', 'resource'] ).forEach(type => {\n clearCallbacks.push(addPerformanceInstrumentationHandler(type, onEntries));\n });\n\n clearCallbacks.push(\n addLcpInstrumentationHandler(webVitalHandler(getLargestContentfulPaint, replay)),\n addClsInstrumentationHandler(webVitalHandler(getCumulativeLayoutShift, replay)),\n addFidInstrumentationHandler(webVitalHandler(getFirstInputDelay, 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\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 */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nconst r = `var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=function(t,e){for(var i=new n(31),a=0;a<31;++a)i[a]=e+=1<>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,a=0,s=new n(r);a>h]=l}else for(o=new n(i),a=0;a>15-t[a]);return o},g=new t(288);for(c=0;c<144;++c)g[c]=8;for(c=144;c<256;++c)g[c]=9;for(c=256;c<280;++c)g[c]=7;for(c=280;c<288;++c)g[c]=8;var w=new t(32);for(c=0;c<32;++c)w[c]=5;var p=d(g,9,0),y=d(w,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==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=[],a=0;ad&&(d=o[a].s);var g=new n(d+1),w=A(i[c-1],g,0);if(w>e){a=0;var p=0,y=w-e,m=1<e))break;p+=m-(1<>=y;p>0;){var M=o[a].s;g[M]=0&&p;--a){var E=o[a].s;g[E]==e&&(--g[E],++p)}w=e}return{t:new t(g),l:w}},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,a=t[0],s=1,o=function(t){e[i++]=t},f=1;f<=r;++f)if(t[f]==a&&f!=r)++s;else{if(!a&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(a),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(a);s=1,a=t[f]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var a=0;a4&&!H[a[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(f,g)+T(h,w)+l,X=T(f,M)+T(h,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=p,P=g,Q=y,R=w;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;return{p:function(n){for(var r=t,e=0;e>>8;t=r},d:function(){return~t}}},L=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,a=0|r.length,s=0;s!=a;){for(var o=Math.min(s+2655,a);s>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},O=function(a,s,o,f,u){if(!u&&(u={l:1},s.dictionary)){var c=s.dictionary.subarray(-32768),v=new t(c.length+a.length);v.set(c),v.set(a,c.length),a=v,u.w=c.length}return function(a,s,o,f,u,c){var v=c.z||a.length,d=new t(f+v+5*(1+Math.ceil(v/7e3))+u),g=d.subarray(f,d.length-u),w=c.l,p=7&(c.r||0);if(s){p&&(g[0]=c.r>>3);for(var y=C[s-1],M=y>>13,E=8191&y,z=(1<7e3||q>24576)&&(N>423||!w)){p=U(a,g,0,F,I,S,O,q,G,j-G,p),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(a[j+Q]==a[j+Q-W]){for(var $=0;$Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;Pnt&&(nt=et,K=rt)}}}W+=(J=K)-(K=_[J])&32767}if(R){F[q++]=268435456|h[Q]<<18|l[R];var it=31&h[Q],at=31&l[R];O+=e[it]+i[at],++I[257+it],++S[at],B=j+Q,++L}else F[q++]=a[j],++I[a[j]]}}for(j=Math.max(j,B);j=v&&(g[p/8|0]=w,st=v),p=k(g,p+1,a.subarray(j,st))}c.i=v}return b(d,0,f+m(p)+u)}(a,null==s.level?6:s.level,null==s.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(a.length)))):12+s.mem,o,f,u)},j=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},q=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&&j(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)}},B=function(t){return 10+(t.filename?t.filename.length+1:0)},G=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(O(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var a=this.b.length-this.s.z;a&&(this.b.set(n.subarray(0,a),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(a),32768),this.s.z=n.length-a+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n}();var H=function(){function t(t,n){this.c=L(),this.v=1,G.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),G.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=O(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=L();i.p(n.dictionary),j(t,2,i.d())}}(r,this.o),this.v=0),n&&j(r,r.length-4,this.c.d()),this.ondata(r,n)},t}(),J=\"undefined\"!=typeof TextEncoder&&new TextEncoder,K=\"undefined\"!=typeof TextDecoder&&new TextDecoder;try{K.decode(F,{stream:!0})}catch(t){}var N=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(P(t),this.d=n||!1)},t}();function P(n,r){if(J)return J.encode(n);for(var e=n.length,i=new t(n.length+(n.length>>1)),a=0,s=function(t){i[a++]=t},o=0;oi.length){var f=new t(a+8+(e-o<<1));f.set(i),i=f}var h=n.charCodeAt(o);h<128||r?s(h):h<2048?(s(192|h>>6),s(128|63&h)):h>55295&&h<57344?(s(240|(h=65536+(1047552&h)|1023&n.charCodeAt(++o))>>18),s(128|h>>12&63),s(128|h>>6&63),s(128|63&h)):(s(224|h>>12),s(128|h>>6&63),s(128|63&h))}return b(i,0,a)}function Q(t){return function(t,n){n||(n={});var r=S(),e=t.length;r.p(t);var i=O(t,n,B(n),8),a=i.length;return q(i,n),j(i,a-8,r.d()),j(i,a-4,e),i}(P(t))}const R=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 N(((t,n)=>{this.deflate.push(t,n)})),this.stream.push(\"[\")}},V={clear:()=>{R.clear()},addEvent:t=>R.addEvent(t),finish:()=>R.finish(),compress:t=>Q(t)};addEventListener(\"message\",(function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in V&&\"function\"==typeof V[n])try{const t=V[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\nfunction e(){const e=new Blob([r]);return URL.createObjectURL(e)}\n\nconst CONSOLE_LEVELS = ['info', 'warn', 'error', 'log'] ;\nconst PREFIX = '[Replay] ';\n\nfunction _addBreadcrumb(message, level = 'info') {\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 makeReplayLogger() {\n let _capture = false;\n let _trace = false;\n\n const _logger = {\n exception: () => undefined,\n infoTick: () => undefined,\n setConfig: (opts) => {\n _capture = opts.captureExceptions;\n _trace = opts.traceInternals;\n },\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n _logger[name] = (...args) => {\n logger$1[name](PREFIX, ...args);\n if (_trace) {\n _addBreadcrumb(args.join(''), severityLevelFromString(name));\n }\n };\n });\n\n _logger.exception = (error, ...message) => {\n if (message.length && _logger.error) {\n _logger.error(...message);\n }\n\n logger$1.error(PREFIX, error);\n\n if (_capture) {\n captureException(error);\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 _logger.infoTick = (...args) => {\n logger$1.info(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 _logger[name] = () => undefined;\n });\n }\n\n return _logger ;\n}\n\nconst logger = makeReplayLogger();\n\n/** This error indicates that the event buffer size exceeded the limit.. */\nclass EventBufferSizeExceededError extends Error {\n constructor() {\n super(`Event buffer exceeded maximum size of ${REPLAY_MAX_EVENT_BUFFER_SIZE}.`);\n }\n}\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 */\nclass EventBufferArray {\n /** All the events that are buffered to be sent. */\n\n /** @inheritdoc */\n\n /** @inheritdoc */\n\n constructor() {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n this.waitForCheckout = false;\n }\n\n /** @inheritdoc */\n get hasEvents() {\n return this.events.length > 0;\n }\n\n /** @inheritdoc */\n get type() {\n return 'sync';\n }\n\n /** @inheritdoc */\n destroy() {\n this.events = [];\n }\n\n /** @inheritdoc */\n async addEvent(event) {\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 finish() {\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 clear() {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n getEarliestTimestamp() {\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\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nclass WorkerHandler {\n\n constructor(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 ensureReady() {\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 }) => {\n if ((data ).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 destroy() {\n DEBUG_BUILD && logger.info('Destroying compression worker');\n this._worker.terminate();\n }\n\n /**\n * Post message to worker and wait for response before resolving promise.\n */\n postMessage(method, arg) {\n const id = this._getAndIncrementId();\n\n return new Promise((resolve, reject) => {\n const listener = ({ data }) => {\n const response = data ;\n if (response.method !== method) {\n return;\n }\n\n // There can be multiple listeners for a single method, the id ensures\n // that the response matches the caller.\n if (response.id !== id) {\n return;\n }\n\n // At this point, we'll always want to remove listener regardless of result status\n this._worker.removeEventListener('message', listener);\n\n if (!response.success) {\n // TODO: Do some error handling, not sure what\n DEBUG_BUILD && logger.error('Error in compression worker: ', response.response);\n\n reject(new Error('Error in compression worker'));\n return;\n }\n\n resolve(response.response );\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 _getAndIncrementId() {\n return this._id++;\n }\n}\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nclass EventBufferCompressionWorker {\n /** @inheritdoc */\n\n /** @inheritdoc */\n\n constructor(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 get hasEvents() {\n return !!this._earliestTimestamp;\n }\n\n /** @inheritdoc */\n get type() {\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 ensureReady() {\n return this._worker.ensureReady();\n }\n\n /**\n * Destroy the event buffer.\n */\n destroy() {\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 addEvent(event) {\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 finish() {\n return this._finishRequest();\n }\n\n /** @inheritdoc */\n clear() {\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n\n // We do not wait on this, as we assume the order of messages is consistent for the worker\n this._worker.postMessage('clear').then(null, e => {\n DEBUG_BUILD && logger.exception(e, 'Sending \"clear\" message to worker failed', e);\n });\n }\n\n /** @inheritdoc */\n getEarliestTimestamp() {\n return this._earliestTimestamp;\n }\n\n /**\n * Send the event to the worker.\n */\n _sendEventToWorker(data) {\n return this._worker.postMessage('addEvent', data);\n }\n\n /**\n * Finish the request and return the compressed data from the worker.\n */\n async _finishRequest() {\n const response = await this._worker.postMessage('finish');\n\n this._earliestTimestamp = null;\n this._totalSize = 0;\n\n return response;\n }\n}\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 */\nclass EventBufferProxy {\n\n constructor(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 get waitForCheckout() {\n return this._used.waitForCheckout;\n }\n\n /** @inheritdoc */\n get type() {\n return this._used.type;\n }\n\n /** @inheritDoc */\n get hasEvents() {\n return this._used.hasEvents;\n }\n\n /** @inheritdoc */\n get hasCheckout() {\n return this._used.hasCheckout;\n }\n /** @inheritdoc */\n set hasCheckout(value) {\n this._used.hasCheckout = value;\n }\n\n /** @inheritdoc */\n // eslint-disable-next-line @typescript-eslint/adjacent-overload-signatures\n set waitForCheckout(value) {\n this._used.waitForCheckout = value;\n }\n\n /** @inheritDoc */\n destroy() {\n this._fallback.destroy();\n this._compression.destroy();\n }\n\n /** @inheritdoc */\n clear() {\n return this._used.clear();\n }\n\n /** @inheritdoc */\n getEarliestTimestamp() {\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 addEvent(event) {\n return this._used.addEvent(event);\n }\n\n /** @inheritDoc */\n async finish() {\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 ensureWorkerIsLoaded() {\n return this._ensureWorkerIsLoadedPromise;\n }\n\n /** Actually check if the worker has been loaded. */\n async _ensureWorkerIsLoaded() {\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 && logger.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 async _switchToCompressionWorker() {\n const { events, hasCheckout, waitForCheckout } = this._fallback;\n\n const addEventPromises = [];\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 && logger.exception(error, 'Failed to add events when switching buffers.');\n }\n }\n}\n\n/**\n * Create an event buffer for replays.\n */\nfunction createEventBuffer({\n useCompression,\n workerUrl: customWorkerUrl,\n}) {\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 && logger.info('Using simple buffer');\n return new EventBufferArray();\n}\n\nfunction _loadWorker(customWorkerUrl) {\n try {\n const workerUrl = customWorkerUrl || _getWorkerUrl();\n\n if (!workerUrl) {\n return;\n }\n\n DEBUG_BUILD && logger.info(`Using compression worker${customWorkerUrl ? ` from ${customWorkerUrl}` : ''}`);\n const worker = new Worker(workerUrl);\n return new EventBufferProxy(worker);\n } catch (error) {\n DEBUG_BUILD && logger.exception(error, 'Failed to create compression worker');\n // Fall back to use simple event buffer array\n }\n}\n\nfunction _getWorkerUrl() {\n if (typeof __SENTRY_EXCLUDE_REPLAY_WORKER__ === 'undefined' || !__SENTRY_EXCLUDE_REPLAY_WORKER__) {\n return e();\n }\n\n return '';\n}\n\n/** If sessionStorage is available. */\nfunction hasSessionStorage() {\n try {\n // This can throw, e.g. when being accessed in a sandboxed iframe\n return 'sessionStorage' in WINDOW && !!WINDOW.sessionStorage;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Removes the session from Session Storage and unsets session in replay instance\n */\nfunction clearSession(replay) {\n deleteSession();\n replay.session = undefined;\n}\n\n/**\n * Deletes a session from storage\n */\nfunction deleteSession() {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);\n } catch (e) {\n // Ignore potential SecurityError exceptions\n }\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 */\nfunction isSampled(sampleRate) {\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\n/**\n * Get a session with defaults & applied sampling.\n */\nfunction makeSession(session) {\n const now = Date.now();\n const id = session.id || uuid4();\n // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.\n const started = session.started || now;\n const lastActivity = session.lastActivity || now;\n const segmentId = session.segmentId || 0;\n const sampled = session.sampled;\n const previousSessionId = session.previousSessionId;\n\n return {\n id,\n started,\n lastActivity,\n segmentId,\n sampled,\n previousSessionId,\n };\n}\n\n/**\n * Save a session to session storage.\n */\nfunction saveSession(session) {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));\n } catch (e) {\n // Ignore potential SecurityError exceptions\n }\n}\n\n/**\n * Get the sampled status for a session based on sample rates & current sampled status.\n */\nfunction getSessionSampleType(sessionSampleRate, allowBuffering) {\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 */\nfunction createSession(\n { sessionSampleRate, allowBuffering, stickySession = false },\n { previousSessionId } = {},\n) {\n const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);\n const session = makeSession({\n sampled,\n previousSessionId,\n });\n\n if (stickySession) {\n saveSession(session);\n }\n\n return session;\n}\n\n/**\n * Fetches a session from storage\n */\nfunction fetchSession() {\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) ;\n\n DEBUG_BUILD && logger.infoTick('Loading existing session');\n\n return makeSession(sessionObj);\n } catch (e) {\n return null;\n }\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 */\nfunction isExpired(\n initialTime,\n expiry,\n targetTime = +new Date(),\n) {\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\n/**\n * Checks to see if session is expired\n */\nfunction isSessionExpired(\n session,\n {\n maxReplayDuration,\n sessionIdleExpire,\n targetTime = Date.now(),\n },\n) {\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\n/** If the session should be refreshed or not. */\nfunction shouldRefreshSession(\n session,\n { sessionIdleExpire, maxReplayDuration },\n) {\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\n/**\n * Get or create a session, when initializing the replay.\n * Returns a session that may be unsampled.\n */\nfunction loadOrCreateSession(\n {\n sessionIdleExpire,\n maxReplayDuration,\n previousSessionId,\n }\n\n,\n sessionOptions,\n) {\n const existingSession = sessionOptions.stickySession && fetchSession();\n\n // No session exists yet, just create a new one\n if (!existingSession) {\n DEBUG_BUILD && logger.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 && logger.infoTick('Session in sessionStorage is expired, creating new one...');\n return createSession(sessionOptions, { previousSessionId: existingSession.id });\n}\n\nfunction isCustomEvent(event) {\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 */\nfunction addEventSync(replay, event, isCheckout) {\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 */\nfunction addEvent(\n replay,\n event,\n isCheckout,\n) {\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,\n event,\n isCheckout,\n) {\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\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 const client = getClient();\n\n if (client) {\n client.recordDroppedEvent('internal_sdk_error', 'replay');\n }\n }\n}\n\n/** Exported only for tests. */\nfunction shouldAddEvent(replay, event) {\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 logger.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,\n callback,\n) {\n try {\n if (typeof callback === 'function' && isCustomEvent(event)) {\n return callback(event);\n }\n } catch (error) {\n DEBUG_BUILD &&\n logger.exception(error, 'An error occurred in the `beforeAddRecordingEvent` callback, skipping the event...');\n return null;\n }\n\n return event;\n}\n\n/** If the event is an error event */\nfunction isErrorEvent(event) {\n return !event.type;\n}\n\n/** If the event is a transaction event */\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\n/** If the event is an replay event */\nfunction isReplayEvent(event) {\n return event.type === 'replay_event';\n}\n\n/** If the event is a feedback event */\nfunction isFeedbackEvent(event) {\n return event.type === 'feedback';\n}\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nfunction handleAfterSendEvent(replay) {\n return (event, sendResponse) => {\n if (!replay.isEnabled() || (!isErrorEvent(event) && !isTransactionEvent(event))) {\n return;\n }\n\n const statusCode = sendResponse && sendResponse.statusCode;\n\n // We only want to do stuff on successful error sending, otherwise you get error replays without errors attached\n // If not using the base transport, we allow `undefined` response (as a custom transport may not implement this correctly yet)\n // If we do use the base transport, we skip if we encountered an non-OK status code\n if (!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, event) {\n const replayContext = replay.getContext();\n\n // Collect traceIds in _context regardless of `recordingMode`\n // In error mode, _context gets cleared on every checkout\n // We limit to max. 100 transactions linked\n if (event.contexts && event.contexts.trace && event.contexts.trace.trace_id && replayContext.traceIds.size < 100) {\n replayContext.traceIds.add(event.contexts.trace.trace_id );\n }\n}\n\nfunction handleErrorEvent(replay, event) {\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$3(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\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nfunction handleBeforeSendEvent(replay) {\n return (event) => {\n if (!replay.isEnabled() || !isErrorEvent(event)) {\n return;\n }\n\n handleHydrationError(replay, event);\n };\n}\n\nfunction handleHydrationError(replay, event) {\n const exceptionValue =\n event.exception && event.exception.values && event.exception.values[0] && 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\n/**\n * Handle breadcrumbs that Sentry captures, and make sure to capture relevant breadcrumbs to Replay as well.\n */\nfunction handleBreadcrumbs(replay) {\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, breadcrumb) {\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. */\nfunction normalizeBreadcrumb(breadcrumb) {\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 */\nfunction normalizeConsoleBreadcrumb(\n breadcrumb,\n) {\n const args = breadcrumb.data && breadcrumb.data.arguments;\n\n if (!Array.isArray(args) || args.length === 0) {\n return createBreadcrumb(breadcrumb);\n }\n\n let isTruncated = false;\n\n // Avoid giant args captures\n const normalizedArgs = args.map(arg => {\n if (!arg) {\n return arg;\n }\n if (typeof arg === 'string') {\n if (arg.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n\n return arg;\n }\n if (typeof arg === 'object') {\n try {\n const normalizedArg = normalize(arg, 7);\n const stringified = JSON.stringify(normalizedArg);\n if (stringified.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n // We use the pretty printed JSON string here as a base\n return `${JSON.stringify(normalizedArg, null, 2).slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n return normalizedArg;\n } catch (e) {\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) {\n return !!breadcrumb.category;\n}\n\n/**\n * Returns true if we think the given event is an error originating inside of rrweb.\n */\nfunction isRrwebError(event, hint) {\n if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) {\n return false;\n }\n\n // @ts-expect-error this may be set by rrweb when it finds errors\n if (hint.originalException && hint.originalException.__rrweb__) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Reset the `replay_id` field on the DSC.\n */\nfunction resetReplayIdOnDynamicSamplingContext() {\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 ).replay_id;\n }\n}\n\n/**\n * Add a feedback breadcrumb event to replay.\n */\nfunction addFeedbackBreadcrumb(replay, event) {\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 } );\n\n return false;\n });\n}\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 */\nfunction shouldSampleForBufferEvent(replay, event) {\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\n/**\n * Returns a listener to be added to `addEventProcessor(listener)`.\n */\nfunction handleGlobalEventListener(replay) {\n return Object.assign(\n (event, hint) => {\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 && logger.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 return event;\n },\n { id: 'Replay' },\n );\n}\n\n/**\n * Create a \"span\" for each performance entry.\n */\nfunction createPerformanceSpans(\n replay,\n entries,\n) {\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\nfunction handleHistory(handlerData) {\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 */\nfunction handleHistorySpanListener(replay) {\n return (handlerData) => {\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\n/**\n * Check whether a given request URL should be filtered out. This is so we\n * don't log Sentry ingest requests.\n */\nfunction shouldFilterRequest(replay, url) {\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\n/** Add a performance entry breadcrumb */\nfunction addNetworkBreadcrumb(\n replay,\n result,\n) {\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\n/** Get the size of a body. */\nfunction getBodySize(body) {\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 (e) {\n // just return undefined\n }\n\n return undefined;\n}\n\n/** Convert a Content-Length header to number/undefined. */\nfunction parseContentLengthHeader(header) {\n if (!header) {\n return undefined;\n }\n\n const size = parseInt(header, 10);\n return isNaN(size) ? undefined : size;\n}\n\n/** Get the string representation of a body. */\nfunction getBodyString(body) {\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 && logger.exception(error, 'Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && logger.info('Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\n/** Merge a warning into an existing network request/response. */\nfunction mergeWarning(\n info,\n warning,\n) {\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. */\nfunction makeNetworkReplayBreadcrumb(\n type,\n data,\n) {\n if (!data) {\n return null;\n }\n\n const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data;\n\n const result = {\n type,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: dropUndefinedKeys({\n method,\n statusCode,\n request,\n response,\n }),\n };\n\n return result;\n}\n\n/** Build the request or response part of a replay network breadcrumb that was skipped. */\nfunction buildSkippedNetworkRequestOrResponse(bodySize) {\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. */\nfunction buildNetworkRequestOrResponse(\n headers,\n bodySize,\n body,\n) {\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 = {\n headers,\n size: bodySize,\n };\n\n const { body: normalizedBody, warnings } = normalizeNetworkBody(body);\n info.body = normalizedBody;\n if (warnings && warnings.length > 0) {\n info._meta = {\n warnings,\n };\n }\n\n return info;\n}\n\n/** Filter a set of headers */\nfunction getAllowedHeaders(headers, allowedHeaders) {\n return Object.entries(headers).reduce((filteredHeaders, [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 _serializeFormData(formData) {\n // This is a bit simplified, but gives us a decent estimate\n // This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'\n // @ts-expect-error passing FormData to URLSearchParams actually works\n return new URLSearchParams(formData).toString();\n}\n\nfunction normalizeNetworkBody(body)\n\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 (e2) {\n // fall back to just send the body as string\n }\n }\n\n return {\n body,\n };\n}\n\nfunction _strIsProbablyJson(str) {\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. */\nfunction urlMatches(url, urls) {\n const fullUrl = getFullUrl(url);\n\n return stringMatchesSomePattern(fullUrl, urls);\n}\n\n/** exported for tests */\nfunction getFullUrl(url, baseURI = WINDOW.document.baseURI) {\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\n/**\n * Capture a fetch breadcrumb to a replay.\n * This adds additional data (where appropriate).\n */\nasync function captureFetchBreadcrumbToReplay(\n breadcrumb,\n hint,\n options\n\n,\n) {\n try {\n const data = await _prepareFetchData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.fetch', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && logger.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 */\nfunction enrichFetchBreadcrumb(\n breadcrumb,\n hint,\n) {\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,\n hint,\n options,\n) {\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 },\n input,\n requestBodySize,\n) {\n const headers = input ? getRequestHeaders(input, networkRequestHeaders) : {};\n\n if (!networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);\n }\n\n // We only want to transmit string or string-like bodies\n const requestBody = _getFetchRequestArgBody(input);\n const [bodyStr, warning] = getBodyString(requestBody);\n const data = buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);\n\n if (warning) {\n return mergeWarning(data, warning);\n }\n\n return data;\n}\n\n/** Exported only for tests. */\nasync function _getResponseInfo(\n captureDetails,\n {\n networkCaptureBodies,\n networkResponseHeaders,\n },\n response,\n responseBodySize,\n) {\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,\n {\n networkCaptureBodies,\n responseBodySize,\n captureDetails,\n headers,\n }\n\n,\n) {\n try {\n const size =\n bodyText && 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 && logger.exception(error, 'Failed to serialize response body');\n // fallback\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n}\n\nasync function _parseFetchResponseBody(response) {\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 && logger.warn('Parsing text body from response timed out');\n return [undefined, 'BODY_PARSE_TIMEOUT'];\n }\n\n DEBUG_BUILD && logger.exception(error, 'Failed to get text body from response');\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n}\n\nfunction _getFetchRequestArgBody(fetchArgs = []) {\n // We only support getting the body from the fetch options\n if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== 'object') {\n return undefined;\n }\n\n return (fetchArgs[1] ).body;\n}\n\nfunction getAllHeaders(headers, allowedHeaders) {\n const allHeaders = {};\n\n allowedHeaders.forEach(header => {\n if (headers.get(header)) {\n allHeaders[header] = headers.get(header) ;\n }\n });\n\n return allHeaders;\n}\n\nfunction getRequestHeaders(fetchArgs, allowedHeaders) {\n if (fetchArgs.length === 1 && typeof fetchArgs[0] !== 'string') {\n return getHeadersFromOptions(fetchArgs[0] , allowedHeaders);\n }\n\n if (fetchArgs.length === 2) {\n return getHeadersFromOptions(fetchArgs[1] , allowedHeaders);\n }\n\n return {};\n}\n\nfunction getHeadersFromOptions(\n input,\n allowedHeaders,\n) {\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) {\n try {\n // We have to clone this, as the body can only be read once\n return response.clone();\n } catch (error) {\n // this can throw if the response was already consumed before\n DEBUG_BUILD && logger.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) {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout$3(() => 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) {\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\n/**\n * Capture an XHR breadcrumb to a replay.\n * This adds additional data (where appropriate).\n */\nasync function captureXhrBreadcrumbToReplay(\n breadcrumb,\n hint,\n options,\n) {\n try {\n const data = _prepareXhrData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.xhr', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && logger.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 */\nfunction enrichXhrBreadcrumb(\n breadcrumb,\n hint,\n) {\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,\n hint,\n options,\n) {\n const now = Date.now();\n const { startTimestamp = now, endTimestamp = now, input, xhr } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n if (!url) {\n return null;\n }\n\n if (!xhr || !urlMatches(url, options.networkDetailAllowUrls) || urlMatches(url, options.networkDetailDenyUrls)) {\n const request = buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = buildSkippedNetworkRequestOrResponse(responseBodySize);\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n }\n\n const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];\n const networkRequestHeaders = xhrInfo\n ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)\n : {};\n const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.networkResponseHeaders);\n\n const [requestBody, requestWarning] = options.networkCaptureBodies ? getBodyString(input) : [undefined];\n const [responseBody, responseWarning] = options.networkCaptureBodies ? _getXhrResponseBody(xhr) : [undefined];\n\n const request = buildNetworkRequestOrResponse(networkRequestHeaders, requestBodySize, requestBody);\n const response = buildNetworkRequestOrResponse(networkResponseHeaders, responseBodySize, responseBody);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request: requestWarning ? mergeWarning(request, requestWarning) : request,\n response: responseWarning ? mergeWarning(response, responseWarning) : response,\n };\n}\n\nfunction getResponseHeaders(xhr) {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc, line) => {\n const [key, value] = line.split(': ') ;\n if (value) {\n acc[key.toLowerCase()] = value;\n }\n return acc;\n }, {});\n}\n\nfunction _getXhrResponseBody(xhr) {\n // We collect errors that happen, but only log them if we can't get any response body\n const errors = [];\n\n try {\n return [xhr.responseText];\n } catch (e) {\n errors.push(e);\n }\n\n // Try to manually parse the response body, if responseText fails\n try {\n return _parseXhrResponse(xhr.response, xhr.responseType);\n } catch (e) {\n errors.push(e);\n }\n\n DEBUG_BUILD && logger.warn('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 */\nfunction _parseXhrResponse(\n body,\n responseType,\n) {\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 && logger.exception(error, 'Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && logger.info('Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\nfunction _getBodySize(\n body,\n responseType,\n) {\n try {\n const bodyStr = responseType === 'json' && body && typeof body === 'object' ? JSON.stringify(body) : body;\n return getBodySize(bodyStr);\n } catch (e2) {\n return undefined;\n }\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 */\nfunction handleNetworkBreadcrumbs(replay) {\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 = {\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 (e2) {\n // Do nothing\n }\n}\n\n/** just exported for tests */\nfunction beforeAddNetworkBreadcrumb(\n options,\n breadcrumb,\n hint,\n) {\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 && logger.exception(e, 'Error when enriching network breadcrumb');\n }\n}\n\nfunction _isXhrBreadcrumb(breadcrumb) {\n return breadcrumb.category === 'xhr';\n}\n\nfunction _isFetchBreadcrumb(breadcrumb) {\n return breadcrumb.category === 'fetch';\n}\n\nfunction _isXhrHint(hint) {\n return hint && hint.xhr;\n}\n\nfunction _isFetchHint(hint) {\n return hint && hint.response;\n}\n\n/**\n * Add global listeners that cannot be removed.\n */\nfunction addGlobalListeners(replay) {\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) => {\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 flush replay\n client.on('beforeSendFeedback', (feedbackEvent, options) => {\n const replayId = replay.getSessionId();\n if (options && options.includeReplay && replay.isEnabled() && replayId) {\n // This should never reject\n if (feedbackEvent.contexts && feedbackEvent.contexts.feedback) {\n feedbackEvent.contexts.feedback.replay_id = replayId;\n }\n }\n });\n }\n}\n\n/**\n * Create a \"span\" for the total amount of memory being used by JS objects\n * (including v8 internal objects).\n */\nasync function addMemoryEntry(replay) {\n // window.performance.memory is a non-standard API and doesn't work on all browsers, so we try-catch this\n try {\n return Promise.all(\n createPerformanceSpans(replay, [\n // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)\n createMemoryEntry(WINDOW.performance.memory),\n ]),\n );\n } catch (error) {\n // Do nothing\n return [];\n }\n}\n\nfunction createMemoryEntry(memoryEntry) {\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\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 */\nfunction debounce(func, wait, options) {\n let callbackReturnValue;\n\n let timerId;\n let maxTimerId;\n\n const maxWait = options && options.maxWait ? Math.max(options.maxWait, wait) : 0;\n\n function invokeFunc() {\n cancelTimers();\n callbackReturnValue = func();\n return callbackReturnValue;\n }\n\n function cancelTimers() {\n timerId !== undefined && clearTimeout(timerId);\n maxTimerId !== undefined && clearTimeout(maxTimerId);\n timerId = maxTimerId = undefined;\n }\n\n function flush() {\n if (timerId !== undefined || maxTimerId !== undefined) {\n return invokeFunc();\n }\n return callbackReturnValue;\n }\n\n function debounced() {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeout$3(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeout$3(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n}\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 */\nfunction getHandleRecordingEmit(replay) {\n let hadFirstEvent = false;\n\n return (event, _isCheckout) => {\n // If this is false, it means session is expired, create and a new session and wait for checkout\n if (!replay.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && logger.warn('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) {\n const earliestEvent = replay.eventBuffer.getEarliestTimestamp();\n if (earliestEvent) {\n DEBUG_BUILD &&\n logger.info(`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 && 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 */\nfunction createOptionsEvent(replay) {\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, isCheckout) {\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/**\n * Create a replay envelope ready to be sent.\n * This includes both the replay event, as well as the recording data.\n */\nfunction createReplayEnvelope(\n replayEvent,\n recordingData,\n dsn,\n tunnel,\n) {\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\n/**\n * Prepare the recording data ready to be sent.\n */\nfunction prepareRecordingData({\n recordingData,\n headers,\n}\n\n) {\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\n/**\n * Prepare a replay event & enrich it with the SDK metadata.\n */\nasync function prepareReplayEvent({\n client,\n scope,\n replayId: event_id,\n event,\n}\n\n) {\n const integrations =\n typeof client._integrations === 'object' && client._integrations !== null && !Array.isArray(client._integrations)\n ? Object.keys(client._integrations)\n : undefined;\n\n const eventHint = { 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 )) ;\n\n // If e.g. a global event processor returned null\n if (!preparedEvent) {\n return null;\n }\n\n // This normally happens in browser client \"_prepareEvent\"\n // but since we do not use this private method from the client, but rather the plain import\n // we need to do this manually.\n preparedEvent.platform = preparedEvent.platform || 'javascript';\n\n // extract the SDK name because `client._prepareEvent` doesn't add it to the event\n const metadata = client.getSdkMetadata();\n const { name, version } = (metadata && metadata.sdk) || {};\n\n preparedEvent.sdk = {\n ...preparedEvent.sdk,\n name: name || 'sentry.javascript.unknown',\n version: version || '0.0.0',\n };\n\n return preparedEvent;\n}\n\n/**\n * Send replay attachment using `fetch()`\n */\nasync function sendReplayRequest({\n recordingData,\n replayId,\n segmentId: segment_id,\n eventContext,\n timestamp,\n session,\n}) {\n const preparedRecordingData = prepareRecordingData({\n recordingData,\n headers: {\n segment_id,\n },\n });\n\n const { urls, errorIds, traceIds, initialTimestamp } = eventContext;\n\n const client = getClient();\n const scope = getCurrentScope();\n const transport = client && client.getTransport();\n const dsn = client && client.getDsn();\n\n if (!client || !transport || !dsn || !session.sampled) {\n return resolvedSyncPromise({});\n }\n\n const baseEvent = {\n type: REPLAY_EVENT_NAME,\n replay_start_timestamp: initialTimestamp / 1000,\n timestamp: timestamp / 1000,\n error_ids: errorIds,\n trace_ids: traceIds,\n urls,\n replay_id: replayId,\n segment_id,\n replay_type: session.sampled,\n };\n\n const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });\n\n if (!replayEvent) {\n // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions\n client.recordDroppedEvent('event_processor', 'replay', baseEvent);\n DEBUG_BUILD && logger.info('An event processor returned `null`, will not send event.');\n return resolvedSyncPromise({});\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;\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 (e) {\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 */\nclass TransportStatusCodeError extends Error {\n constructor(statusCode) {\n super(`Transport returned status code ${statusCode}`);\n }\n}\n\n/**\n * This error indicates that we hit a rate limit API error.\n */\nclass RateLimitError extends Error {\n\n constructor(rateLimits) {\n super('Rate limit hit');\n this.rateLimits = rateLimits;\n }\n}\n\n/**\n * Finalize and send the current replay event to Sentry\n */\nasync function sendReplay(\n replayData,\n retryConfig = {\n count: 0,\n interval: RETRY_BASE_INTERVAL,\n },\n) {\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 (e) {\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$3(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\nconst THROTTLED = '__THROTTLED';\nconst 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\nfunction throttle(\n fn,\n maxCount,\n durationSeconds,\n) {\n const counter = new Map();\n\n const _cleanup = (now) => {\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 = () => {\n return [...counter.values()].reduce((a, b) => a + b, 0);\n };\n\n let isThrottled = false;\n\n return (...rest) => {\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\n/* eslint-disable max-lines */ // TODO: We might want to split this file up\n\n/**\n * The main replay container class, which holds all the state and methods for recording and sending replays.\n */\nclass ReplayContainer {\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\n /**\n * The current or last active span.\n * This is only available when performance is enabled.\n */\n\n /**\n * These are here so we can overwrite them in tests etc.\n * @hidden\n */\n\n /** The replay has to be manually started, because no sample rate (neither session or error) was provided. */\n\n /**\n * Options to pass to `rrweb.record()`\n */\n\n /**\n * Timestamp of the last user activity. This lives across sessions.\n */\n\n /**\n * Is the integration currently active?\n */\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\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\n /**\n * Function to stop recording\n */\n\n /**\n * Internal use for canvas recording options\n */\n\n constructor({\n options,\n recordingOptions,\n }\n\n) {ReplayContainer.prototype.__init.call(this);ReplayContainer.prototype.__init2.call(this);ReplayContainer.prototype.__init3.call(this);ReplayContainer.prototype.__init4.call(this);ReplayContainer.prototype.__init5.call(this);ReplayContainer.prototype.__init6.call(this);\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 } ;\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, isCheckout) => 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 = 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 logger w/ experimental options\n if (DEBUG_BUILD) {\n const experiments = options._experiments;\n logger.setConfig({\n captureExceptions: !!experiments.captureExceptions,\n traceInternals: !!experiments.traceInternals,\n });\n }\n }\n\n /** Get the event context. */\n getContext() {\n return this._context;\n }\n\n /** If recording is currently enabled. */\n isEnabled() {\n return this._isEnabled;\n }\n\n /** If recording is currently paused. */\n isPaused() {\n return this._isPaused;\n }\n\n /**\n * Determine if canvas recording is enabled\n */\n isRecordingCanvas() {\n return Boolean(this._canvas);\n }\n\n /** Get the replay integration options. */\n getOptions() {\n return this._options;\n }\n\n /** A wrapper to conditionally capture exceptions. */\n handleException(error) {\n DEBUG_BUILD && logger.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 initializeSampling(previousSessionId) {\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 && logger.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 && logger.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 start() {\n if (this._isEnabled && this.recordingMode === 'session') {\n DEBUG_BUILD && logger.info('Recording is already in progress');\n return;\n }\n\n if (this._isEnabled && this.recordingMode === 'buffer') {\n DEBUG_BUILD && logger.info('Buffering is in progress, call `flush()` to save the replay');\n return;\n }\n\n DEBUG_BUILD && logger.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\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 startBuffering() {\n if (this._isEnabled) {\n DEBUG_BUILD && logger.info('Buffering is in progress, call `flush()` to save the replay');\n return;\n }\n\n DEBUG_BUILD && logger.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 startRecording() {\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(360000, this._options._experiments.continuousCheckout),\n }),\n emit: getHandleRecordingEmit(this),\n onMutation: this._onMutationHandler,\n ...(canvasOptions\n ? {\n recordCanvas: canvasOptions.recordCanvas,\n getCanvasManager: canvasOptions.getCanvasManager,\n sampling: canvasOptions.sampling,\n dataURLOptions: canvasOptions.dataURLOptions,\n }\n : {}),\n });\n } catch (err) {\n this.handleException(err);\n }\n }\n\n /**\n * Stops the recording, if it was running.\n *\n * Returns true if it was previously stopped, or is now stopped,\n * otherwise false.\n */\n stopRecording() {\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 async stop({ forceFlush = false, reason } = {}) {\n if (!this._isEnabled) {\n return;\n }\n\n // We can't move `_isEnabled` after awaiting a flush, otherwise we can\n // enter into an infinite loop when `stop()` is called while flushing.\n this._isEnabled = false;\n\n try {\n DEBUG_BUILD && logger.info(`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 && 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 pause() {\n if (this._isPaused) {\n return;\n }\n\n this._isPaused = true;\n this.stopRecording();\n\n DEBUG_BUILD && logger.info('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 resume() {\n if (!this._isPaused || !this._checkSession()) {\n return;\n }\n\n this._isPaused = false;\n this.startRecording();\n\n DEBUG_BUILD && logger.info('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 async sendBufferedReplayOrFlush({ continueRecording = true } = {}) {\n if (this.recordingMode === 'session') {\n return this.flushImmediate();\n }\n\n const activityTime = Date.now();\n\n DEBUG_BUILD && logger.info('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 ) === 'session') {\n return;\n }\n\n // Re-start recording in session-mode\n this.recordingMode = 'session';\n\n // Once this session ends, we do not want to refresh it\n if (this.session) {\n this._updateUserActivity(activityTime);\n this._updateSessionActivity(activityTime);\n this._maybeSaveSession();\n }\n\n this.startRecording();\n }\n\n /**\n * We want to batch uploads of replay events. Save events only if\n * `` milliseconds have elapsed since the last event\n * *OR* if `` milliseconds have elapsed.\n *\n * Accepts a callback to perform side-effects and returns true to stop batch\n * processing and hand back control to caller.\n */\n addUpdate(cb) {\n // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)\n const cbResult = cb();\n\n // If this option is turned on then we will only want to call `flush`\n // explicitly\n if (this.recordingMode === 'buffer') {\n return;\n }\n\n // If callback is true, we do not want to continue with flushing -- the\n // caller will need to handle it.\n if (cbResult === true) {\n return;\n }\n\n // addUpdate is called quite frequently - use _debouncedFlush so that it\n // respects the flush delays and does not flush immediately\n this._debouncedFlush();\n }\n\n /**\n * Updates the user activity timestamp and resumes recording. This should be\n * called in an event handler for a user action that we consider as the user\n * being \"active\" (e.g. a mouse click).\n */\n triggerUserActivity() {\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 updateUserActivity() {\n this._updateUserActivity();\n this._updateSessionActivity();\n }\n\n /**\n * Only flush if `this.recordingMode === 'session'`\n */\n conditionalFlush() {\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 flush() {\n return this._debouncedFlush() ;\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 flushImmediate() {\n this._debouncedFlush();\n // `.flush` is provided by the debounced function, analogously to lodash.debounce\n return this._debouncedFlush.flush() ;\n }\n\n /**\n * Cancels queued up flushes.\n */\n cancelFlush() {\n this._debouncedFlush.cancel();\n }\n\n /** Get the current session (=replay) ID */\n getSessionId() {\n return this.session && this.session.id;\n }\n\n /**\n * Checks if recording should be stopped due to user inactivity. Otherwise\n * check if session is expired and create a new session if so. Triggers a new\n * full snapshot on new session.\n *\n * Returns true if session is not expired, false otherwise.\n * @hidden\n */\n checkAndHandleExpiredSession() {\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 setInitialState() {\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 throttledAddEvent(\n event,\n isCheckout,\n ) {\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 getCurrentRoute() {\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 _initializeRecording() {\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 _initializeSessionForSampling(previousSessionId) {\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 _checkSession() {\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 async _refreshSession(session) {\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 _addListeners() {\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 _removeListeners() {\n try {\n WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);\n\n WINDOW.removeEventListener('blur', this._handleWindowBlur);\n WINDOW.removeEventListener('focus', this._handleWindowFocus);\n WINDOW.removeEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.removeListeners();\n }\n\n if (this._performanceCleanupCallback) {\n this._performanceCleanupCallback();\n }\n } catch (err) {\n this.handleException(err);\n }\n }\n\n /**\n * Handle when visibility of the page content changes. Opening a new tab will\n * cause the state to change to hidden because of content of current page will\n * be hidden. Likewise, moving a different window to cover the contents of the\n * page will also trigger a change to a hidden state.\n */\n __init() {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 __init2() {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 /**\n * Handle when page is focused\n */\n __init3() {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 __init4() {this._handleKeyboardEvent = (event) => {\n handleKeyboardEvent(this, event);\n };}\n\n /**\n * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)\n */\n _doChangeToBackgroundTasks(breadcrumb) {\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 _doChangeToForegroundTasks(breadcrumb) {\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 && logger.info('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 _updateUserActivity(_lastActivity = Date.now()) {\n this._lastActivity = _lastActivity;\n }\n\n /**\n * Updates the session's last activity timestamp\n */\n _updateSessionActivity(_lastActivity = Date.now()) {\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 _createCustomBreadcrumb(breadcrumb) {\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 _addPerformanceEntries() {\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 _clearContext() {\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 _updateInitialTimestampFromEventBuffer() {\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 _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 async _runFlush() {\n const replayId = this.getSessionId();\n\n if (!this.session || !this.eventBuffer || !replayId) {\n DEBUG_BUILD && logger.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 || !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 + 30000) {\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 __init5() {this._flush = async ({\n force = false,\n }\n\n = {}) => {\n if (!this._isEnabled && !force) {\n // This can happen if e.g. the replay was stopped because of exceeding the retry limit\n return;\n }\n\n if (!this.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && logger.error('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 + 5000;\n if (tooShort || tooLong) {\n DEBUG_BUILD &&\n logger.info(\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 && logger.info('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 _maybeSaveSession() {\n if (this.session && this._options.stickySession) {\n saveSession(this.session);\n }\n }\n\n /** Handler for rrweb.record.onMutation */\n __init6() {this._onMutationHandler = (mutations) => {\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\nfunction getOption(selectors, defaultSelectors) {\n return [\n ...selectors,\n // sentry defaults\n ...defaultSelectors,\n ].join(',');\n}\n\n/**\n * Returns privacy related configuration for use in rrweb\n */\nfunction getPrivacyOptions({ mask, unmask, block, unblock, ignore }) {\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 = {\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\n/**\n * Masks an attribute if necessary, otherwise return attribute value as-is.\n */\nfunction maskAttribute({\n el,\n key,\n maskAttributes,\n maskAllText,\n privacyOptions,\n value,\n}) {\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\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 */\nconst replayIntegration = ((options) => {\n return new Replay(options);\n}) ;\n\n/**\n * Replay integration\n *\n * TODO: Rewrite this to be functional integration\n * Exported for tests.\n */\nclass Replay {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Replay';}\n\n /**\n * @inheritDoc\n */\n\n /**\n * Options to pass to `rrweb.record()`\n */\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\n 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 = 10000,\n\n slowClickTimeout = 7000,\n slowClickIgnoreSelectors = [],\n\n networkDetailAllowUrls = [],\n networkDetailDenyUrls = [],\n networkCaptureBodies = true,\n networkRequestHeaders = [],\n networkResponseHeaders = [],\n\n mask = [],\n maskAttributes = ['title', 'placeholder'],\n unmask = [],\n block = [],\n unblock = [],\n ignore = [],\n maskFn,\n\n beforeAddRecordingEvent,\n beforeErrorSampling,\n onError,\n } = {}) {\n this.name = Replay.id;\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, value, el) =>\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) => {\n try {\n err.__rrweb__ = true;\n } catch (error) {\n // ignore errors here\n // this can happen if the error is frozen or does not allow mutation for other reasons\n }\n },\n };\n\n this._initialOptions = {\n flushMinDelay,\n flushMaxDelay,\n minReplayDuration: Math.min(minReplayDuration, MIN_REPLAY_DURATION_LIMIT),\n maxReplayDuration: Math.min(maxReplayDuration, MAX_REPLAY_DURATION),\n stickySession,\n 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 }\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 get _isInitialized() {\n return _initialized;\n }\n\n /** Update _isInitialized */\n set _isInitialized(value) {\n _initialized = value;\n }\n\n /**\n * Setup and initialize replay container\n */\n afterAllSetup(client) {\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 start() {\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 startBuffering() {\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 stop() {\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 flush(options) {\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 getReplayId() {\n if (!this._replay || !this._replay.isEnabled()) {\n return;\n }\n\n return this._replay.getSessionId();\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 getRecordingMode() {\n if (!this._replay || !this._replay.isEnabled()) {\n return;\n }\n\n return this._replay.recordingMode;\n }\n\n /**\n * Initializes replay.\n */\n _initialize(client) {\n if (!this._replay) {\n return;\n }\n\n this._maybeLoadFromReplayCanvasIntegration(client);\n this._replay.initializeSampling();\n }\n\n /** Setup the integration. */\n _setup(client) {\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 _maybeLoadFromReplayCanvasIntegration(client) {\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')\n\n;\n if (!canvasIntegration) {\n return;\n }\n\n this._replay['_canvas'] = canvasIntegration.getOptions();\n } catch (e) {\n // ignore errors here\n }\n /* eslint-enable @typescript-eslint/no-non-null-assertion */\n }\n}Replay.__initStatic();\n\n/** Parse Replay-related options from SDK options */\nfunction loadReplayOptionsFromClient(initialOptions, client) {\n const opt = client.getOptions() ;\n\n const finalOptions = {\n sessionSampleRate: 0,\n errorSampleRate: 0,\n ...dropUndefinedKeys(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) {\n return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];\n}\n\n/**\n * This is a small utility to get a type-safe instance of the Replay integration.\n */\nfunction getReplay() {\n const client = getClient();\n return client && client.getIntegrationByName('Replay');\n}\n\nexport { getReplay, replayIntegration };\n//# sourceMappingURL=index.js.map\n","import { addXhrInstrumentationHandler, addPerformanceInstrumentationHandler, SENTRY_XHR_DATA_KEY } from '@sentry-internal/browser-utils';\nimport { addFetchEndInstrumentationHandler, addFetchInstrumentationHandler, instrumentFetchRequest, parseUrl, spanToJSON, browserPerformanceTimeOrigin, hasTracingEnabled, setHttpStatus, getActiveSpan, startInactiveSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP, SentryNonRecordingSpan, getTraceData, stringMatchesSomePattern } from '@sentry/core';\nimport { WINDOW } from '../helpers.js';\n\n/** Options for Request Instrumentation */\n\nconst responseToSpanId = new WeakMap();\nconst spanIdToEndTimestamp = new Map();\n\nconst defaultRequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n enableHTTPTimings: true,\n trackFetchStreamPerformance: false,\n};\n\n/** Registers span creators for xhr and fetch requests */\nfunction instrumentOutgoingRequests(client, _options) {\n const {\n traceFetch,\n traceXHR,\n trackFetchStreamPerformance,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n tracePropagationTargets,\n } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n trackFetchStreamPerformance: defaultRequestInstrumentationOptions.trackFetchStreamPerformance,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_) => true;\n\n const shouldAttachHeadersWithTargets = (url) => shouldAttachHeaders(url, tracePropagationTargets);\n\n const spans = {};\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\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\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n\n if (traceXHR) {\n addXhrInstrumentationHandler(handlerData => {\n const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n}\n\nfunction isPerformanceResourceTiming(entry) {\n return (\n entry.entryType === 'resource' &&\n 'initiatorType' in entry &&\n typeof (entry ).nextHopProtocol === 'string' &&\n (entry.initiatorType === 'fetch' || entry.initiatorType === 'xmlhttprequest')\n );\n}\n\n/**\n * Creates a temporary observer to listen to the next fetch/xhr resourcing timings,\n * so that when timings hit their per-browser limit they don't need to be removed.\n *\n * @param span A span that has yet to be finished, must contain `url` on data.\n */\nfunction addHTTPTimings(span) {\n const { url } = spanToJSON(span).data || {};\n\n if (!url || typeof url !== 'string') {\n return;\n }\n\n const cleanup = addPerformanceInstrumentationHandler('resource', ({ entries }) => {\n entries.forEach(entry => {\n if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) {\n const spanData = resourceTimingEntryToSpanData(entry);\n spanData.forEach(data => span.setAttribute(...data));\n // In the next tick, clean this handler up\n // We have to wait here because otherwise this cleans itself up before it is fully done\n setTimeout(cleanup);\n }\n });\n });\n}\n\n/**\n * Converts ALPN protocol ids to name and version.\n *\n * (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids)\n * @param nextHopProtocol PerformanceResourceTiming.nextHopProtocol\n */\nfunction extractNetworkProtocol(nextHopProtocol) {\n let name = 'unknown';\n let version = 'unknown';\n let _name = '';\n for (const char of nextHopProtocol) {\n // http/1.1 etc.\n if (char === '/') {\n [name, version] = nextHopProtocol.split('/') ;\n break;\n }\n // h2, h3 etc.\n if (!isNaN(Number(char))) {\n name = _name === 'h' ? 'http' : _name;\n version = nextHopProtocol.split(_name)[1] ;\n break;\n }\n _name += char;\n }\n if (_name === nextHopProtocol) {\n // webrtc, ftp, etc.\n name = _name;\n }\n return { name, version };\n}\n\nfunction getAbsoluteTime(time = 0) {\n return ((browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1000;\n}\n\nfunction resourceTimingEntryToSpanData(resourceTiming) {\n const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol);\n\n const timingSpanData = [];\n\n timingSpanData.push(['network.protocol.version', version], ['network.protocol.name', name]);\n\n if (!browserPerformanceTimeOrigin) {\n return timingSpanData;\n }\n return [\n ...timingSpanData,\n ['http.request.redirect_start', getAbsoluteTime(resourceTiming.redirectStart)],\n ['http.request.fetch_start', getAbsoluteTime(resourceTiming.fetchStart)],\n ['http.request.domain_lookup_start', getAbsoluteTime(resourceTiming.domainLookupStart)],\n ['http.request.domain_lookup_end', getAbsoluteTime(resourceTiming.domainLookupEnd)],\n ['http.request.connect_start', getAbsoluteTime(resourceTiming.connectStart)],\n ['http.request.secure_connection_start', getAbsoluteTime(resourceTiming.secureConnectionStart)],\n ['http.request.connection_end', getAbsoluteTime(resourceTiming.connectEnd)],\n ['http.request.request_start', getAbsoluteTime(resourceTiming.requestStart)],\n ['http.request.response_start', getAbsoluteTime(resourceTiming.responseStart)],\n ['http.request.response_end', getAbsoluteTime(resourceTiming.responseEnd)],\n ];\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * We only export this function for testing purposes.\n */\nfunction shouldAttachHeaders(\n targetUrl,\n tracePropagationTargets,\n) {\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 = WINDOW.location && WINDOW.location.href;\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 (e) {\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,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n) {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];\n\n if (!xhr || xhr.__sentry_own_request__ || !sentryXhrData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = hasTracingEnabled() && shouldCreateSpan(sentryXhrData.url);\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span && sentryXhrData.status_code !== undefined) {\n setHttpStatus(span, sentryXhrData.status_code);\n span.end();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const fullUrl = getFullURL(sentryXhrData.url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const hasParent = !!getActiveSpan();\n\n const span =\n shouldCreateSpanResult && hasParent\n ? startInactiveSpan({\n name: `${sentryXhrData.method} ${sentryXhrData.url}`,\n attributes: {\n type: 'xhr',\n 'http.method': sentryXhrData.method,\n 'http.url': fullUrl,\n url: sentryXhrData.url,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.client',\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(sentryXhrData.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 hasTracingEnabled() && hasParent ? span : undefined,\n );\n }\n\n return span;\n}\n\nfunction addTracingHeadersToXhrRequest(xhr, span) {\n const { 'sentry-trace': sentryTrace, baggage } = getTraceData({ span });\n\n if (sentryTrace) {\n setHeaderOnXhr(xhr, sentryTrace, baggage);\n }\n}\n\nfunction setHeaderOnXhr(\n xhr,\n sentryTraceHeader,\n sentryBaggageHeader,\n) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader('sentry-trace', sentryTraceHeader);\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader('baggage', sentryBaggageHeader);\n }\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n}\n\nfunction getFullURL(url) {\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 (e2) {\n return undefined;\n }\n}\n\nexport { defaultRequestInstrumentationOptions, extractNetworkProtocol, instrumentOutgoingRequests, shouldAttachHeaders, xhrCallback };\n//# sourceMappingURL=request.js.map\n","import { getActiveSpan, getRootSpan, spanToJSON, logger, SPAN_STATUS_ERROR } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nfunction registerBackgroundTabDetection() {\n if (WINDOW && 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 logger.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 && logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n\nexport { registerBackgroundTabDetection };\n//# sourceMappingURL=backgroundtab.js.map\n","import { startTrackingWebVitals, startTrackingINP, startTrackingLongAnimationFrames, startTrackingLongTasks, startTrackingInteractions, addHistoryInstrumentationHandler, registerInpInteractionListener, addPerformanceEntries } from '@sentry-internal/browser-utils';\nimport { TRACING_DEFAULTS, registerSpanErrorInstrumentation, GLOBAL_OBJ, getClient, propagationContextFromHeaders, getCurrentScope, spanToJSON, getRootSpan, spanIsSampled, getDynamicSamplingContextFromSpan, browserPerformanceTimeOrigin, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getActiveSpan, getIsolationScope, generateTraceId, getDomElement, startIdleSpan, logger, SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\nimport { registerBackgroundTabDetection } from './backgroundtab.js';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request.js';\n\n/* eslint-disable max-lines */\n\nconst BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS = {\n ...TRACING_DEFAULTS,\n instrumentNavigation: true,\n instrumentPageLoad: true,\n markBackgroundSpan: true,\n enableLongTask: true,\n enableLongAnimationFrame: true,\n enableInp: true,\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 */\nconst browserTracingIntegration = ((_options = {}) => {\n registerSpanErrorInstrumentation();\n\n const {\n enableInp,\n enableLongTask,\n enableLongAnimationFrame,\n _experiments: { enableInteractions, enableStandaloneClsSpans },\n beforeStartSpan,\n idleTimeout,\n finalTimeout,\n childSpanTimeout,\n markBackgroundSpan,\n traceFetch,\n traceXHR,\n trackFetchStreamPerformance,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n instrumentPageLoad,\n instrumentNavigation,\n } = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n const _collectWebVitals = startTrackingWebVitals({ recordClsStandaloneSpans: enableStandaloneClsSpans || false });\n\n if (enableInp) {\n startTrackingINP();\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 const latestRoute = {\n name: undefined,\n source: undefined,\n };\n\n /** Create routing idle transaction. */\n function _createRouteSpan(client, startSpanOptions) {\n const isPageloadTransaction = startSpanOptions.op === 'pageload';\n\n const finalStartSpanOptions = 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 (startSpanOptions.name !== finalStartSpanOptions.name) {\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'custom';\n finalStartSpanOptions.attributes = attributes;\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: isPageloadTransaction,\n beforeSpanEnd: span => {\n _collectWebVitals();\n addPerformanceEntries(span, { recordClsOnPageloadSpan: !enableStandaloneClsSpans });\n },\n });\n\n function emitFinish() {\n if (['interactive', 'complete'].includes(WINDOW.document.readyState)) {\n client.emit('idleSpanEnableAutoFinish', idleSpan);\n }\n }\n\n if (isPageloadTransaction && WINDOW.document) {\n WINDOW.document.addEventListener('readystatechange', () => {\n emitFinish();\n });\n\n emitFinish();\n }\n\n return idleSpan;\n }\n\n return {\n name: BROWSER_TRACING_INTEGRATION_ID,\n afterAllSetup(client) {\n let activeSpan;\n let startingUrl = WINDOW.location && WINDOW.location.href;\n\n function maybeEndActiveSpan() {\n if (activeSpan && !spanToJSON(activeSpan).timestamp) {\n DEBUG_BUILD && logger.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.end();\n }\n }\n\n client.on('startNavigationSpan', startSpanOptions => {\n if (getClient() !== client) {\n return;\n }\n\n maybeEndActiveSpan();\n\n activeSpan = _createRouteSpan(client, {\n op: 'navigation',\n ...startSpanOptions,\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 getCurrentScope().setPropagationContext(propagationContext);\n\n activeSpan = _createRouteSpan(client, {\n op: 'pageload',\n ...startSpanOptions,\n });\n });\n\n // A trace should to stay the consistent over the entire time span of one route.\n // Therefore, when the initial pageload or navigation root span ends, we update the\n // scope's propagation context to keep span-specific attributes like the `sampled` decision and\n // the dynamic sampling context valid, even after the root span has ended.\n // This ensures that the trace data is consistent for the entire duration of the route.\n client.on('spanEnd', span => {\n const op = spanToJSON(span).op;\n if (span !== getRootSpan(span) || (op !== 'navigation' && op !== 'pageload')) {\n return;\n }\n\n const scope = getCurrentScope();\n const oldPropagationContext = scope.getPropagationContext();\n\n scope.setPropagationContext({\n ...oldPropagationContext,\n sampled: oldPropagationContext.sampled !== undefined ? oldPropagationContext.sampled : spanIsSampled(span),\n dsc: oldPropagationContext.dsc || getDynamicSamplingContextFromSpan(span),\n });\n });\n\n if (WINDOW.location) {\n if (instrumentPageLoad) {\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: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 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 && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n startBrowserTracingNavigationSpan(client, {\n name: WINDOW.location.pathname,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.navigation.browser',\n },\n });\n }\n });\n }\n }\n\n if (markBackgroundSpan) {\n registerBackgroundTabDetection();\n }\n\n if (enableInteractions) {\n registerInteractionListener(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 });\n },\n };\n}) ;\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 */\nfunction startBrowserTracingPageLoadSpan(\n client,\n spanOptions,\n traceOptions,\n) {\n client.emit('startPageLoadSpan', spanOptions, traceOptions);\n\n getCurrentScope().setTransactionName(spanOptions.name);\n\n const span = getActiveSpan();\n const op = span && spanToJSON(span).op;\n return op === 'pageload' ? span : undefined;\n}\n\n/**\n * Manually start a navigation span.\n * This will only do something if a browser tracing integration has been setup.\n */\nfunction startBrowserTracingNavigationSpan(client, spanOptions) {\n getIsolationScope().setPropagationContext({ traceId: generateTraceId() });\n getCurrentScope().setPropagationContext({ traceId: generateTraceId() });\n\n client.emit('startNavigationSpan', spanOptions);\n\n getCurrentScope().setTransactionName(spanOptions.name);\n\n const span = getActiveSpan();\n const op = span && spanToJSON(span).op;\n return op === 'navigation' ? span : undefined;\n}\n\n/** Returns the value of a meta tag */\nfunction getMetaContent(metaName) {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : undefined;\n}\n\n/** Start listener for interaction transactions */\nfunction registerInteractionListener(\n idleTimeout,\n finalTimeout,\n childSpanTimeout,\n latestRoute,\n) {\n let inflightInteractionSpan;\n const registerInteractionTransaction = () => {\n const op = 'ui.action.click';\n\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n if (rootSpan) {\n const currentRootSpanOp = spanToJSON(rootSpan).op;\n if (['navigation', 'pageload'].includes(currentRootSpanOp )) {\n DEBUG_BUILD &&\n logger.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 && logger.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 (WINDOW.document) {\n addEventListener('click', registerInteractionTransaction, { once: false, capture: true });\n }\n}\n\nexport { BROWSER_TRACING_INTEGRATION_ID, browserTracingIntegration, getMetaContent, startBrowserTracingNavigationSpan, startBrowserTracingPageLoadSpan };\n//# sourceMappingURL=browserTracingIntegration.js.map\n","import { spanToJSON, forEachEnvelopeItem, logger, getClient, timestampInSeconds, DEFAULT_ENVIRONMENT, uuid4, getDebugImagesForResources, browserPerformanceTimeOrigin } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\n\nconst MS_TO_NS = 1e6;\n// Use 0 as main thread id which is identical to threadId in node:worker_threads\n// where main logs 0 and workers seem to log in increments of 1\nconst THREAD_ID_STRING = String(0);\nconst THREAD_NAME = 'main';\n\n// Machine properties (eval only once)\nlet OS_PLATFORM = '';\nlet OS_PLATFORM_VERSION = '';\nlet OS_ARCH = '';\nlet OS_BROWSER = (WINDOW.navigator && WINDOW.navigator.userAgent) || '';\nlet OS_MODEL = '';\nconst OS_LOCALE =\n (WINDOW.navigator && WINDOW.navigator.language) ||\n (WINDOW.navigator && WINDOW.navigator.languages && WINDOW.navigator.languages[0]) ||\n '';\n\nfunction isUserAgentData(data) {\n return typeof data === 'object' && data !== null && 'getHighEntropyValues' in data;\n}\n\n// @ts-expect-error userAgentData is not part of the navigator interface yet\nconst userAgentData = WINDOW.navigator && WINDOW.navigator.userAgentData;\n\nif (isUserAgentData(userAgentData)) {\n userAgentData\n .getHighEntropyValues(['architecture', 'model', 'platform', 'platformVersion', 'fullVersionList'])\n .then((ua) => {\n OS_PLATFORM = ua.platform || '';\n OS_ARCH = ua.architecture || '';\n OS_MODEL = ua.model || '';\n OS_PLATFORM_VERSION = ua.platformVersion || '';\n\n if (ua.fullVersionList && ua.fullVersionList.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const firstUa = ua.fullVersionList[ua.fullVersionList.length - 1];\n OS_BROWSER = `${firstUa.brand} ${firstUa.version}`;\n }\n })\n .catch(e => void e);\n}\n\nfunction isProcessedJSSelfProfile(profile) {\n return !('thread_metadata' in profile);\n}\n\n// Enriches the profile with threadId of the current thread.\n// This is done in node as we seem to not be able to get the info from C native code.\n/**\n *\n */\nfunction enrichWithThreadInformation(profile) {\n if (!isProcessedJSSelfProfile(profile)) {\n return profile;\n }\n\n return convertJSSelfProfileToSampledFormat(profile);\n}\n\n// Profile is marked as optional because it is deleted from the metadata\n// by the integration before the event is processed by other integrations.\n\nfunction getTraceId(event) {\n const traceId = event && event.contexts && event.contexts['trace'] && event.contexts['trace']['trace_id'];\n // Log a warning if the profile has an invalid traceId (should be uuidv4).\n // All profiles and transactions are rejected if this is the case and we want to\n // warn users that this is happening if they enable debug flag\n if (typeof traceId === 'string' && traceId.length !== 32) {\n if (DEBUG_BUILD) {\n logger.log(`[Profiling] Invalid traceId: ${traceId} on profiled event`);\n }\n }\n if (typeof traceId !== 'string') {\n return '';\n }\n\n return traceId;\n}\n/**\n * Creates a profiling event envelope from a Sentry event. If profile does not pass\n * validation, returns null.\n * @param event\n * @param dsn\n * @param metadata\n * @param tunnel\n * @returns {EventEnvelope | null}\n */\n\n/**\n * Creates a profiling event envelope from a Sentry event.\n */\nfunction createProfilePayload(\n profile_id,\n start_timestamp,\n processed_profile,\n event,\n) {\n if (event.type !== 'transaction') {\n // createProfilingEventEnvelope should only be called for transactions,\n // we type guard this behavior with isProfiledTransactionEvent.\n throw new TypeError('Profiling events may only be attached to transactions, this should never occur.');\n }\n\n if (processed_profile === undefined || processed_profile === null) {\n throw new TypeError(\n `Cannot construct profiling event envelope without a valid profile. Got ${processed_profile} instead.`,\n );\n }\n\n const traceId = getTraceId(event);\n const enrichedThreadProfile = enrichWithThreadInformation(processed_profile);\n const transactionStartMs = start_timestamp\n ? start_timestamp\n : typeof event.start_timestamp === 'number'\n ? event.start_timestamp * 1000\n : timestampInSeconds() * 1000;\n const transactionEndMs = typeof event.timestamp === 'number' ? event.timestamp * 1000 : timestampInSeconds() * 1000;\n\n const profile = {\n event_id: profile_id,\n timestamp: new Date(transactionStartMs).toISOString(),\n platform: 'javascript',\n version: '1',\n release: event.release || '',\n environment: event.environment || DEFAULT_ENVIRONMENT,\n runtime: {\n name: 'javascript',\n version: WINDOW.navigator.userAgent,\n },\n os: {\n name: OS_PLATFORM,\n version: OS_PLATFORM_VERSION,\n build_number: OS_BROWSER,\n },\n device: {\n locale: OS_LOCALE,\n model: OS_MODEL,\n manufacturer: OS_BROWSER,\n architecture: OS_ARCH,\n is_emulator: false,\n },\n debug_meta: {\n images: applyDebugMetadata(processed_profile.resources),\n },\n profile: enrichedThreadProfile,\n transactions: [\n {\n name: event.transaction || '',\n id: event.event_id || uuid4(),\n trace_id: traceId,\n active_thread_id: THREAD_ID_STRING,\n relative_start_ns: '0',\n relative_end_ns: ((transactionEndMs - transactionStartMs) * 1e6).toFixed(0),\n },\n ],\n };\n\n return profile;\n}\n\n/*\n See packages/browser-utils/src/browser/router.ts\n*/\n/**\n *\n */\nfunction isAutomatedPageLoadSpan(span) {\n return spanToJSON(span).op === 'pageload';\n}\n\n/**\n * Converts a JSSelfProfile to a our sampled format.\n * Does not currently perform stack indexing.\n */\nfunction convertJSSelfProfileToSampledFormat(input) {\n let EMPTY_STACK_ID = undefined;\n let STACK_ID = 0;\n\n // Initialize the profile that we will fill with data\n const profile = {\n samples: [],\n stacks: [],\n frames: [],\n thread_metadata: {\n [THREAD_ID_STRING]: { name: THREAD_NAME },\n },\n };\n\n const firstSample = input.samples[0];\n if (!firstSample) {\n return profile;\n }\n\n // We assert samples.length > 0 above and timestamp should always be present\n const start = firstSample.timestamp;\n // The JS SDK might change it's time origin based on some heuristic (see See packages/utils/src/time.ts)\n // when that happens, we need to ensure we are correcting the profile timings so the two timelines stay in sync.\n // Since JS self profiling time origin is always initialized to performance.timeOrigin, we need to adjust for\n // the drift between the SDK selected value and our profile time origin.\n const origin =\n typeof performance.timeOrigin === 'number' ? performance.timeOrigin : browserPerformanceTimeOrigin || 0;\n const adjustForOriginChange = origin - (browserPerformanceTimeOrigin || origin);\n\n input.samples.forEach((jsSample, i) => {\n // If sample has no stack, add an empty sample\n if (jsSample.stackId === undefined) {\n if (EMPTY_STACK_ID === undefined) {\n EMPTY_STACK_ID = STACK_ID;\n profile.stacks[EMPTY_STACK_ID] = [];\n STACK_ID++;\n }\n\n profile['samples'][i] = {\n // convert ms timestamp to ns\n elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start) * MS_TO_NS).toFixed(0),\n stack_id: EMPTY_STACK_ID,\n thread_id: THREAD_ID_STRING,\n };\n return;\n }\n\n let stackTop = input.stacks[jsSample.stackId];\n\n // Functions in top->down order (root is last)\n // We follow the stackTop.parentId trail and collect each visited frameId\n const stack = [];\n\n while (stackTop) {\n stack.push(stackTop.frameId);\n\n const frame = input.frames[stackTop.frameId];\n\n // If our frame has not been indexed yet, index it\n if (frame && profile.frames[stackTop.frameId] === undefined) {\n profile.frames[stackTop.frameId] = {\n function: frame.name,\n abs_path: typeof frame.resourceId === 'number' ? input.resources[frame.resourceId] : undefined,\n lineno: frame.line,\n colno: frame.column,\n };\n }\n\n stackTop = stackTop.parentId === undefined ? undefined : input.stacks[stackTop.parentId];\n }\n\n const sample = {\n // convert ms timestamp to ns\n elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start) * MS_TO_NS).toFixed(0),\n stack_id: STACK_ID,\n thread_id: THREAD_ID_STRING,\n };\n\n profile['stacks'][STACK_ID] = stack;\n profile['samples'][i] = sample;\n STACK_ID++;\n });\n\n return profile;\n}\n\n/**\n * Adds items to envelope if they are not already present - mutates the envelope.\n * @param envelope\n */\nfunction addProfilesToEnvelope(envelope, profiles) {\n if (!profiles.length) {\n return envelope;\n }\n\n for (const profile of profiles) {\n envelope[1].push([{ type: 'profile' }, profile]);\n }\n return envelope;\n}\n\n/**\n * Finds transactions with profile_id context in the envelope\n * @param envelope\n * @returns\n */\nfunction findProfiledTransactionsFromEnvelope(envelope) {\n const events = [];\n\n forEachEnvelopeItem(envelope, (item, type) => {\n if (type !== 'transaction') {\n return;\n }\n\n for (let j = 1; j < item.length; j++) {\n const event = item[j] ;\n\n if (event && event.contexts && event.contexts['profile'] && event.contexts['profile']['profile_id']) {\n events.push(item[j] );\n }\n }\n });\n\n return events;\n}\n\n/**\n * Applies debug meta data to an event from a list of paths to resources (sourcemaps)\n */\nfunction applyDebugMetadata(resource_paths) {\n const client = getClient();\n const options = client && client.getOptions();\n const stackParser = options && options.stackParser;\n\n if (!stackParser) {\n return [];\n }\n\n return getDebugImagesForResources(stackParser, resource_paths);\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nfunction isValidSampleRate(rate) {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n if ((typeof rate !== 'number' && typeof rate !== 'boolean') || (typeof rate === 'number' && isNaN(rate))) {\n DEBUG_BUILD &&\n logger.warn(\n `[Profiling] Invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // Boolean sample rates are always valid\n if (rate === true || rate === false) {\n return true;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n DEBUG_BUILD && logger.warn(`[Profiling] Invalid sample rate. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n\nfunction isValidProfile(profile) {\n if (profile.samples.length < 2) {\n if (DEBUG_BUILD) {\n // Log a warning if the profile has less than 2 samples so users can know why\n // they are not seeing any profiling data and we cant avoid the back and forth\n // of asking them to provide us with a dump of the profile data.\n logger.log('[Profiling] Discarding profile because it contains less than 2 samples');\n }\n return false;\n }\n\n if (!profile.frames.length) {\n if (DEBUG_BUILD) {\n logger.log('[Profiling] Discarding profile because it contains no frames');\n }\n return false;\n }\n\n return true;\n}\n\n// Keep a flag value to avoid re-initializing the profiler constructor. If it fails\n// once, it will always fail and this allows us to early return.\nlet PROFILING_CONSTRUCTOR_FAILED = false;\nconst MAX_PROFILE_DURATION_MS = 30000;\n\n/**\n * Check if profiler constructor is available.\n * @param maybeProfiler\n */\nfunction isJSProfilerSupported(maybeProfiler) {\n return typeof maybeProfiler === 'function';\n}\n\n/**\n * Starts the profiler and returns the profiler instance.\n */\nfunction startJSSelfProfile() {\n // Feature support check first\n const JSProfilerConstructor = WINDOW.Profiler;\n\n if (!isJSProfilerSupported(JSProfilerConstructor)) {\n if (DEBUG_BUILD) {\n logger.log(\n '[Profiling] Profiling is not supported by this browser, Profiler interface missing on window object.',\n );\n }\n return;\n }\n\n // From initial testing, it seems that the minimum value for sampleInterval is 10ms.\n const samplingIntervalMS = 10;\n // Start the profiler\n const maxSamples = Math.floor(MAX_PROFILE_DURATION_MS / samplingIntervalMS);\n\n // Attempt to initialize the profiler constructor, if it fails, we disable profiling for the current user session.\n // This is likely due to a missing 'Document-Policy': 'js-profiling' header. We do not want to throw an error if this happens\n // as we risk breaking the user's application, so just disable profiling and log an error.\n try {\n return new JSProfilerConstructor({ sampleInterval: samplingIntervalMS, maxBufferSize: maxSamples });\n } catch (e) {\n if (DEBUG_BUILD) {\n logger.log(\n \"[Profiling] Failed to initialize the Profiling constructor, this is likely due to a missing 'Document-Policy': 'js-profiling' header.\",\n );\n logger.log('[Profiling] Disabling profiling for current user session.');\n }\n PROFILING_CONSTRUCTOR_FAILED = true;\n }\n\n return;\n}\n\n/**\n * Determine if a profile should be profiled.\n */\nfunction shouldProfileSpan(span) {\n // If constructor failed once, it will always fail, so we can early return.\n if (PROFILING_CONSTRUCTOR_FAILED) {\n if (DEBUG_BUILD) {\n logger.log('[Profiling] Profiling has been disabled for the duration of the current user session.');\n }\n return false;\n }\n\n if (!span.isRecording()) {\n if (DEBUG_BUILD) {\n logger.log('[Profiling] Discarding profile because transaction was not sampled.');\n }\n return false;\n }\n\n const client = getClient();\n const options = client && client.getOptions();\n if (!options) {\n DEBUG_BUILD && logger.log('[Profiling] Profiling disabled, no options found.');\n return false;\n }\n\n // @ts-expect-error profilesSampleRate is not part of the browser options yet\n const profilesSampleRate = options.profilesSampleRate;\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(profilesSampleRate)) {\n DEBUG_BUILD && logger.warn('[Profiling] Discarding profile because of invalid sample rate.');\n return false;\n }\n\n // if the function returned 0 (or false), or if `profileSampleRate` is 0, it's a sign the profile should be dropped\n if (!profilesSampleRate) {\n DEBUG_BUILD &&\n logger.log(\n '[Profiling] Discarding profile because a negative sampling decision was inherited or profileSampleRate is set to 0',\n );\n return false;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n const sampled = profilesSampleRate === true ? true : Math.random() < profilesSampleRate;\n // Check if we should sample this profile\n if (!sampled) {\n DEBUG_BUILD &&\n logger.log(\n `[Profiling] Discarding profile because it's not included in the random sample (sampling rate = ${Number(\n profilesSampleRate,\n )})`,\n );\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a profiling envelope item, if the profile does not pass validation, returns null.\n * @param event\n * @returns {Profile | null}\n */\nfunction createProfilingEvent(\n profile_id,\n start_timestamp,\n profile,\n event,\n) {\n if (!isValidProfile(profile)) {\n return null;\n }\n\n return createProfilePayload(profile_id, start_timestamp, profile, event);\n}\n\n// TODO (v8): We need to obtain profile ids in @sentry-internal/tracing,\n// but we don't have access to this map because importing this map would\n// cause a circular dependency. We need to resolve this in v8.\nconst PROFILE_MAP = new Map();\n/**\n *\n */\nfunction getActiveProfilesCount() {\n return PROFILE_MAP.size;\n}\n\n/**\n * Retrieves profile from global cache and removes it.\n */\nfunction takeProfileFromGlobalCache(profile_id) {\n const profile = PROFILE_MAP.get(profile_id);\n if (profile) {\n PROFILE_MAP.delete(profile_id);\n }\n return profile;\n}\n/**\n * Adds profile to global cache and evicts the oldest profile if the cache is full.\n */\nfunction addProfileToGlobalCache(profile_id, profile) {\n PROFILE_MAP.set(profile_id, profile);\n\n if (PROFILE_MAP.size > 30) {\n const last = PROFILE_MAP.keys().next().value;\n PROFILE_MAP.delete(last);\n }\n}\n\nexport { MAX_PROFILE_DURATION_MS, addProfileToGlobalCache, addProfilesToEnvelope, applyDebugMetadata, convertJSSelfProfileToSampledFormat, createProfilePayload, createProfilingEvent, enrichWithThreadInformation, findProfiledTransactionsFromEnvelope, getActiveProfilesCount, isAutomatedPageLoadSpan, isValidSampleRate, shouldProfileSpan, startJSSelfProfile, takeProfileFromGlobalCache };\n//# sourceMappingURL=utils.js.map\n","import { timestampInSeconds, logger, spanToJSON, uuid4, getCurrentScope } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\nimport { isAutomatedPageLoadSpan, startJSSelfProfile, MAX_PROFILE_DURATION_MS, addProfileToGlobalCache } from './utils.js';\n\n/**\n * Wraps startTransaction and stopTransaction with profiling related logic.\n * startProfileForTransaction is called after the call to startTransaction in order to avoid our own code from\n * being profiled. Because of that same reason, stopProfiling is called before the call to stopTransaction.\n */\nfunction startProfileForSpan(span) {\n // Start the profiler and get the profiler instance.\n let startTimestamp;\n if (isAutomatedPageLoadSpan(span)) {\n startTimestamp = timestampInSeconds() * 1000;\n }\n\n const profiler = startJSSelfProfile();\n\n // We failed to construct the profiler, so we skip.\n // No need to log anything as this has already been logged in startProfile.\n if (!profiler) {\n return;\n }\n\n if (DEBUG_BUILD) {\n logger.log(`[Profiling] started profiling span: ${spanToJSON(span).description}`);\n }\n\n // We create \"unique\" span names to avoid concurrent spans with same names\n // from being ignored by the profiler. From here on, only this span name should be used when\n // calling the profiler methods. Note: we log the original name to the user to avoid confusion.\n const profileId = uuid4();\n\n getCurrentScope().setContext('profile', {\n profile_id: profileId,\n start_timestamp: startTimestamp,\n });\n\n /**\n * Idempotent handler for profile stop\n */\n async function onProfileHandler() {\n // Check if the profile exists and return it the behavior has to be idempotent as users may call span.finish multiple times.\n if (!span) {\n return;\n }\n // Satisfy the type checker, but profiler will always be defined here.\n if (!profiler) {\n return;\n }\n\n return profiler\n .stop()\n .then((profile) => {\n if (maxDurationTimeoutID) {\n WINDOW.clearTimeout(maxDurationTimeoutID);\n maxDurationTimeoutID = undefined;\n }\n\n if (DEBUG_BUILD) {\n logger.log(`[Profiling] stopped profiling of span: ${spanToJSON(span).description}`);\n }\n\n // In case of an overlapping span, stopProfiling may return null and silently ignore the overlapping profile.\n if (!profile) {\n if (DEBUG_BUILD) {\n logger.log(\n `[Profiling] profiler returned null profile for: ${spanToJSON(span).description}`,\n 'this may indicate an overlapping span or a call to stopProfiling with a profile title that was never started',\n );\n }\n return;\n }\n\n addProfileToGlobalCache(profileId, profile);\n })\n .catch(error => {\n if (DEBUG_BUILD) {\n logger.log('[Profiling] error while stopping profiler:', error);\n }\n });\n }\n\n // Enqueue a timeout to prevent profiles from running over max duration.\n let maxDurationTimeoutID = WINDOW.setTimeout(() => {\n if (DEBUG_BUILD) {\n logger.log('[Profiling] max profile duration elapsed, stopping profiling for:', spanToJSON(span).description);\n }\n // If the timeout exceeds, we want to stop profiling, but not finish the span\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n onProfileHandler();\n }, MAX_PROFILE_DURATION_MS);\n\n // We need to reference the original end call to avoid creating an infinite loop\n const originalEnd = span.end.bind(span);\n\n /**\n * Wraps span `end()` with profiling related logic.\n * startProfiling is called after the call to spanStart in order to avoid our own code from\n * being profiled. Because of that same reason, stopProfiling is called before the call to spanEnd.\n */\n function profilingWrappedSpanEnd() {\n if (!span) {\n return originalEnd();\n }\n // onProfileHandler should always return the same profile even if this is called multiple times.\n // Always call onProfileHandler to ensure stopProfiling is called and the timeout is cleared.\n void onProfileHandler().then(\n () => {\n originalEnd();\n },\n () => {\n // If onProfileHandler fails, we still want to call the original finish method.\n originalEnd();\n },\n );\n\n return span;\n }\n\n span.end = profilingWrappedSpanEnd;\n}\n\nexport { startProfileForSpan };\n//# sourceMappingURL=startProfileForSpan.js.map\n","import { defineIntegration, getActiveSpan, getRootSpan, logger } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { startProfileForSpan } from './startProfileForSpan.js';\nimport { isAutomatedPageLoadSpan, shouldProfileSpan, getActiveProfilesCount, findProfiledTransactionsFromEnvelope, takeProfileFromGlobalCache, createProfilingEvent, addProfilesToEnvelope } from './utils.js';\n\nconst INTEGRATION_NAME = 'BrowserProfiling';\n\nconst _browserProfilingIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n\n if (rootSpan && isAutomatedPageLoadSpan(rootSpan)) {\n if (shouldProfileSpan(rootSpan)) {\n startProfileForSpan(rootSpan);\n }\n }\n\n client.on('spanStart', (span) => {\n if (span === getRootSpan(span) && shouldProfileSpan(span)) {\n startProfileForSpan(span);\n }\n });\n\n client.on('beforeEnvelope', (envelope) => {\n // if not profiles are in queue, there is nothing to add to the envelope.\n if (!getActiveProfilesCount()) {\n return;\n }\n\n const profiledTransactionEvents = findProfiledTransactionsFromEnvelope(envelope);\n if (!profiledTransactionEvents.length) {\n return;\n }\n\n const profilesToAddToEnvelope = [];\n\n for (const profiledTransaction of profiledTransactionEvents) {\n const context = profiledTransaction && profiledTransaction.contexts;\n const profile_id = context && context['profile'] && context['profile']['profile_id'];\n const start_timestamp = context && context['profile'] && context['profile']['start_timestamp'];\n\n if (typeof profile_id !== 'string') {\n DEBUG_BUILD && logger.log('[Profiling] cannot find profile for a span without a profile context');\n continue;\n }\n\n if (!profile_id) {\n DEBUG_BUILD && logger.log('[Profiling] cannot find profile for a span without a profile context');\n continue;\n }\n\n // Remove the profile from the span context before sending, relay will take care of the rest.\n if (context && context['profile']) {\n delete context.profile;\n }\n\n const profile = takeProfileFromGlobalCache(profile_id);\n if (!profile) {\n DEBUG_BUILD && logger.log(`[Profiling] Could not retrieve profile for span: ${profile_id}`);\n continue;\n }\n\n const profileEvent = createProfilingEvent(\n profile_id,\n start_timestamp ,\n profile,\n profiledTransaction ,\n );\n if (profileEvent) {\n profilesToAddToEnvelope.push(profileEvent);\n }\n }\n\n addProfilesToEnvelope(envelope , profilesToAddToEnvelope);\n });\n },\n };\n}) ;\n\nconst browserProfilingIntegration = defineIntegration(_browserProfilingIntegration);\n\nexport { browserProfilingIntegration };\n//# sourceMappingURL=integration.js.map\n","import { setContext, init as init$1 } from '@sentry/browser';\nimport { applySdkMetadata } from '@sentry/core';\nimport { version } from 'react';\n\n/**\n * Inits the React SDK\n */\nfunction init(options) {\n const opts = {\n ...options,\n };\n\n applySdkMetadata(opts, 'react');\n setContext('react', { version });\n return init$1(opts);\n}\n\nexport { init };\n//# sourceMappingURL=sdk.js.map\n","import { browserTracingIntegration, WINDOW, startBrowserTracingPageLoadSpan, startBrowserTracingNavigationSpan } from '@sentry/browser';\nimport { logger, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getClient, getNumberOfUrlSegments, getCurrentScope, getActiveSpan, getRootSpan, spanToJSON } from '@sentry/core';\nimport * as React from 'react';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport { DEBUG_BUILD } from './debug-build.js';\n\n/* eslint-disable max-lines */\n// Inspired from Donnie McNeal's solution:\n// https://gist.github.com/wontondon/e8c4bdf2888875e4c755712e99279536\n\n\nlet _useEffect;\nlet _useLocation;\nlet _useNavigationType;\nlet _createRoutesFromChildren;\nlet _matchRoutes;\nlet _stripBasename = false;\n\nconst CLIENTS_WITH_INSTRUMENT_NAVIGATION = new WeakSet();\n\n/**\n * Creates a wrapCreateBrowserRouter function that can be used with all React Router v6 compatible versions.\n */\nfunction createV6CompatibleWrapCreateBrowserRouter\n\n(\n createRouterFunction,\n version,\n) {\n if (!_useEffect || !_useLocation || !_useNavigationType || !_matchRoutes) {\n DEBUG_BUILD &&\n logger.warn(\n `reactRouterV${version}Instrumentation was unable to wrap the \\`createRouter\\` function because of one or more missing parameters.`,\n );\n\n return createRouterFunction;\n }\n\n // `opts` for createBrowserHistory and createMemoryHistory are different, but also not relevant for us at the moment.\n // `basename` is the only option that is relevant for us, and it is the same for all.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (routes, opts) {\n const router = createRouterFunction(routes, opts);\n const basename = opts && opts.basename;\n\n const activeRootSpan = getActiveRootSpan();\n\n // The initial load ends when `createBrowserRouter` is called.\n // This is the earliest convenient time to update the transaction name.\n // Callbacks to `router.subscribe` are not called for the initial load.\n if (router.state.historyAction === 'POP' && activeRootSpan) {\n updatePageloadTransaction(activeRootSpan, router.state.location, routes, undefined, basename);\n }\n\n router.subscribe((state) => {\n const location = state.location;\n if (state.historyAction === 'PUSH' || state.historyAction === 'POP') {\n handleNavigation({\n location,\n routes,\n navigationType: state.historyAction,\n version,\n basename,\n });\n }\n });\n\n return router;\n };\n}\n\n/**\n * Creates a browser tracing integration that can be used with all React Router v6 compatible versions.\n */\nfunction createReactRouterV6CompatibleTracingIntegration(\n options,\n version,\n) {\n const integration = browserTracingIntegration({\n ...options,\n instrumentPageLoad: false,\n instrumentNavigation: false,\n });\n\n const {\n useEffect,\n useLocation,\n useNavigationType,\n createRoutesFromChildren,\n matchRoutes,\n stripBasename,\n instrumentPageLoad = true,\n instrumentNavigation = true,\n } = options;\n\n return {\n ...integration,\n setup() {\n _useEffect = useEffect;\n _useLocation = useLocation;\n _useNavigationType = useNavigationType;\n _matchRoutes = matchRoutes;\n _createRoutesFromChildren = createRoutesFromChildren;\n _stripBasename = stripBasename || false;\n },\n afterAllSetup(client) {\n integration.afterAllSetup(client);\n\n const initPathName = WINDOW && WINDOW.location && WINDOW.location.pathname;\n if (instrumentPageLoad && initPathName) {\n startBrowserTracingPageLoadSpan(client, {\n name: initPathName,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'pageload',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: `auto.pageload.react.reactrouter_v${version}`,\n },\n });\n }\n\n if (instrumentNavigation) {\n CLIENTS_WITH_INSTRUMENT_NAVIGATION.add(client);\n }\n },\n };\n}\n\nfunction createV6CompatibleWrapUseRoutes(origUseRoutes, version) {\n if (!_useEffect || !_useLocation || !_useNavigationType || !_matchRoutes) {\n DEBUG_BUILD &&\n logger.warn(\n 'reactRouterV6Instrumentation was unable to wrap `useRoutes` because of one or more missing parameters.',\n );\n\n return origUseRoutes;\n }\n\n const allRoutes = [];\n\n const SentryRoutes\n\n = (props) => {\n const isMountRenderPass = React.useRef(true);\n const { routes, locationArg } = props;\n\n const Routes = origUseRoutes(routes, locationArg);\n\n const location = _useLocation();\n const navigationType = _useNavigationType();\n\n // A value with stable identity to either pick `locationArg` if available or `location` if not\n const stableLocationParam =\n typeof locationArg === 'string' || (locationArg && locationArg.pathname)\n ? (locationArg )\n : location;\n\n _useEffect(() => {\n const normalizedLocation =\n typeof stableLocationParam === 'string' ? { pathname: stableLocationParam } : stableLocationParam;\n\n if (isMountRenderPass.current) {\n routes.forEach(route => {\n allRoutes.push(...getChildRoutesRecursively(route));\n });\n\n updatePageloadTransaction(getActiveRootSpan(), normalizedLocation, routes, undefined, undefined, allRoutes);\n isMountRenderPass.current = false;\n } else {\n handleNavigation({\n location: normalizedLocation,\n routes,\n navigationType,\n version,\n allRoutes,\n });\n }\n }, [navigationType, stableLocationParam]);\n\n return Routes;\n };\n\n // eslint-disable-next-line react/display-name\n return (routes, locationArg) => {\n return React.createElement(SentryRoutes, { routes: routes, locationArg: locationArg,} );\n };\n}\n\nfunction handleNavigation(opts\n\n) {\n const { location, routes, navigationType, version, matches, basename, allRoutes } = opts;\n\n const branches = Array.isArray(matches) ? matches : _matchRoutes(routes, location, basename);\n\n const client = getClient();\n if (!client || !CLIENTS_WITH_INSTRUMENT_NAVIGATION.has(client)) {\n return;\n }\n\n if ((navigationType === 'PUSH' || navigationType === 'POP') && branches) {\n let name,\n source = 'url';\n const isInDescendantRoute = locationIsInsideDescendantRoute(location, allRoutes || routes);\n\n if (isInDescendantRoute) {\n name = prefixWithSlash(rebuildRoutePathFromAllRoutes(allRoutes || routes, location));\n source = 'route';\n }\n\n if (!isInDescendantRoute || !name) {\n [name, source] = getNormalizedName(routes, location, branches, basename);\n }\n\n startBrowserTracingNavigationSpan(client, {\n name,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'navigation',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: `auto.navigation.react.reactrouter_v${version}`,\n },\n });\n }\n}\n\n/**\n * Strip the basename from a pathname if exists.\n *\n * Vendored and modified from `react-router`\n * https://github.com/remix-run/react-router/blob/462bb712156a3f739d6139a0f14810b76b002df6/packages/router/utils.ts#L1038\n */\nfunction stripBasenameFromPathname(pathname, basename) {\n if (!basename || basename === '/') {\n return pathname;\n }\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return pathname;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n const startIndex = basename.endsWith('/') ? basename.length - 1 : basename.length;\n const nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== '/') {\n // pathname does not start with basename/\n return pathname;\n }\n\n return pathname.slice(startIndex) || '/';\n}\n\nfunction sendIndexPath(pathBuilder, pathname, basename) {\n const reconstructedPath = pathBuilder || _stripBasename ? stripBasenameFromPathname(pathname, basename) : pathname;\n\n const formattedPath =\n // If the path ends with a slash, remove it\n reconstructedPath[reconstructedPath.length - 1] === '/'\n ? reconstructedPath.slice(0, -1)\n : // If the path ends with a wildcard, remove it\n reconstructedPath.slice(-2) === '/*'\n ? reconstructedPath.slice(0, -1)\n : reconstructedPath;\n\n return [formattedPath, 'route'];\n}\n\nfunction pathEndsWithWildcard(path) {\n return path.endsWith('*');\n}\n\nfunction pathIsWildcardAndHasChildren(path, branch) {\n return (pathEndsWithWildcard(path) && branch.route.children && branch.route.children.length > 0) || false;\n}\n\nfunction routeIsDescendant(route) {\n return !!(!route.children && route.element && route.path && route.path.endsWith('/*'));\n}\n\nfunction locationIsInsideDescendantRoute(location, routes) {\n const matchedRoutes = _matchRoutes(routes, location) ;\n\n if (matchedRoutes) {\n for (const match of matchedRoutes) {\n if (routeIsDescendant(match.route) && pickSplat(match)) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nfunction getChildRoutesRecursively(route, allRoutes = []) {\n if (route.children && !route.index) {\n route.children.forEach(child => {\n allRoutes.push(...getChildRoutesRecursively(child, allRoutes));\n });\n }\n\n allRoutes.push(route);\n\n return allRoutes;\n}\n\nfunction pickPath(match) {\n return trimWildcard(match.route.path || '');\n}\n\nfunction pickSplat(match) {\n return match.params['*'] || '';\n}\n\nfunction trimWildcard(path) {\n return path[path.length - 1] === '*' ? path.slice(0, -1) : path;\n}\n\nfunction trimSlash(path) {\n return path[path.length - 1] === '/' ? path.slice(0, -1) : path;\n}\n\nfunction prefixWithSlash(path) {\n return path[0] === '/' ? path : `/${path}`;\n}\n\nfunction rebuildRoutePathFromAllRoutes(allRoutes, location) {\n const matchedRoutes = _matchRoutes(allRoutes, location) ;\n\n if (!matchedRoutes || matchedRoutes.length === 0) {\n return '';\n }\n\n for (const match of matchedRoutes) {\n if (match.route.path && match.route.path !== '*') {\n const path = pickPath(match);\n const strippedPath = stripBasenameFromPathname(location.pathname, prefixWithSlash(match.pathnameBase));\n\n return trimSlash(\n trimSlash(path || '') +\n prefixWithSlash(\n rebuildRoutePathFromAllRoutes(\n allRoutes.filter(route => route !== match.route),\n {\n pathname: strippedPath,\n },\n ),\n ),\n );\n }\n }\n\n return '';\n}\n\nfunction getNormalizedName(\n routes,\n location,\n branches,\n basename = '',\n) {\n if (!routes || routes.length === 0) {\n return [_stripBasename ? stripBasenameFromPathname(location.pathname, basename) : location.pathname, 'url'];\n }\n\n let pathBuilder = '';\n if (branches) {\n for (const branch of branches) {\n const route = branch.route;\n if (route) {\n // Early return if index route\n if (route.index) {\n return sendIndexPath(pathBuilder, branch.pathname, basename);\n }\n const path = route.path;\n\n // If path is not a wildcard and has no child routes, append the path\n if (path && !pathIsWildcardAndHasChildren(path, branch)) {\n const newPath = path[0] === '/' || pathBuilder[pathBuilder.length - 1] === '/' ? path : `/${path}`;\n pathBuilder += newPath;\n\n // If the path matches the current location, return the path\n if (location.pathname.endsWith(basename + branch.pathname)) {\n if (\n // If the route defined on the element is something like\n // Product} />\n // We should check against the branch.pathname for the number of / separators\n // TODO(v9): Put the implementation of `getNumberOfUrlSegments` in this file\n // eslint-disable-next-line deprecation/deprecation\n getNumberOfUrlSegments(pathBuilder) !== getNumberOfUrlSegments(branch.pathname) &&\n // We should not count wildcard operators in the url segments calculation\n !pathEndsWithWildcard(pathBuilder)\n ) {\n return [(_stripBasename ? '' : basename) + newPath, 'route'];\n }\n\n // if the last character of the pathbuilder is a wildcard and there are children, remove the wildcard\n if (pathIsWildcardAndHasChildren(pathBuilder, branch)) {\n pathBuilder = pathBuilder.slice(0, -1);\n }\n\n return [(_stripBasename ? '' : basename) + pathBuilder, 'route'];\n }\n }\n }\n }\n }\n\n const fallbackTransactionName = _stripBasename\n ? stripBasenameFromPathname(location.pathname, basename)\n : location.pathname || '/';\n\n return [fallbackTransactionName, 'url'];\n}\n\nfunction updatePageloadTransaction(\n activeRootSpan,\n location,\n routes,\n matches,\n basename,\n allRoutes,\n) {\n const branches = Array.isArray(matches)\n ? matches\n : (_matchRoutes(routes, location, basename) );\n\n if (branches) {\n let name,\n source = 'url';\n const isInDescendantRoute = locationIsInsideDescendantRoute(location, allRoutes || routes);\n\n if (isInDescendantRoute) {\n name = prefixWithSlash(rebuildRoutePathFromAllRoutes(allRoutes || routes, location));\n source = 'route';\n }\n\n if (!isInDescendantRoute || !name) {\n [name, source] = getNormalizedName(routes, location, branches, basename);\n }\n\n getCurrentScope().setTransactionName(name);\n\n if (activeRootSpan) {\n activeRootSpan.updateName(name);\n activeRootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);\n }\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction createV6CompatibleWithSentryReactRouterRouting(\n Routes,\n version,\n) {\n if (!_useEffect || !_useLocation || !_useNavigationType || !_createRoutesFromChildren || !_matchRoutes) {\n DEBUG_BUILD &&\n logger.warn(`reactRouterV6Instrumentation was unable to wrap Routes because of one or more missing parameters.\n useEffect: ${_useEffect}. useLocation: ${_useLocation}. useNavigationType: ${_useNavigationType}.\n createRoutesFromChildren: ${_createRoutesFromChildren}. matchRoutes: ${_matchRoutes}.`);\n\n return Routes;\n }\n\n const allRoutes = [];\n\n const SentryRoutes = (props) => {\n const isMountRenderPass = React.useRef(true);\n\n const location = _useLocation();\n const navigationType = _useNavigationType();\n\n _useEffect(\n () => {\n const routes = _createRoutesFromChildren(props.children) ;\n\n if (isMountRenderPass.current) {\n routes.forEach(route => {\n allRoutes.push(...getChildRoutesRecursively(route));\n });\n\n updatePageloadTransaction(getActiveRootSpan(), location, routes, undefined, undefined, allRoutes);\n isMountRenderPass.current = false;\n } else {\n handleNavigation({\n location,\n routes,\n navigationType,\n version,\n allRoutes,\n });\n }\n },\n // `props.children` is purposely not included in the dependency array, because we do not want to re-run this effect\n // when the children change. We only want to start transactions when the location or navigation type change.\n [location, navigationType],\n );\n\n // @ts-expect-error Setting more specific React Component typing for `R` generic above\n // will break advanced type inference done by react router params\n return React.createElement(Routes, { ...props,} );\n };\n\n hoistNonReactStatics(SentryRoutes, Routes);\n\n // @ts-expect-error Setting more specific React Component typing for `R` generic above\n // will break advanced type inference done by react router params\n return SentryRoutes;\n}\n\nfunction getActiveRootSpan() {\n const span = getActiveSpan();\n const rootSpan = span ? getRootSpan(span) : undefined;\n\n if (!rootSpan) {\n return undefined;\n }\n\n const op = spanToJSON(rootSpan).op;\n\n // Only use this root span if it is a pageload or navigation span\n return op === 'navigation' || op === 'pageload' ? rootSpan : undefined;\n}\n\nexport { createReactRouterV6CompatibleTracingIntegration, createV6CompatibleWithSentryReactRouterRouting, createV6CompatibleWrapCreateBrowserRouter, createV6CompatibleWrapUseRoutes, handleNavigation };\n//# sourceMappingURL=reactrouterv6-compat-utils.js.map\n","import { createReactRouterV6CompatibleTracingIntegration, createV6CompatibleWrapUseRoutes, createV6CompatibleWrapCreateBrowserRouter, createV6CompatibleWithSentryReactRouterRouting } from './reactrouterv6-compat-utils.js';\n\n/**\n * A browser tracing integration that uses React Router v6 to instrument navigations.\n * Expects `useEffect`, `useLocation`, `useNavigationType`, `createRoutesFromChildren` and `matchRoutes` to be passed as options.\n */\nfunction reactRouterV6BrowserTracingIntegration(\n options,\n) {\n return createReactRouterV6CompatibleTracingIntegration(options, '6');\n}\n\n/**\n * A wrapper function that adds Sentry routing instrumentation to a React Router v6 useRoutes hook.\n * This is used to automatically capture route changes as transactions when using the useRoutes hook.\n */\nfunction wrapUseRoutesV6(origUseRoutes) {\n return createV6CompatibleWrapUseRoutes(origUseRoutes, '6');\n}\n\n/**\n * Alias for backwards compatibility\n * @deprecated Use `wrapUseRoutesV6` or `wrapUseRoutesV7` instead.\n */\nconst wrapUseRoutes = wrapUseRoutesV6;\n\n/**\n * A wrapper function that adds Sentry routing instrumentation to a React Router v6 createBrowserRouter function.\n * This is used to automatically capture route changes as transactions when using the createBrowserRouter API.\n */\nfunction wrapCreateBrowserRouterV6\n\n(createRouterFunction) {\n return createV6CompatibleWrapCreateBrowserRouter(createRouterFunction, '6');\n}\n\n/**\n * Alias for backwards compatibility\n * @deprecated Use `wrapCreateBrowserRouterV6` or `wrapCreateBrowserRouterV7` instead.\n */\nconst wrapCreateBrowserRouter = wrapCreateBrowserRouterV6;\n\n/**\n * A higher-order component that adds Sentry routing instrumentation to a React Router v6 Route component.\n * This is used to automatically capture route changes as transactions.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction withSentryReactRouterV6Routing(routes) {\n return createV6CompatibleWithSentryReactRouterRouting(routes, '6');\n}\n\nexport { reactRouterV6BrowserTracingIntegration, withSentryReactRouterV6Routing, wrapCreateBrowserRouter, wrapCreateBrowserRouterV6, wrapUseRoutes, wrapUseRoutesV6 };\n//# sourceMappingURL=reactrouterv6.js.map\n","import { useEffect } from \"react\";\nimport * as Sentry from \"@sentry/react\";\nimport {\n createRoutesFromChildren,\n matchRoutes,\n useLocation,\n useNavigationType,\n} from \"react-router-dom\";\n\nconst sentryConfig = {\n dsn: import.meta.env.VITE_APP_SENTRY_DSN,\n integrations: [\n // See docs for support of different versions of variation of react router\n // https://docs.sentry.io/platforms/javascript/guides/react/configuration/integrations/react-router/\n Sentry.reactRouterV6BrowserTracingIntegration({\n useEffect,\n useLocation,\n useNavigationType,\n createRoutesFromChildren,\n matchRoutes,\n }),\n Sentry.replayIntegration(),\n Sentry.browserTracingIntegration(),\n Sentry.browserProfilingIntegration(),\n ],\n \n // Set tracesSampleRate to 1.0 to capture 100%\n // of transactions for tracing.\n // Learn more at\n // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate\n tracesSampleRate: 1.0,\n \n // Set `tracePropagationTargets` to control for which URLs trace propagation should be enabled\n tracePropagationTargets: [/^\\//, /^https:\\/\\/zeno.ltd\\.io\\/api/],\n \n // Capture Replay for 10% of all sessions,\n // plus for 100% of sessions with an error\n // Learn more at\n // https://docs.sentry.io/platforms/javascript/session-replay/configuration/#general-integration-configuration\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0,\n profilesSampleRate: 1.0,\n}\n\nif (import.meta.env.PROD) {\n console.log('Sentry initialized');\n Sentry.init(sentryConfig);\n}\n\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nvar gtag = function gtag() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n if (typeof window !== \"undefined\") {\n var _window;\n if (typeof window.gtag === \"undefined\") {\n window.dataLayer = window.dataLayer || [];\n window.gtag = function gtag() {\n window.dataLayer.push(arguments);\n };\n }\n (_window = window).gtag.apply(_window, args);\n }\n};\nvar _default = gtag;\nexports[\"default\"] = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = format;\nvar smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\\.?|via)$/i;\nfunction toTitleCase(string) {\n return string.toString().trim().replace(/[A-Za-z0-9\\u00C0-\\u00FF]+[^\\s-]*/g, function (match, index, title) {\n if (index > 0 && index + match.length !== title.length && match.search(smallWords) > -1 && title.charAt(index - 2) !== \":\" && (title.charAt(index + match.length) !== \"-\" || title.charAt(index - 1) === \"-\") && title.charAt(index - 1).search(/[^\\s-]/) < 0) {\n return match.toLowerCase();\n }\n if (match.substr(1).search(/[A-Z]|\\../) > -1) {\n return match;\n }\n return match.charAt(0).toUpperCase() + match.substr(1);\n });\n}\n\n// See if s could be an email address. We don't want to send personal data like email.\n// https://support.google.com/analytics/answer/2795983?hl=en\nfunction mightBeEmail(s) {\n // There's no point trying to validate rfc822 fully, just look for ...@...\n return typeof s === \"string\" && s.indexOf(\"@\") !== -1;\n}\nvar redacted = \"REDACTED (Potential Email Address)\";\nfunction redactEmail(string) {\n if (mightBeEmail(string)) {\n console.warn(\"This arg looks like an email address, redacting.\");\n return redacted;\n }\n return string;\n}\nfunction format() {\n var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : \"\";\n var titleCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n var redactingEmail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n var _str = s || \"\";\n if (titleCase) {\n _str = toTitleCase(s);\n }\n if (redactingEmail) {\n _str = redactEmail(_str);\n }\n return _str;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = exports.GA4 = void 0;\nvar _gtag = _interopRequireDefault(require(\"./gtag\"));\nvar _format = _interopRequireDefault(require(\"./format\"));\nvar _excluded = [\"eventCategory\", \"eventAction\", \"eventLabel\", \"eventValue\", \"hitType\"],\n _excluded2 = [\"title\", \"location\"],\n _excluded3 = [\"page\", \"hitType\"];\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : \"undefined\" != typeof Symbol && arr[Symbol.iterator] || arr[\"@@iterator\"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i[\"return\"] && (_r = _i[\"return\"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\n/*\nLinks\nhttps://developers.google.com/gtagjs/reference/api\nhttps://developers.google.com/tag-platform/gtagjs/reference\n*/\n/**\n * @typedef GaOptions\n * @type {Object}\n * @property {boolean} [cookieUpdate=true]\n * @property {number} [cookieExpires=63072000] Default two years\n * @property {string} [cookieDomain=\"auto\"]\n * @property {string} [cookieFlags]\n * @property {string} [userId]\n * @property {string} [clientId]\n * @property {boolean} [anonymizeIp]\n * @property {string} [contentGroup1]\n * @property {string} [contentGroup2]\n * @property {string} [contentGroup3]\n * @property {string} [contentGroup4]\n * @property {string} [contentGroup5]\n * @property {boolean} [allowAdFeatures=true]\n * @property {boolean} [allowAdPersonalizationSignals]\n * @property {boolean} [nonInteraction]\n * @property {string} [page]\n */\n/**\n * @typedef UaEventOptions\n * @type {Object}\n * @property {string} action\n * @property {string} category\n * @property {string} [label]\n * @property {number} [value]\n * @property {boolean} [nonInteraction]\n * @property {('beacon'|'xhr'|'image')} [transport]\n */\n/**\n * @typedef InitOptions\n * @type {Object}\n * @property {string} trackingId\n * @property {GaOptions|any} [gaOptions]\n * @property {Object} [gtagOptions] New parameter\n */\nvar GA4 = /*#__PURE__*/function () {\n function GA4() {\n var _this = this;\n _classCallCheck(this, GA4);\n _defineProperty(this, \"reset\", function () {\n _this.isInitialized = false;\n _this._testMode = false;\n _this._currentMeasurementId;\n _this._hasLoadedGA = false;\n _this._isQueuing = false;\n _this._queueGtag = [];\n });\n _defineProperty(this, \"_gtag\", function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n if (!_this._testMode) {\n if (_this._isQueuing) {\n _this._queueGtag.push(args);\n } else {\n _gtag[\"default\"].apply(void 0, args);\n }\n } else {\n _this._queueGtag.push(args);\n }\n });\n _defineProperty(this, \"_loadGA\", function (GA_MEASUREMENT_ID, nonce) {\n var gtagUrl = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : \"https://www.googletagmanager.com/gtag/js\";\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return;\n }\n if (!_this._hasLoadedGA) {\n // Global Site Tag (gtag.js) - Google Analytics\n var script = document.createElement(\"script\");\n script.async = true;\n script.src = \"\".concat(gtagUrl, \"?id=\").concat(GA_MEASUREMENT_ID);\n if (nonce) {\n script.setAttribute(\"nonce\", nonce);\n }\n document.body.appendChild(script);\n window.dataLayer = window.dataLayer || [];\n window.gtag = function gtag() {\n window.dataLayer.push(arguments);\n };\n _this._hasLoadedGA = true;\n }\n });\n _defineProperty(this, \"_toGtagOptions\", function (gaOptions) {\n if (!gaOptions) {\n return;\n }\n var mapFields = {\n // Old https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#cookieUpdate\n // New https://developers.google.com/analytics/devguides/collection/gtagjs/cookies-user-id#cookie_update\n cookieUpdate: \"cookie_update\",\n cookieExpires: \"cookie_expires\",\n cookieDomain: \"cookie_domain\",\n cookieFlags: \"cookie_flags\",\n // must be in set method?\n userId: \"user_id\",\n clientId: \"client_id\",\n anonymizeIp: \"anonymize_ip\",\n // https://support.google.com/analytics/answer/2853546?hl=en#zippy=%2Cin-this-article\n contentGroup1: \"content_group1\",\n contentGroup2: \"content_group2\",\n contentGroup3: \"content_group3\",\n contentGroup4: \"content_group4\",\n contentGroup5: \"content_group5\",\n // https://support.google.com/analytics/answer/9050852?hl=en\n allowAdFeatures: \"allow_google_signals\",\n allowAdPersonalizationSignals: \"allow_ad_personalization_signals\",\n nonInteraction: \"non_interaction\",\n page: \"page_path\",\n hitCallback: \"event_callback\"\n };\n var gtagOptions = Object.entries(gaOptions).reduce(function (prev, _ref) {\n var _ref2 = _slicedToArray(_ref, 2),\n key = _ref2[0],\n value = _ref2[1];\n if (mapFields[key]) {\n prev[mapFields[key]] = value;\n } else {\n prev[key] = value;\n }\n return prev;\n }, {});\n return gtagOptions;\n });\n _defineProperty(this, \"initialize\", function (GA_MEASUREMENT_ID) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n if (!GA_MEASUREMENT_ID) {\n throw new Error(\"Require GA_MEASUREMENT_ID\");\n }\n var initConfigs = typeof GA_MEASUREMENT_ID === \"string\" ? [{\n trackingId: GA_MEASUREMENT_ID\n }] : GA_MEASUREMENT_ID;\n _this._currentMeasurementId = initConfigs[0].trackingId;\n var gaOptions = options.gaOptions,\n gtagOptions = options.gtagOptions,\n nonce = options.nonce,\n _options$testMode = options.testMode,\n testMode = _options$testMode === void 0 ? false : _options$testMode,\n gtagUrl = options.gtagUrl;\n _this._testMode = testMode;\n if (!testMode) {\n _this._loadGA(_this._currentMeasurementId, nonce, gtagUrl);\n }\n if (!_this.isInitialized) {\n _this._gtag(\"js\", new Date());\n initConfigs.forEach(function (config) {\n var mergedGtagOptions = _objectSpread(_objectSpread(_objectSpread({}, _this._toGtagOptions(_objectSpread(_objectSpread({}, gaOptions), config.gaOptions))), gtagOptions), config.gtagOptions);\n if (Object.keys(mergedGtagOptions).length) {\n _this._gtag(\"config\", config.trackingId, mergedGtagOptions);\n } else {\n _this._gtag(\"config\", config.trackingId);\n }\n });\n }\n _this.isInitialized = true;\n if (!testMode) {\n var queues = _toConsumableArray(_this._queueGtag);\n _this._queueGtag = [];\n _this._isQueuing = false;\n while (queues.length) {\n var queue = queues.shift();\n _this._gtag.apply(_this, _toConsumableArray(queue));\n if (queue[0] === \"get\") {\n _this._isQueuing = true;\n }\n }\n }\n });\n _defineProperty(this, \"set\", function (fieldsObject) {\n if (!fieldsObject) {\n console.warn(\"`fieldsObject` is required in .set()\");\n return;\n }\n if (_typeof(fieldsObject) !== \"object\") {\n console.warn(\"Expected `fieldsObject` arg to be an Object\");\n return;\n }\n if (Object.keys(fieldsObject).length === 0) {\n console.warn(\"empty `fieldsObject` given to .set()\");\n }\n _this._gaCommand(\"set\", fieldsObject);\n });\n _defineProperty(this, \"_gaCommandSendEvent\", function (eventCategory, eventAction, eventLabel, eventValue, fieldsObject) {\n _this._gtag(\"event\", eventAction, _objectSpread(_objectSpread({\n event_category: eventCategory,\n event_label: eventLabel,\n value: eventValue\n }, fieldsObject && {\n non_interaction: fieldsObject.nonInteraction\n }), _this._toGtagOptions(fieldsObject)));\n });\n _defineProperty(this, \"_gaCommandSendEventParameters\", function () {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n if (typeof args[0] === \"string\") {\n _this._gaCommandSendEvent.apply(_this, _toConsumableArray(args.slice(1)));\n } else {\n var _args$ = args[0],\n eventCategory = _args$.eventCategory,\n eventAction = _args$.eventAction,\n eventLabel = _args$.eventLabel,\n eventValue = _args$.eventValue,\n hitType = _args$.hitType,\n rest = _objectWithoutProperties(_args$, _excluded);\n _this._gaCommandSendEvent(eventCategory, eventAction, eventLabel, eventValue, rest);\n }\n });\n _defineProperty(this, \"_gaCommandSendTiming\", function (timingCategory, timingVar, timingValue, timingLabel) {\n _this._gtag(\"event\", \"timing_complete\", {\n name: timingVar,\n value: timingValue,\n event_category: timingCategory,\n event_label: timingLabel\n });\n });\n _defineProperty(this, \"_gaCommandSendPageview\", function (page, fieldsObject) {\n if (fieldsObject && Object.keys(fieldsObject).length) {\n var _this$_toGtagOptions = _this._toGtagOptions(fieldsObject),\n title = _this$_toGtagOptions.title,\n location = _this$_toGtagOptions.location,\n rest = _objectWithoutProperties(_this$_toGtagOptions, _excluded2);\n _this._gtag(\"event\", \"page_view\", _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, page && {\n page_path: page\n }), title && {\n page_title: title\n }), location && {\n page_location: location\n }), rest));\n } else if (page) {\n _this._gtag(\"event\", \"page_view\", {\n page_path: page\n });\n } else {\n _this._gtag(\"event\", \"page_view\");\n }\n });\n _defineProperty(this, \"_gaCommandSendPageviewParameters\", function () {\n for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n args[_key3] = arguments[_key3];\n }\n if (typeof args[0] === \"string\") {\n _this._gaCommandSendPageview.apply(_this, _toConsumableArray(args.slice(1)));\n } else {\n var _args$2 = args[0],\n page = _args$2.page,\n hitType = _args$2.hitType,\n rest = _objectWithoutProperties(_args$2, _excluded3);\n _this._gaCommandSendPageview(page, rest);\n }\n });\n _defineProperty(this, \"_gaCommandSend\", function () {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n var hitType = typeof args[0] === \"string\" ? args[0] : args[0].hitType;\n switch (hitType) {\n case \"event\":\n _this._gaCommandSendEventParameters.apply(_this, args);\n break;\n case \"pageview\":\n _this._gaCommandSendPageviewParameters.apply(_this, args);\n break;\n case \"timing\":\n _this._gaCommandSendTiming.apply(_this, _toConsumableArray(args.slice(1)));\n break;\n case \"screenview\":\n case \"transaction\":\n case \"item\":\n case \"social\":\n case \"exception\":\n console.warn(\"Unsupported send command: \".concat(hitType));\n break;\n default:\n console.warn(\"Send command doesn't exist: \".concat(hitType));\n }\n });\n _defineProperty(this, \"_gaCommandSet\", function () {\n for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {\n args[_key5] = arguments[_key5];\n }\n if (typeof args[0] === \"string\") {\n args[0] = _defineProperty({}, args[0], args[1]);\n }\n _this._gtag(\"set\", _this._toGtagOptions(args[0]));\n });\n _defineProperty(this, \"_gaCommand\", function (command) {\n for (var _len6 = arguments.length, args = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {\n args[_key6 - 1] = arguments[_key6];\n }\n switch (command) {\n case \"send\":\n _this._gaCommandSend.apply(_this, args);\n break;\n case \"set\":\n _this._gaCommandSet.apply(_this, args);\n break;\n default:\n console.warn(\"Command doesn't exist: \".concat(command));\n }\n });\n _defineProperty(this, \"ga\", function () {\n for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {\n args[_key7] = arguments[_key7];\n }\n if (typeof args[0] === \"string\") {\n _this._gaCommand.apply(_this, args);\n } else {\n var readyCallback = args[0];\n _this._gtag(\"get\", _this._currentMeasurementId, \"client_id\", function (clientId) {\n _this._isQueuing = false;\n var queues = _this._queueGtag;\n readyCallback({\n get: function get(property) {\n return property === \"clientId\" ? clientId : property === \"trackingId\" ? _this._currentMeasurementId : property === \"apiVersion\" ? \"1\" : undefined;\n }\n });\n while (queues.length) {\n var queue = queues.shift();\n _this._gtag.apply(_this, _toConsumableArray(queue));\n }\n });\n _this._isQueuing = true;\n }\n return _this.ga;\n });\n _defineProperty(this, \"event\", function (optionsOrName, params) {\n if (typeof optionsOrName === \"string\") {\n _this._gtag(\"event\", optionsOrName, _this._toGtagOptions(params));\n } else {\n var action = optionsOrName.action,\n category = optionsOrName.category,\n label = optionsOrName.label,\n value = optionsOrName.value,\n nonInteraction = optionsOrName.nonInteraction,\n transport = optionsOrName.transport;\n if (!category || !action) {\n console.warn(\"args.category AND args.action are required in event()\");\n return;\n }\n\n // Required Fields\n var fieldObject = {\n hitType: \"event\",\n eventCategory: (0, _format[\"default\"])(category),\n eventAction: (0, _format[\"default\"])(action)\n };\n\n // Optional Fields\n if (label) {\n fieldObject.eventLabel = (0, _format[\"default\"])(label);\n }\n if (typeof value !== \"undefined\") {\n if (typeof value !== \"number\") {\n console.warn(\"Expected `args.value` arg to be a Number.\");\n } else {\n fieldObject.eventValue = value;\n }\n }\n if (typeof nonInteraction !== \"undefined\") {\n if (typeof nonInteraction !== \"boolean\") {\n console.warn(\"`args.nonInteraction` must be a boolean.\");\n } else {\n fieldObject.nonInteraction = nonInteraction;\n }\n }\n if (typeof transport !== \"undefined\") {\n if (typeof transport !== \"string\") {\n console.warn(\"`args.transport` must be a string.\");\n } else {\n if ([\"beacon\", \"xhr\", \"image\"].indexOf(transport) === -1) {\n console.warn(\"`args.transport` must be either one of these values: `beacon`, `xhr` or `image`\");\n }\n fieldObject.transport = transport;\n }\n }\n _this._gaCommand(\"send\", fieldObject);\n }\n });\n _defineProperty(this, \"send\", function (fieldObject) {\n _this._gaCommand(\"send\", fieldObject);\n });\n this.reset();\n }\n _createClass(GA4, [{\n key: \"gtag\",\n value: function gtag() {\n this._gtag.apply(this, arguments);\n }\n }]);\n return GA4;\n}();\nexports.GA4 = GA4;\nvar _default = new GA4();\nexports[\"default\"] = _default;","\"use strict\";\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = exports.ReactGAImplementation = void 0;\nvar _ga = _interopRequireWildcard(require(\"./ga4\"));\nfunction _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== \"function\") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }\nfunction _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== \"object\" && typeof obj !== \"function\") { return { \"default\": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== \"default\" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj[\"default\"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }\nvar ReactGAImplementation = _ga.GA4;\nexports.ReactGAImplementation = ReactGAImplementation;\nvar _default = _ga[\"default\"];\nexports[\"default\"] = _default;","import { DefaultRoute } from '../router/routes'\n\n// ** Checks if an object is empty (returns boolean)\nexport const isObjEmpty = (obj) => Object.keys(obj).length === 0\n\n// ** Returns K format from a number\nexport const kFormatter = (num) =>\n num > 999 ? `${(num / 1000).toFixed(1)}k` : num\n\n// ** Converts HTML to string\nexport const htmlToString = (html) => html.replace(/<\\/?[^>]+(>|$)/g, '')\n\n// ** Checks if the passed date is today\nconst isToday = (date) => {\n const today = new Date()\n return (\n /* eslint-disable operator-linebreak */\n date.getDate() === today.getDate() &&\n date.getMonth() === today.getMonth() &&\n date.getFullYear() === today.getFullYear()\n /* eslint-enable */\n )\n}\n\n/**\n ** Format and return date in Humanize format\n ** Intl docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format\n ** Intl Constructor: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat\n * @param {String} value date to format\n * @param {Object} formatting Intl object to format with\n */\nexport const formatDate = (\n value,\n formatting = { month: 'short', day: 'numeric', year: 'numeric' }\n) => {\n if (!value) return value\n return new Intl.DateTimeFormat('en-US', formatting).format(new Date(value))\n}\n\n// ** Returns short month of passed date\nexport const formatDateToMonthShort = (value, toTimeForCurrentDay = true) => {\n const date = new Date(value)\n let formatting = { month: 'short', day: 'numeric' }\n\n if (toTimeForCurrentDay && isToday(date)) {\n formatting = { hour: 'numeric', minute: 'numeric' }\n }\n\n return new Intl.DateTimeFormat('en-US', formatting).format(new Date(value))\n}\n\n/**\n ** Return if user is logged in\n ** This is completely up to you and how you want to store the token in your frontend application\n * ? e.g. If you are using cookies to store the application please update this function\n */\n const cookiePrefix = import.meta.env.VITE_COOKIE_PREFIX\n\nexport const isUserLoggedIn = () => localStorage.getItem(`${cookiePrefix}userData`)\nexport const getUserData = () => JSON.parse(localStorage.getItem(`${cookiePrefix}userData`))\n\nexport const getUserDataTemp = () => {\n let item = localStorage.getItem(`${cookiePrefix}userData`)\n if (item) {\n item = JSON.parse(item)\n return {\n ...item.account,\n phone_number: item.identity_type === 'phone' ? item.identity : ''\n }\n } else {\n return null\n }\n}\n\n/**\n ** This function is used for demo purpose route navigation\n ** In real app you won't need this function because your app will navigate to same route for each users regardless of ability\n ** Please note role field is just for showing purpose it's not used by anything in frontend\n ** We are checking role just for ease\n * ? NOTE: If you have different pages to navigate based on user ability then this function can be useful. However, you need to update it.\n * @param {String} userRole Role of user\n */\nexport const getHomeRouteForLoggedInUser = () => {\n return DefaultRoute\n}\n\n// ** React Select Theme Colors\nexport const selectThemeColors = (theme) => ({\n ...theme,\n colors: {\n ...theme.colors,\n primary25: '#7367f01a', // for option hover bg-color\n primary: '#7367f0', // for selected option bg-color\n neutral10: '#7367f0', // for tags bg-color\n neutral20: '#ededed', // for input border-color\n neutral30: '#ededed' // for input hover border-color\n }\n})\n","// ** React Imports\nimport { Suspense } from 'react'\nimport { Navigate } from 'react-router-dom'\nimport { useSelector } from 'react-redux'\n\n// ** Utils\nimport { getHomeRouteForLoggedInUser } from '@utils/Utils'\nimport PropTypes from 'prop-types'\nconst PublicRoute = ({ children, route }) => {\n const { userData } = useSelector(state => state.auth)\n if (route) {\n const restrictedRoute = route.meta && route.meta.restricted\n if (userData && !userData.account_id && restrictedRoute) {\n return \n }\n }\n\n return {children}\n}\n\nPublicRoute.propTypes = {\n children: PropTypes.node,\n route: PropTypes.object\n}\nexport default PublicRoute\n","import PropTypes from 'prop-types'\nimport { Navigate, useParams } from 'react-router-dom';\n\nconst Redirect = ({path}) => {\n const params = useParams()\n if (path) {\n return ;\n }\n}\n\nRedirect.propTypes = {\n path: PropTypes.string.isRequired\n}\nexport default Redirect","// ** React Imports\nimport { lazy } from 'react'\nimport { Navigate } from 'react-router-dom'\n\n// ** Route Components\nimport PublicRoute from '@components/routes/PublicRoute'\n\nconst Dashboard = lazy(() => import('@features/user/UserDashboard'))\nconst Home = lazy(() => import('@features/home/Home'))\nconst AppLayout = lazy(() => import('@components/layout/AppLayout'))\nconst Error = lazy(() => import('@components/error/Error'))\nconst Brand = lazy(() => import('@features/membership/Brand'))\nconst MembershipCart = lazy(() => import('@features/membership/MembershipCart'))\nconst CustomMembershipCart = lazy(() => import('@features/membership/CustomMembershipCart'))\nconst LeaseMembershipCart = lazy(() => import('@features/membership/LeaseMembershipCart'))\nconst CheckoutResult = lazy(() => import('@features/membership/CheckoutResult'))\nconst CheckoutSuccess = lazy(() => import('@features/membership/CheckoutSuccess'))\nconst CheckoutFailure = lazy(() => import('@features/membership/CheckoutFailure'))\nconst Terms = lazy(() => import('@features/Terms'))\nconst Faqs = lazy(() => import('@features/Faqs'))\nconst Refunds = lazy(() => import('@features/Refunds'))\nconst Privacy = lazy(() => import('@features/Privacy'))\nconst About = lazy(() => import('@features/About'))\nconst ScanQrCode = lazy(() => import('@features/membership/ScanQrCode'))\nimport Redirect from '@components/routes/Redirect'\n\n// ** Document title\nconst TemplateTitle =\n '%s - What is Zeno - Zeno powers premium brands to sell and manage digital memberships and collectibles.'\n\n// ** Default Route\nconst DefaultRoute = '/'\n\n// ** Merge Routes\nconst Routes = [\n {\n path: '/home',\n index: true,\n element: \n },\n {\n path: '/',\n element: \n },\n {\n path: '/profile',\n element: \n },\n {\n path: '/error',\n element: \n },\n {\n path: \"/brand/:slug\",\n element: \n },\n {\n path: \"/collection/:id\",\n element: \n },\n {\n path: \"/collections/:id\",\n element: \n },\n {\n path: \"/airdrop/:id\",\n element: \n },\n {\n path: \"/airdrop/:id\",\n element: \n },\n {\n path: \"/scan\",\n element: \n },\n {\n path: \"/collectible/:id\",\n element: \n },\n {\n path: \"/collectible/:id/lease\",\n element: \n },\n {\n path: \"/payment\",\n element: \n },\n {\n path: \"/checkout/:id/success\",\n element: \n },\n {\n path: \"/checkout/:id/failure\",\n element: \n },\n {\n path: \"/faq\",\n element: \n },\n {\n path: \"/terms\",\n element: \n },\n {\n path: \"/privacy\",\n element: \n },\n {\n path: \"/refunds\",\n element: \n },\n {\n path: \"/about\",\n element: \n }\n\n]\n\nexport { DefaultRoute, TemplateTitle, Routes }\n","// ** Router imports\nimport { useRoutes } from 'react-router-dom'\n\n// ** GetRoutes\nimport { Routes } from './routes'\n\n\nconst Router = () => {\n const routes = useRoutes([...Routes])\n return routes\n}\n\nexport default Router","export const GET_USER = '/v1/accounts/user'\nexport const SEND_OTP = '/v1/accounts/otp'\nexport const VERIFY_OTP = '/v1/accounts/otp/verify'\nexport const GET_ACCOUNT = '/v1/accounts'\nexport const GET_CLAIMED_COLLECTIBLES = '/v1/collectibles'\nexport const GET_LOCALITY = '/v1/accounts/locality'\n\nexport const GET_SETTINGS = accountId => {\n return `/v1/wati/settings/${accountId}`\n}\nexport const CHECK_TOKEN = '/v1/accounts/expiry'\n\nexport const GET_COLLECTION_WITH_ID = collectionId =>\n `/v1/collections/${collectionId}`\n\nexport const GET_COLLECTION_COLLECTIBLES = collectionId => {\n return `/v1/collections/${collectionId}/collectibles`\n}\n\nexport const PAY_COLLECTION = collectionId =>\n `/v1/collections/${collectionId}/purchase`\nexport const MINT_COLLECTION = collectionId =>\n `/v1/collections/${collectionId}/mint`\n\nexport const COLLECTION_PRIVILEGES = `/v1/collections/privileges`\n\nexport const GET_AIRDROP_WITH_ID = airdropId => `/v1/airdrops/${airdropId}`\nexport const PAY_AIRDROP = airdropId => `/v1/airdrops/${airdropId}/purchase`\nexport const MINT_AIRDROP = airdropId => `/v1/airdrops/${airdropId}/mint`\n\nexport const GET_COLLECTIBLE_WITH_ID = collectibleId =>\n `/v1/collectibles/${collectibleId}/details`\nexport const RENEW_COLLECTIBLE_WITH_ID = collectibleId =>\n `/v1/collectibles/${collectibleId}/renew`\nexport const GET_COLLECTIBLE_RECEIPT = tokenId =>\n `/v1/collectibles/${tokenId}/receipt`\nexport const GET_COLLECTIBLE_APPLE_WALLET_PASS = tokenId =>\n `/v1/collectibles/${tokenId}/applepass`\nexport const ADD_COLLECTIBLE_CHECKIN = tokenId =>\n `/v1/collectibles/${tokenId}/checkins`\nexport const GET_CHECKINS = `/v1/collectibles/checkins` \n\nexport const PRESIGN_UPLOAD_URL = '/v1/s3/uploads'\n\nexport const LEASE_COLLECTIBLE_PURCHASE = tokenId =>\n `/v1/leases/${tokenId}/purchase`\nexport const LEASE_COLLECTIBLE = tokenId => `/v1/leases/${tokenId}/claim`\nexport const LEASE_COLLECTIBLE_LIST = tokenId => `/v1/leases/${tokenId}`\n\nexport const GET_LEASE_DETAILS = leaseId => `/v1/leases/${leaseId}/details`\nexport const LEASE_COLLECTIBLE_FROM_COLLECTION = collectionId =>\n `/v1/collectibles/${collectionId}/lease`\n\nexport const BRAND_CONTACT_FORM =\n 'https://script.google.com/macros/s/AKfycbxJWBaIPvSf7aXN3dx-PYhRXN667RMeWJ1aaq5_lsl3q7jiGGIn7DEsLWlvCGdBAw_1/exec'\n\nexport const GET_BRAND_DETAILS = `/v1/brands`\nexport const ADD_USER_TO_WAITLIST = `/v1/brands/waitlist`\n\nexport const GET_WALLET_HISTORY = `/v1/accounts/wallet_history`\nexport const GET_WALLET_BALANCE = `/v1/accounts/wallet_balance`\nexport const ADD_PAN = `/v1/accounts/pan`\nexport const ADD_BANK = `/v1/accounts/bank`\nexport const GET_ACCOUNTS_BY_ID = accountId => `/v1/accounts/${accountId}`\nexport const GET_ACCOUNTS_BY_PHONE = `/v1/accounts`\n\nexport const CREATE_PAYOUT_TRANSFER = `/v1/payouts/transfers`\nexport const SEARCH_USER = `/v1/accounts/search`\n\nexport const GET_BANK_BY_IFSC_CODE = ifscCode =>\n `https://ifsc.razorpay.com/${ifscCode}`\n\nexport const PAYTM_BANKS_URL =\n 'https://trust.paytm.in/wallet-web/wrapper/getList?channel=web&child_site_id=1&site_id=1&version=2'\n","import axios from 'axios'\nimport * as Sentry from '@sentry/react'\n\n//apply base url for axios\nconst API_URL = import.meta.env.VITE_APP_APISERVER\n\nconst axiosApi = axios.create({\n baseURL: API_URL\n})\nconst cookiePrefix = import.meta.env.VITE_COOKIE_PREFIX\n\naxiosApi.interceptors.request.use(config => {\n const token = localStorage.getItem(`${cookiePrefix}authToken`)\n if (config.headers.Authorization === null) {\n delete config.headers.Authorization\n } else if (token) {\n config.headers.Authorization = `Bearer ${token}`\n } else {\n // config.headers.Authorization = `Bearer ${ANON_AUTH}`\n }\n return config\n})\n\naxiosApi.interceptors.response.use(\n response => {\n console.log(JSON.stringify(response)) // This is logged for sentry breadcrumbs\n return response\n },\n error => {\n Sentry.captureException(error)\n return Promise.reject(error)\n }\n)\n\nexport const handleError = (error, toast) => {\n if (error.response) {\n // The request was made and the server responded with a status code\n // that falls out of the range of 2xx\n console.log(error.response.data)\n console.log(error.response.status)\n console.log(error.response.headers)\n toast({ title: `${error.response.data.data.message}`, status: 'error', duration: 3000, isClosable: true })\n return error.response.data\n } else if (error.request) {\n // The request was made but no response was received\n // `error.request` is an instance of XMLHttpRequest in the browser and an instance of\n // http.ClientRequest in node.js\n console.log(error.request)\n toast({ title: `Network error!`, status: 'error', duration: 3000, isClosable: true })\n return error.request\n } else {\n // Something happened in setting up the request that triggered an Error\n console.log('Error', error.message)\n toast({ title: `${error.message}`, status: 'error', duration: 3000, isClosable: true })\n }\n console.log(error.config)\n}\n\n\nexport const get = async (url, data = {}, headers = {}) => {\n return await axiosApi\n .request({ url, headers, method: 'get', params: data })\n .then((response) => response.data)\n}\n\nexport const post = async (url, data = {}, headers = {}) => {\n return await axiosApi\n .request({ url, headers, method: 'post', data })\n .then(response => response.data)\n}\n\nexport const put = async (url, data = {}, headers = {}) => {\n return await axiosApi\n .request({ url, headers, method: 'put', data })\n .then(response => response.data)\n}\n\nexport const del = async (url, data = {}, headers = {}) => {\n return await axiosApi\n .request({ url, headers, method: 'delete', data })\n .then(response => response.data)\n}\n","// ** Axios Imports\nimport * as url from '@utility/URLHelper'\nimport { post, put, get } from '@utility/APIHelper'\n\nexport async function getUser(params) {\n const response = await post(url.GET_USER, params)\n return response\n}\n\nexport async function checkToken(params) {\n const response = await post(url.CHECK_TOKEN, params)\n return response\n}\n\nexport async function getRefreshToken(params) {\n const response = await put(url.GET_USER, params)\n return response\n}\n\nexport async function setIdentity(params) {\n const response = await put(url.GET_ACCOUNT, params)\n return response\n}\n\nexport async function sendOTPService(params) {\n const response = await post(url.SEND_OTP, params)\n return response\n}\n\nexport async function verifyOTPService(params) {\n const response = await post(url.VERIFY_OTP, params)\n return response\n}\n\nexport async function findAccount(params) {\n const response = await get(url.GET_ACCOUNTS_BY_PHONE, params)\n return response\n}","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\r\n */\r\nconst CONSTANTS = {\r\n /**\r\n * @define {boolean} Whether this is the client Node.js SDK.\r\n */\r\n NODE_CLIENT: false,\r\n /**\r\n * @define {boolean} Whether this is the Admin Node.js SDK.\r\n */\r\n NODE_ADMIN: false,\r\n /**\r\n * Firebase SDK Version\r\n */\r\n SDK_VERSION: '${JSCORE_VERSION}'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Throws an error if the provided assertion is falsy\r\n */\r\nconst assert = function (assertion, message) {\r\n if (!assertion) {\r\n throw assertionError(message);\r\n }\r\n};\r\n/**\r\n * Returns an Error object suitable for throwing.\r\n */\r\nconst assertionError = function (message) {\r\n return new Error('Firebase Database (' +\r\n CONSTANTS.SDK_VERSION +\r\n ') INTERNAL ASSERT FAILED: ' +\r\n message);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst stringToByteArray$1 = function (str) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if ((c & 0xfc00) === 0xd800 &&\r\n i + 1 < str.length &&\r\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\r\n // Surrogate Pair\r\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Turns an array of numbers into the string given by the concatenation of the\r\n * characters to which the numbers correspond.\r\n * @param bytes Array of numbers representing characters.\r\n * @return Stringification of the array.\r\n */\r\nconst byteArrayToString = function (bytes) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let pos = 0, c = 0;\r\n while (pos < bytes.length) {\r\n const c1 = bytes[pos++];\r\n if (c1 < 128) {\r\n out[c++] = String.fromCharCode(c1);\r\n }\r\n else if (c1 > 191 && c1 < 224) {\r\n const c2 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\r\n }\r\n else if (c1 > 239 && c1 < 365) {\r\n // Surrogate Pair\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n const c4 = bytes[pos++];\r\n const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\r\n 0x10000;\r\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\r\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\r\n }\r\n else {\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\r\n }\r\n }\r\n return out.join('');\r\n};\r\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\r\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\r\n// Static lookup maps, lazily populated by init_()\r\nconst base64 = {\r\n /**\r\n * Maps bytes to characters.\r\n */\r\n byteToCharMap_: null,\r\n /**\r\n * Maps characters to bytes.\r\n */\r\n charToByteMap_: null,\r\n /**\r\n * Maps bytes to websafe characters.\r\n * @private\r\n */\r\n byteToCharMapWebSafe_: null,\r\n /**\r\n * Maps websafe characters to bytes.\r\n * @private\r\n */\r\n charToByteMapWebSafe_: null,\r\n /**\r\n * Our default alphabet, shared between\r\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\r\n */\r\n ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\r\n /**\r\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\r\n */\r\n get ENCODED_VALS() {\r\n return this.ENCODED_VALS_BASE + '+/=';\r\n },\r\n /**\r\n * Our websafe alphabet.\r\n */\r\n get ENCODED_VALS_WEBSAFE() {\r\n return this.ENCODED_VALS_BASE + '-_.';\r\n },\r\n /**\r\n * Whether this browser supports the atob and btoa functions. This extension\r\n * started at Mozilla but is now implemented by many browsers. We use the\r\n * ASSUME_* variables to avoid pulling in the full useragent detection library\r\n * but still allowing the standard per-browser compilations.\r\n *\r\n */\r\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\r\n /**\r\n * Base64-encode an array of bytes.\r\n *\r\n * @param input An array of bytes (numbers with\r\n * value in [0, 255]) to encode.\r\n * @param webSafe Boolean indicating we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeByteArray(input, webSafe) {\r\n if (!Array.isArray(input)) {\r\n throw Error('encodeByteArray takes an array as a parameter');\r\n }\r\n this.init_();\r\n const byteToCharMap = webSafe\r\n ? this.byteToCharMapWebSafe_\r\n : this.byteToCharMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length; i += 3) {\r\n const byte1 = input[i];\r\n const haveByte2 = i + 1 < input.length;\r\n const byte2 = haveByte2 ? input[i + 1] : 0;\r\n const haveByte3 = i + 2 < input.length;\r\n const byte3 = haveByte3 ? input[i + 2] : 0;\r\n const outByte1 = byte1 >> 2;\r\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\r\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\r\n let outByte4 = byte3 & 0x3f;\r\n if (!haveByte3) {\r\n outByte4 = 64;\r\n if (!haveByte2) {\r\n outByte3 = 64;\r\n }\r\n }\r\n output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\r\n }\r\n return output.join('');\r\n },\r\n /**\r\n * Base64-encode a string.\r\n *\r\n * @param input A string to encode.\r\n * @param webSafe If true, we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return btoa(input);\r\n }\r\n return this.encodeByteArray(stringToByteArray$1(input), webSafe);\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * @param input to decode.\r\n * @param webSafe True if we should use the\r\n * alternative alphabet.\r\n * @return string representing the decoded value.\r\n */\r\n decodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return atob(input);\r\n }\r\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * In base-64 decoding, groups of four characters are converted into three\r\n * bytes. If the encoder did not apply padding, the input length may not\r\n * be a multiple of 4.\r\n *\r\n * In this case, the last group will have fewer than 4 characters, and\r\n * padding will be inferred. If the group has one or two characters, it decodes\r\n * to one byte. If the group has three characters, it decodes to two bytes.\r\n *\r\n * @param input Input to decode.\r\n * @param webSafe True if we should use the web-safe alphabet.\r\n * @return bytes representing the decoded value.\r\n */\r\n decodeStringToByteArray(input, webSafe) {\r\n this.init_();\r\n const charToByteMap = webSafe\r\n ? this.charToByteMapWebSafe_\r\n : this.charToByteMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length;) {\r\n const byte1 = charToByteMap[input.charAt(i++)];\r\n const haveByte2 = i < input.length;\r\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\r\n ++i;\r\n const haveByte3 = i < input.length;\r\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n const haveByte4 = i < input.length;\r\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\r\n throw new DecodeBase64StringError();\r\n }\r\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\r\n output.push(outByte1);\r\n if (byte3 !== 64) {\r\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\r\n output.push(outByte2);\r\n if (byte4 !== 64) {\r\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\r\n output.push(outByte3);\r\n }\r\n }\r\n }\r\n return output;\r\n },\r\n /**\r\n * Lazy static initialization function. Called before\r\n * accessing any of the static map variables.\r\n * @private\r\n */\r\n init_() {\r\n if (!this.byteToCharMap_) {\r\n this.byteToCharMap_ = {};\r\n this.charToByteMap_ = {};\r\n this.byteToCharMapWebSafe_ = {};\r\n this.charToByteMapWebSafe_ = {};\r\n // We want quick mappings back and forth, so we precompute two maps.\r\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\r\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\r\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\r\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\r\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\r\n // Be forgiving when decoding and correctly decode both encodings.\r\n if (i >= this.ENCODED_VALS_BASE.length) {\r\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\r\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\r\n }\r\n }\r\n }\r\n }\r\n};\r\n/**\r\n * An error encountered while decoding base64 string.\r\n */\r\nclass DecodeBase64StringError extends Error {\r\n constructor() {\r\n super(...arguments);\r\n this.name = 'DecodeBase64StringError';\r\n }\r\n}\r\n/**\r\n * URL-safe base64 encoding\r\n */\r\nconst base64Encode = function (str) {\r\n const utf8Bytes = stringToByteArray$1(str);\r\n return base64.encodeByteArray(utf8Bytes, true);\r\n};\r\n/**\r\n * URL-safe base64 encoding (without \".\" padding in the end).\r\n * e.g. Used in JSON Web Token (JWT) parts.\r\n */\r\nconst base64urlEncodeWithoutPadding = function (str) {\r\n // Use base64url encoding and remove padding in the end (dot characters).\r\n return base64Encode(str).replace(/\\./g, '');\r\n};\r\n/**\r\n * URL-safe base64 decoding\r\n *\r\n * NOTE: DO NOT use the global atob() function - it does NOT support the\r\n * base64Url variant encoding.\r\n *\r\n * @param str To be decoded\r\n * @return Decoded result, if possible\r\n */\r\nconst base64Decode = function (str) {\r\n try {\r\n return base64.decodeString(str, true);\r\n }\r\n catch (e) {\r\n console.error('base64Decode failed: ', e);\r\n }\r\n return null;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Do a deep-copy of basic JavaScript Objects or Arrays.\r\n */\r\nfunction deepCopy(value) {\r\n return deepExtend(undefined, value);\r\n}\r\n/**\r\n * Copy properties from source to target (recursively allows extension\r\n * of Objects and Arrays). Scalar values in the target are over-written.\r\n * If target is undefined, an object of the appropriate type will be created\r\n * (and returned).\r\n *\r\n * We recursively copy all child properties of plain Objects in the source- so\r\n * that namespace- like dictionaries are merged.\r\n *\r\n * Note that the target can be a function, in which case the properties in\r\n * the source Object are copied onto it as static properties of the Function.\r\n *\r\n * Note: we don't merge __proto__ to prevent prototype pollution\r\n */\r\nfunction deepExtend(target, source) {\r\n if (!(source instanceof Object)) {\r\n return source;\r\n }\r\n switch (source.constructor) {\r\n case Date:\r\n // Treat Dates like scalars; if the target date object had any child\r\n // properties - they will be lost!\r\n const dateValue = source;\r\n return new Date(dateValue.getTime());\r\n case Object:\r\n if (target === undefined) {\r\n target = {};\r\n }\r\n break;\r\n case Array:\r\n // Always copy the array source and overwrite the target.\r\n target = [];\r\n break;\r\n default:\r\n // Not a plain Object - treat it as a scalar.\r\n return source;\r\n }\r\n for (const prop in source) {\r\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\r\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\r\n continue;\r\n }\r\n target[prop] = deepExtend(target[prop], source[prop]);\r\n }\r\n return target;\r\n}\r\nfunction isValidKey(key) {\r\n return key !== '__proto__';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Polyfill for `globalThis` object.\r\n * @returns the `globalThis` object for the given environment.\r\n * @public\r\n */\r\nfunction getGlobal() {\r\n if (typeof self !== 'undefined') {\r\n return self;\r\n }\r\n if (typeof window !== 'undefined') {\r\n return window;\r\n }\r\n if (typeof global !== 'undefined') {\r\n return global;\r\n }\r\n throw new Error('Unable to locate global object.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;\r\n/**\r\n * Attempt to read defaults from a JSON string provided to\r\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\r\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\r\n * The dots are in parens because certain compilers (Vite?) cannot\r\n * handle seeing that variable in comments.\r\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\r\n */\r\nconst getDefaultsFromEnvVariable = () => {\r\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\r\n return;\r\n }\r\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\r\n if (defaultsJsonString) {\r\n return JSON.parse(defaultsJsonString);\r\n }\r\n};\r\nconst getDefaultsFromCookie = () => {\r\n if (typeof document === 'undefined') {\r\n return;\r\n }\r\n let match;\r\n try {\r\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\r\n }\r\n catch (e) {\r\n // Some environments such as Angular Universal SSR have a\r\n // `document` object but error on accessing `document.cookie`.\r\n return;\r\n }\r\n const decoded = match && base64Decode(match[1]);\r\n return decoded && JSON.parse(decoded);\r\n};\r\n/**\r\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\r\n * (1) if such an object exists as a property of `globalThis`\r\n * (2) if such an object was provided on a shell environment variable\r\n * (3) if such an object exists in a cookie\r\n * @public\r\n */\r\nconst getDefaults = () => {\r\n try {\r\n return (getDefaultsFromGlobal() ||\r\n getDefaultsFromEnvVariable() ||\r\n getDefaultsFromCookie());\r\n }\r\n catch (e) {\r\n /**\r\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\r\n * to any environment case we have not accounted for. Log to\r\n * info instead of swallowing so we can find these unknown cases\r\n * and add paths for them if needed.\r\n */\r\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\r\n return;\r\n }\r\n};\r\n/**\r\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHost = (productName) => { var _a, _b; return (_b = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName]; };\r\n/**\r\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHostnameAndPort = (productName) => {\r\n const host = getDefaultEmulatorHost(productName);\r\n if (!host) {\r\n return undefined;\r\n }\r\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\r\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\r\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\r\n }\r\n // eslint-disable-next-line no-restricted-globals\r\n const port = parseInt(host.substring(separatorIndex + 1), 10);\r\n if (host[0] === '[') {\r\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\r\n return [host.substring(1, separatorIndex - 1), port];\r\n }\r\n else {\r\n return [host.substring(0, separatorIndex), port];\r\n }\r\n};\r\n/**\r\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\r\n * @public\r\n */\r\nconst getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };\r\n/**\r\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\r\n * prefixed by \"_\")\r\n * @public\r\n */\r\nconst getExperimentalSetting = (name) => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; };\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Deferred {\r\n constructor() {\r\n this.reject = () => { };\r\n this.resolve = () => { };\r\n this.promise = new Promise((resolve, reject) => {\r\n this.resolve = resolve;\r\n this.reject = reject;\r\n });\r\n }\r\n /**\r\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\r\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\r\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\r\n */\r\n wrapCallback(callback) {\r\n return (error, value) => {\r\n if (error) {\r\n this.reject(error);\r\n }\r\n else {\r\n this.resolve(value);\r\n }\r\n if (typeof callback === 'function') {\r\n // Attaching noop handler just in case developer wasn't expecting\r\n // promises\r\n this.promise.catch(() => { });\r\n // Some of our callbacks don't expect a value and our own tests\r\n // assert that the parameter length is 1\r\n if (callback.length === 1) {\r\n callback(error);\r\n }\r\n else {\r\n callback(error, value);\r\n }\r\n }\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createMockUserToken(token, projectId) {\r\n if (token.uid) {\r\n throw new Error('The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.');\r\n }\r\n // Unsecured JWTs use \"none\" as the algorithm.\r\n const header = {\r\n alg: 'none',\r\n type: 'JWT'\r\n };\r\n const project = projectId || 'demo-project';\r\n const iat = token.iat || 0;\r\n const sub = token.sub || token.user_id;\r\n if (!sub) {\r\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\r\n }\r\n const payload = Object.assign({ \r\n // Set all required fields to decent defaults\r\n iss: `https://securetoken.google.com/${project}`, aud: project, iat, exp: iat + 3600, auth_time: iat, sub, user_id: sub, firebase: {\r\n sign_in_provider: 'custom',\r\n identities: {}\r\n } }, token);\r\n // Unsecured JWTs use the empty string as a signature.\r\n const signature = '';\r\n return [\r\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\r\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\r\n signature\r\n ].join('.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns navigator.userAgent string or '' if it's not defined.\r\n * @return user agent string\r\n */\r\nfunction getUA() {\r\n if (typeof navigator !== 'undefined' &&\r\n typeof navigator['userAgent'] === 'string') {\r\n return navigator['userAgent'];\r\n }\r\n else {\r\n return '';\r\n }\r\n}\r\n/**\r\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\r\n *\r\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\r\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\r\n * wait for a callback.\r\n */\r\nfunction isMobileCordova() {\r\n return (typeof window !== 'undefined' &&\r\n // @ts-ignore Setting up an broadly applicable index signature for Window\r\n // just to deal with this case would probably be a bad idea.\r\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\r\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));\r\n}\r\n/**\r\n * Detect Node.js.\r\n *\r\n * @return true if Node.js environment is detected or specified.\r\n */\r\n// Node detection logic from: https://github.com/iliakan/detect-node/\r\nfunction isNode() {\r\n var _a;\r\n const forceEnvironment = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.forceEnvironment;\r\n if (forceEnvironment === 'node') {\r\n return true;\r\n }\r\n else if (forceEnvironment === 'browser') {\r\n return false;\r\n }\r\n try {\r\n return (Object.prototype.toString.call(global.process) === '[object process]');\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Detect Browser Environment\r\n */\r\nfunction isBrowser() {\r\n return typeof self === 'object' && self.self === self;\r\n}\r\nfunction isBrowserExtension() {\r\n const runtime = typeof chrome === 'object'\r\n ? chrome.runtime\r\n : typeof browser === 'object'\r\n ? browser.runtime\r\n : undefined;\r\n return typeof runtime === 'object' && runtime.id !== undefined;\r\n}\r\n/**\r\n * Detect React Native.\r\n *\r\n * @return true if ReactNative environment is detected.\r\n */\r\nfunction isReactNative() {\r\n return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');\r\n}\r\n/** Detects Electron apps. */\r\nfunction isElectron() {\r\n return getUA().indexOf('Electron/') >= 0;\r\n}\r\n/** Detects Internet Explorer. */\r\nfunction isIE() {\r\n const ua = getUA();\r\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\r\n}\r\n/** Detects Universal Windows Platform apps. */\r\nfunction isUWP() {\r\n return getUA().indexOf('MSAppHost/') >= 0;\r\n}\r\n/**\r\n * Detect whether the current SDK build is the Node version.\r\n *\r\n * @return true if it's the Node SDK build.\r\n */\r\nfunction isNodeSdk() {\r\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\r\n}\r\n/** Returns true if we are running in Safari. */\r\nfunction isSafari() {\r\n return (!isNode() &&\r\n !!navigator.userAgent &&\r\n navigator.userAgent.includes('Safari') &&\r\n !navigator.userAgent.includes('Chrome'));\r\n}\r\n/**\r\n * This method checks if indexedDB is supported by current browser/service worker context\r\n * @return true if indexedDB is supported by current browser/service worker context\r\n */\r\nfunction isIndexedDBAvailable() {\r\n try {\r\n return typeof indexedDB === 'object';\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\r\n * if errors occur during the database open operation.\r\n *\r\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\r\n * private browsing)\r\n */\r\nfunction validateIndexedDBOpenable() {\r\n return new Promise((resolve, reject) => {\r\n try {\r\n let preExist = true;\r\n const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';\r\n const request = self.indexedDB.open(DB_CHECK_NAME);\r\n request.onsuccess = () => {\r\n request.result.close();\r\n // delete database only when it doesn't pre-exist\r\n if (!preExist) {\r\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\r\n }\r\n resolve(true);\r\n };\r\n request.onupgradeneeded = () => {\r\n preExist = false;\r\n };\r\n request.onerror = () => {\r\n var _a;\r\n reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');\r\n };\r\n }\r\n catch (error) {\r\n reject(error);\r\n }\r\n });\r\n}\r\n/**\r\n *\r\n * This method checks whether cookie is enabled within current browser\r\n * @return true if cookie is enabled within current browser\r\n */\r\nfunction areCookiesEnabled() {\r\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\r\n return false;\r\n }\r\n return true;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Standardized Firebase Error.\r\n *\r\n * Usage:\r\n *\r\n * // Typescript string literals for type-safe codes\r\n * type Err =\r\n * 'unknown' |\r\n * 'object-not-found'\r\n * ;\r\n *\r\n * // Closure enum for type-safe error codes\r\n * // at-enum {string}\r\n * var Err = {\r\n * UNKNOWN: 'unknown',\r\n * OBJECT_NOT_FOUND: 'object-not-found',\r\n * }\r\n *\r\n * let errors: Map = {\r\n * 'generic-error': \"Unknown error\",\r\n * 'file-not-found': \"Could not find file: {$file}\",\r\n * };\r\n *\r\n * // Type-safe function - must pass a valid error code as param.\r\n * let error = new ErrorFactory('service', 'Service', errors);\r\n *\r\n * ...\r\n * throw error.create(Err.GENERIC);\r\n * ...\r\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\r\n * ...\r\n * // Service: Could not file file: foo.txt (service/file-not-found).\r\n *\r\n * catch (e) {\r\n * assert(e.message === \"Could not find file: foo.txt.\");\r\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\r\n * console.log(\"Could not read file: \" + e['file']);\r\n * }\r\n * }\r\n */\r\nconst ERROR_NAME = 'FirebaseError';\r\n// Based on code from:\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\r\nclass FirebaseError extends Error {\r\n constructor(\r\n /** The error code for this error. */\r\n code, message, \r\n /** Custom data for this error. */\r\n customData) {\r\n super(message);\r\n this.code = code;\r\n this.customData = customData;\r\n /** The custom name for all FirebaseErrors. */\r\n this.name = ERROR_NAME;\r\n // Fix For ES5\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, FirebaseError.prototype);\r\n // Maintains proper stack trace for where our error was thrown.\r\n // Only available on V8.\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\r\n }\r\n }\r\n}\r\nclass ErrorFactory {\r\n constructor(service, serviceName, errors) {\r\n this.service = service;\r\n this.serviceName = serviceName;\r\n this.errors = errors;\r\n }\r\n create(code, ...data) {\r\n const customData = data[0] || {};\r\n const fullCode = `${this.service}/${code}`;\r\n const template = this.errors[code];\r\n const message = template ? replaceTemplate(template, customData) : 'Error';\r\n // Service Name: Error message (service/code).\r\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\r\n const error = new FirebaseError(fullCode, fullMessage, customData);\r\n return error;\r\n }\r\n}\r\nfunction replaceTemplate(template, data) {\r\n return template.replace(PATTERN, (_, key) => {\r\n const value = data[key];\r\n return value != null ? String(value) : `<${key}?>`;\r\n });\r\n}\r\nconst PATTERN = /\\{\\$([^}]+)}/g;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Evaluates a JSON string into a javascript object.\r\n *\r\n * @param {string} str A string containing JSON.\r\n * @return {*} The javascript object representing the specified JSON.\r\n */\r\nfunction jsonEval(str) {\r\n return JSON.parse(str);\r\n}\r\n/**\r\n * Returns JSON representing a javascript object.\r\n * @param {*} data Javascript object to be stringified.\r\n * @return {string} The JSON contents of the object.\r\n */\r\nfunction stringify(data) {\r\n return JSON.stringify(data);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Decodes a Firebase auth. token into constituent parts.\r\n *\r\n * Notes:\r\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst decode = function (token) {\r\n let header = {}, claims = {}, data = {}, signature = '';\r\n try {\r\n const parts = token.split('.');\r\n header = jsonEval(base64Decode(parts[0]) || '');\r\n claims = jsonEval(base64Decode(parts[1]) || '');\r\n signature = parts[2];\r\n data = claims['d'] || {};\r\n delete claims['d'];\r\n }\r\n catch (e) { }\r\n return {\r\n header,\r\n claims,\r\n data,\r\n signature\r\n };\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\r\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidTimestamp = function (token) {\r\n const claims = decode(token).claims;\r\n const now = Math.floor(new Date().getTime() / 1000);\r\n let validSince = 0, validUntil = 0;\r\n if (typeof claims === 'object') {\r\n if (claims.hasOwnProperty('nbf')) {\r\n validSince = claims['nbf'];\r\n }\r\n else if (claims.hasOwnProperty('iat')) {\r\n validSince = claims['iat'];\r\n }\r\n if (claims.hasOwnProperty('exp')) {\r\n validUntil = claims['exp'];\r\n }\r\n else {\r\n // token will expire after 24h by default\r\n validUntil = validSince + 86400;\r\n }\r\n }\r\n return (!!now &&\r\n !!validSince &&\r\n !!validUntil &&\r\n now >= validSince &&\r\n now <= validUntil);\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\r\n *\r\n * Notes:\r\n * - May return null if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst issuedAtTime = function (token) {\r\n const claims = decode(token).claims;\r\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\r\n return claims['iat'];\r\n }\r\n return null;\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidFormat = function (token) {\r\n const decoded = decode(token), claims = decoded.claims;\r\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\r\n};\r\n/**\r\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isAdmin = function (token) {\r\n const claims = decode(token).claims;\r\n return typeof claims === 'object' && claims['admin'] === true;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction contains(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n}\r\nfunction safeGet(obj, key) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return obj[key];\r\n }\r\n else {\r\n return undefined;\r\n }\r\n}\r\nfunction isEmpty(obj) {\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction map(obj, fn, contextObj) {\r\n const res = {};\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n res[key] = fn.call(contextObj, obj[key], key, obj);\r\n }\r\n }\r\n return res;\r\n}\r\n/**\r\n * Deep equal two objects. Support Arrays and Objects.\r\n */\r\nfunction deepEqual(a, b) {\r\n if (a === b) {\r\n return true;\r\n }\r\n const aKeys = Object.keys(a);\r\n const bKeys = Object.keys(b);\r\n for (const k of aKeys) {\r\n if (!bKeys.includes(k)) {\r\n return false;\r\n }\r\n const aProp = a[k];\r\n const bProp = b[k];\r\n if (isObject(aProp) && isObject(bProp)) {\r\n if (!deepEqual(aProp, bProp)) {\r\n return false;\r\n }\r\n }\r\n else if (aProp !== bProp) {\r\n return false;\r\n }\r\n }\r\n for (const k of bKeys) {\r\n if (!aKeys.includes(k)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isObject(thing) {\r\n return thing !== null && typeof thing === 'object';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\r\n * @internal\r\n */\r\nfunction promiseWithTimeout(promise, timeInMS = 2000) {\r\n const deferredPromise = new Deferred();\r\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\r\n promise.then(deferredPromise.resolve, deferredPromise.reject);\r\n return deferredPromise.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\r\n * params object (e.g. {arg: 'val', arg2: 'val2'})\r\n * Note: You must prepend it with ? when adding it to a URL.\r\n */\r\nfunction querystring(querystringParams) {\r\n const params = [];\r\n for (const [key, value] of Object.entries(querystringParams)) {\r\n if (Array.isArray(value)) {\r\n value.forEach(arrayVal => {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\r\n });\r\n }\r\n else {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\r\n }\r\n }\r\n return params.length ? '&' + params.join('&') : '';\r\n}\r\n/**\r\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\r\n * (e.g. {arg: 'val', arg2: 'val2'})\r\n */\r\nfunction querystringDecode(querystring) {\r\n const obj = {};\r\n const tokens = querystring.replace(/^\\?/, '').split('&');\r\n tokens.forEach(token => {\r\n if (token) {\r\n const [key, value] = token.split('=');\r\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\r\n }\r\n });\r\n return obj;\r\n}\r\n/**\r\n * Extract the query string part of a URL, including the leading question mark (if present).\r\n */\r\nfunction extractQuerystring(url) {\r\n const queryStart = url.indexOf('?');\r\n if (!queryStart) {\r\n return '';\r\n }\r\n const fragmentStart = url.indexOf('#', queryStart);\r\n return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview SHA-1 cryptographic hash.\r\n * Variable names follow the notation in FIPS PUB 180-3:\r\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\r\n *\r\n * Usage:\r\n * var sha1 = new sha1();\r\n * sha1.update(bytes);\r\n * var hash = sha1.digest();\r\n *\r\n * Performance:\r\n * Chrome 23: ~400 Mbit/s\r\n * Firefox 16: ~250 Mbit/s\r\n *\r\n */\r\n/**\r\n * SHA-1 cryptographic hash constructor.\r\n *\r\n * The properties declared here are discussed in the above algorithm document.\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\nclass Sha1 {\r\n constructor() {\r\n /**\r\n * Holds the previous values of accumulated variables a-e in the compress_\r\n * function.\r\n * @private\r\n */\r\n this.chain_ = [];\r\n /**\r\n * A buffer holding the partially computed hash result.\r\n * @private\r\n */\r\n this.buf_ = [];\r\n /**\r\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\r\n * as the message schedule in the docs.\r\n * @private\r\n */\r\n this.W_ = [];\r\n /**\r\n * Contains data needed to pad messages less than 64 bytes.\r\n * @private\r\n */\r\n this.pad_ = [];\r\n /**\r\n * @private {number}\r\n */\r\n this.inbuf_ = 0;\r\n /**\r\n * @private {number}\r\n */\r\n this.total_ = 0;\r\n this.blockSize = 512 / 8;\r\n this.pad_[0] = 128;\r\n for (let i = 1; i < this.blockSize; ++i) {\r\n this.pad_[i] = 0;\r\n }\r\n this.reset();\r\n }\r\n reset() {\r\n this.chain_[0] = 0x67452301;\r\n this.chain_[1] = 0xefcdab89;\r\n this.chain_[2] = 0x98badcfe;\r\n this.chain_[3] = 0x10325476;\r\n this.chain_[4] = 0xc3d2e1f0;\r\n this.inbuf_ = 0;\r\n this.total_ = 0;\r\n }\r\n /**\r\n * Internal compress helper function.\r\n * @param buf Block to compress.\r\n * @param offset Offset of the block in the buffer.\r\n * @private\r\n */\r\n compress_(buf, offset) {\r\n if (!offset) {\r\n offset = 0;\r\n }\r\n const W = this.W_;\r\n // get 16 big endian words\r\n if (typeof buf === 'string') {\r\n for (let i = 0; i < 16; i++) {\r\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\r\n // have a bug that turns the post-increment ++ operator into pre-increment\r\n // during JIT compilation. We have code that depends heavily on SHA-1 for\r\n // correctness and which is affected by this bug, so I've removed all uses\r\n // of post-increment ++ in which the result value is used. We can revert\r\n // this change once the Safari bug\r\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\r\n // most clients have been updated.\r\n W[i] =\r\n (buf.charCodeAt(offset) << 24) |\r\n (buf.charCodeAt(offset + 1) << 16) |\r\n (buf.charCodeAt(offset + 2) << 8) |\r\n buf.charCodeAt(offset + 3);\r\n offset += 4;\r\n }\r\n }\r\n else {\r\n for (let i = 0; i < 16; i++) {\r\n W[i] =\r\n (buf[offset] << 24) |\r\n (buf[offset + 1] << 16) |\r\n (buf[offset + 2] << 8) |\r\n buf[offset + 3];\r\n offset += 4;\r\n }\r\n }\r\n // expand to 80 words\r\n for (let i = 16; i < 80; i++) {\r\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\r\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\r\n }\r\n let a = this.chain_[0];\r\n let b = this.chain_[1];\r\n let c = this.chain_[2];\r\n let d = this.chain_[3];\r\n let e = this.chain_[4];\r\n let f, k;\r\n // TODO(user): Try to unroll this loop to speed up the computation.\r\n for (let i = 0; i < 80; i++) {\r\n if (i < 40) {\r\n if (i < 20) {\r\n f = d ^ (b & (c ^ d));\r\n k = 0x5a827999;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0x6ed9eba1;\r\n }\r\n }\r\n else {\r\n if (i < 60) {\r\n f = (b & c) | (d & (b | c));\r\n k = 0x8f1bbcdc;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0xca62c1d6;\r\n }\r\n }\r\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\r\n e = d;\r\n d = c;\r\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\r\n b = a;\r\n a = t;\r\n }\r\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\r\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\r\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\r\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\r\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\r\n }\r\n update(bytes, length) {\r\n // TODO(johnlenz): tighten the function signature and remove this check\r\n if (bytes == null) {\r\n return;\r\n }\r\n if (length === undefined) {\r\n length = bytes.length;\r\n }\r\n const lengthMinusBlock = length - this.blockSize;\r\n let n = 0;\r\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\r\n const buf = this.buf_;\r\n let inbuf = this.inbuf_;\r\n // The outer while loop should execute at most twice.\r\n while (n < length) {\r\n // When we have no data in the block to top up, we can directly process the\r\n // input buffer (assuming it contains sufficient data). This gives ~25%\r\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\r\n // the data is provided in large chunks (or in multiples of 64 bytes).\r\n if (inbuf === 0) {\r\n while (n <= lengthMinusBlock) {\r\n this.compress_(bytes, n);\r\n n += this.blockSize;\r\n }\r\n }\r\n if (typeof bytes === 'string') {\r\n while (n < length) {\r\n buf[inbuf] = bytes.charCodeAt(n);\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n while (n < length) {\r\n buf[inbuf] = bytes[n];\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n this.inbuf_ = inbuf;\r\n this.total_ += length;\r\n }\r\n /** @override */\r\n digest() {\r\n const digest = [];\r\n let totalBits = this.total_ * 8;\r\n // Add pad 0x80 0x00*.\r\n if (this.inbuf_ < 56) {\r\n this.update(this.pad_, 56 - this.inbuf_);\r\n }\r\n else {\r\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\r\n }\r\n // Add # bits.\r\n for (let i = this.blockSize - 1; i >= 56; i--) {\r\n this.buf_[i] = totalBits & 255;\r\n totalBits /= 256; // Don't use bit-shifting here!\r\n }\r\n this.compress_(this.buf_);\r\n let n = 0;\r\n for (let i = 0; i < 5; i++) {\r\n for (let j = 24; j >= 0; j -= 8) {\r\n digest[n] = (this.chain_[i] >> j) & 255;\r\n ++n;\r\n }\r\n }\r\n return digest;\r\n }\r\n}\n\n/**\r\n * Helper to make a Subscribe function (just like Promise helps make a\r\n * Thenable).\r\n *\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\nfunction createSubscribe(executor, onNoObservers) {\r\n const proxy = new ObserverProxy(executor, onNoObservers);\r\n return proxy.subscribe.bind(proxy);\r\n}\r\n/**\r\n * Implement fan-out for any number of Observers attached via a subscribe\r\n * function.\r\n */\r\nclass ObserverProxy {\r\n /**\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\n constructor(executor, onNoObservers) {\r\n this.observers = [];\r\n this.unsubscribes = [];\r\n this.observerCount = 0;\r\n // Micro-task scheduling by calling task.then().\r\n this.task = Promise.resolve();\r\n this.finalized = false;\r\n this.onNoObservers = onNoObservers;\r\n // Call the executor asynchronously so subscribers that are called\r\n // synchronously after the creation of the subscribe function\r\n // can still receive the very first value generated in the executor.\r\n this.task\r\n .then(() => {\r\n executor(this);\r\n })\r\n .catch(e => {\r\n this.error(e);\r\n });\r\n }\r\n next(value) {\r\n this.forEachObserver((observer) => {\r\n observer.next(value);\r\n });\r\n }\r\n error(error) {\r\n this.forEachObserver((observer) => {\r\n observer.error(error);\r\n });\r\n this.close(error);\r\n }\r\n complete() {\r\n this.forEachObserver((observer) => {\r\n observer.complete();\r\n });\r\n this.close();\r\n }\r\n /**\r\n * Subscribe function that can be used to add an Observer to the fan-out list.\r\n *\r\n * - We require that no event is sent to a subscriber sychronously to their\r\n * call to subscribe().\r\n */\r\n subscribe(nextOrObserver, error, complete) {\r\n let observer;\r\n if (nextOrObserver === undefined &&\r\n error === undefined &&\r\n complete === undefined) {\r\n throw new Error('Missing Observer.');\r\n }\r\n // Assemble an Observer object when passed as callback functions.\r\n if (implementsAnyMethods(nextOrObserver, [\r\n 'next',\r\n 'error',\r\n 'complete'\r\n ])) {\r\n observer = nextOrObserver;\r\n }\r\n else {\r\n observer = {\r\n next: nextOrObserver,\r\n error,\r\n complete\r\n };\r\n }\r\n if (observer.next === undefined) {\r\n observer.next = noop;\r\n }\r\n if (observer.error === undefined) {\r\n observer.error = noop;\r\n }\r\n if (observer.complete === undefined) {\r\n observer.complete = noop;\r\n }\r\n const unsub = this.unsubscribeOne.bind(this, this.observers.length);\r\n // Attempt to subscribe to a terminated Observable - we\r\n // just respond to the Observer with the final error or complete\r\n // event.\r\n if (this.finalized) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n try {\r\n if (this.finalError) {\r\n observer.error(this.finalError);\r\n }\r\n else {\r\n observer.complete();\r\n }\r\n }\r\n catch (e) {\r\n // nothing\r\n }\r\n return;\r\n });\r\n }\r\n this.observers.push(observer);\r\n return unsub;\r\n }\r\n // Unsubscribe is synchronous - we guarantee that no events are sent to\r\n // any unsubscribed Observer.\r\n unsubscribeOne(i) {\r\n if (this.observers === undefined || this.observers[i] === undefined) {\r\n return;\r\n }\r\n delete this.observers[i];\r\n this.observerCount -= 1;\r\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\r\n this.onNoObservers(this);\r\n }\r\n }\r\n forEachObserver(fn) {\r\n if (this.finalized) {\r\n // Already closed by previous event....just eat the additional values.\r\n return;\r\n }\r\n // Since sendOne calls asynchronously - there is no chance that\r\n // this.observers will become undefined.\r\n for (let i = 0; i < this.observers.length; i++) {\r\n this.sendOne(i, fn);\r\n }\r\n }\r\n // Call the Observer via one of it's callback function. We are careful to\r\n // confirm that the observe has not been unsubscribed since this asynchronous\r\n // function had been queued.\r\n sendOne(i, fn) {\r\n // Execute the callback asynchronously\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n if (this.observers !== undefined && this.observers[i] !== undefined) {\r\n try {\r\n fn(this.observers[i]);\r\n }\r\n catch (e) {\r\n // Ignore exceptions raised in Observers or missing methods of an\r\n // Observer.\r\n // Log error to console. b/31404806\r\n if (typeof console !== 'undefined' && console.error) {\r\n console.error(e);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n close(err) {\r\n if (this.finalized) {\r\n return;\r\n }\r\n this.finalized = true;\r\n if (err !== undefined) {\r\n this.finalError = err;\r\n }\r\n // Proxy is no longer needed - garbage collect references\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n this.observers = undefined;\r\n this.onNoObservers = undefined;\r\n });\r\n }\r\n}\r\n/** Turn synchronous function into one called asynchronously. */\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction async(fn, onError) {\r\n return (...args) => {\r\n Promise.resolve(true)\r\n .then(() => {\r\n fn(...args);\r\n })\r\n .catch((error) => {\r\n if (onError) {\r\n onError(error);\r\n }\r\n });\r\n };\r\n}\r\n/**\r\n * Return true if the object passed in implements any of the named methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return false;\r\n }\r\n for (const method of methods) {\r\n if (method in obj && typeof obj[method] === 'function') {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction noop() {\r\n // do nothing\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Check to make sure the appropriate number of arguments are provided for a public function.\r\n * Throws an error if it fails.\r\n *\r\n * @param fnName The function name\r\n * @param minCount The minimum number of arguments to allow for the function call\r\n * @param maxCount The maximum number of argument to allow for the function call\r\n * @param argCount The actual number of arguments provided.\r\n */\r\nconst validateArgCount = function (fnName, minCount, maxCount, argCount) {\r\n let argError;\r\n if (argCount < minCount) {\r\n argError = 'at least ' + minCount;\r\n }\r\n else if (argCount > maxCount) {\r\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\r\n }\r\n if (argError) {\r\n const error = fnName +\r\n ' failed: Was called with ' +\r\n argCount +\r\n (argCount === 1 ? ' argument.' : ' arguments.') +\r\n ' Expects ' +\r\n argError +\r\n '.';\r\n throw new Error(error);\r\n }\r\n};\r\n/**\r\n * Generates a string to prefix an error message about failed argument validation\r\n *\r\n * @param fnName The function name\r\n * @param argName The name of the argument\r\n * @return The prefix to add to the error thrown for validation.\r\n */\r\nfunction errorPrefix(fnName, argName) {\r\n return `${fnName} failed: ${argName} argument `;\r\n}\r\n/**\r\n * @param fnName\r\n * @param argumentNumber\r\n * @param namespace\r\n * @param optional\r\n */\r\nfunction validateNamespace(fnName, namespace, optional) {\r\n if (optional && !namespace) {\r\n return;\r\n }\r\n if (typeof namespace !== 'string') {\r\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\r\n throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');\r\n }\r\n}\r\nfunction validateCallback(fnName, argumentName, \r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\ncallback, optional) {\r\n if (optional && !callback) {\r\n return;\r\n }\r\n if (typeof callback !== 'function') {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');\r\n }\r\n}\r\nfunction validateContextObject(fnName, argumentName, context, optional) {\r\n if (optional && !context) {\r\n return;\r\n }\r\n if (typeof context !== 'object' || context === null) {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\r\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\r\n// so it's been modified.\r\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\r\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\r\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\r\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\r\n// pair).\r\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\r\n/**\r\n * @param {string} str\r\n * @return {Array}\r\n */\r\nconst stringToByteArray = function (str) {\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n // Is this the lead surrogate in a surrogate pair?\r\n if (c >= 0xd800 && c <= 0xdbff) {\r\n const high = c - 0xd800; // the high 10 bits.\r\n i++;\r\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\r\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\r\n c = 0x10000 + (high << 10) + low;\r\n }\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if (c < 65536) {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Calculate length without actually converting; useful for doing cheaper validation.\r\n * @param {string} str\r\n * @return {number}\r\n */\r\nconst stringLength = function (str) {\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n const c = str.charCodeAt(i);\r\n if (c < 128) {\r\n p++;\r\n }\r\n else if (c < 2048) {\r\n p += 2;\r\n }\r\n else if (c >= 0xd800 && c <= 0xdbff) {\r\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\r\n p += 4;\r\n i++; // skip trail surrogate.\r\n }\r\n else {\r\n p += 3;\r\n }\r\n }\r\n return p;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Copied from https://stackoverflow.com/a/2117523\r\n * Generates a new uuid.\r\n * @public\r\n */\r\nconst uuidv4 = function () {\r\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\r\n const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;\r\n return v.toString(16);\r\n });\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The amount of milliseconds to exponentially increase.\r\n */\r\nconst DEFAULT_INTERVAL_MILLIS = 1000;\r\n/**\r\n * The factor to backoff by.\r\n * Should be a number greater than 1.\r\n */\r\nconst DEFAULT_BACKOFF_FACTOR = 2;\r\n/**\r\n * The maximum milliseconds to increase to.\r\n *\r\n *

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

Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n const randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return `${i}`;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n const cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n const dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\nexport { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\n","import { Deferred } from '@firebase/util';\n\n/**\r\n * Component for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass Component {\r\n /**\r\n *\r\n * @param name The public service name, e.g. app, auth, firestore, database\r\n * @param instanceFactory Service factory responsible for creating the public interface\r\n * @param type whether the service provided by the component is public or private\r\n */\r\n constructor(name, instanceFactory, type) {\r\n this.name = name;\r\n this.instanceFactory = instanceFactory;\r\n this.type = type;\r\n this.multipleInstances = false;\r\n /**\r\n * Properties to be added to the service namespace\r\n */\r\n this.serviceProps = {};\r\n this.instantiationMode = \"LAZY\" /* InstantiationMode.LAZY */;\r\n this.onInstanceCreated = null;\r\n }\r\n setInstantiationMode(mode) {\r\n this.instantiationMode = mode;\r\n return this;\r\n }\r\n setMultipleInstances(multipleInstances) {\r\n this.multipleInstances = multipleInstances;\r\n return this;\r\n }\r\n setServiceProps(props) {\r\n this.serviceProps = props;\r\n return this;\r\n }\r\n setInstanceCreatedCallback(callback) {\r\n this.onInstanceCreated = callback;\r\n return this;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\r\n * NameServiceMapping[T] is an alias for the type of the instance\r\n */\r\nclass Provider {\r\n constructor(name, container) {\r\n this.name = name;\r\n this.container = container;\r\n this.component = null;\r\n this.instances = new Map();\r\n this.instancesDeferred = new Map();\r\n this.instancesOptions = new Map();\r\n this.onInitCallbacks = new Map();\r\n }\r\n /**\r\n * @param identifier A provider can provide mulitple instances of a service\r\n * if this.component.multipleInstances is true.\r\n */\r\n get(identifier) {\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\r\n const deferred = new Deferred();\r\n this.instancesDeferred.set(normalizedIdentifier, deferred);\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n // initialize the service if it can be auto-initialized\r\n try {\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n if (instance) {\r\n deferred.resolve(instance);\r\n }\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception during get(), it should not cause\r\n // a fatal error. We just return the unresolved promise in this case.\r\n }\r\n }\r\n }\r\n return this.instancesDeferred.get(normalizedIdentifier).promise;\r\n }\r\n getImmediate(options) {\r\n var _a;\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);\r\n const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n try {\r\n return this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n }\r\n catch (e) {\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw e;\r\n }\r\n }\r\n }\r\n else {\r\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw Error(`Service ${this.name} is not available`);\r\n }\r\n }\r\n }\r\n getComponent() {\r\n return this.component;\r\n }\r\n setComponent(component) {\r\n if (component.name !== this.name) {\r\n throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);\r\n }\r\n if (this.component) {\r\n throw Error(`Component for ${this.name} has already been provided`);\r\n }\r\n this.component = component;\r\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\r\n if (!this.shouldAutoInitialize()) {\r\n return;\r\n }\r\n // if the service is eager, initialize the default instance\r\n if (isComponentEager(component)) {\r\n try {\r\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\r\n }\r\n catch (e) {\r\n // when the instance factory for an eager Component throws an exception during the eager\r\n // initialization, it should not cause a fatal error.\r\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\r\n // a fatal error in this case?\r\n }\r\n }\r\n // Create service instances for the pending promises and resolve them\r\n // NOTE: if this.multipleInstances is false, only the default instance will be created\r\n // and all promises with resolve with it regardless of the identifier.\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n try {\r\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n instanceDeferred.resolve(instance);\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception, it should not cause\r\n // a fatal error. We just leave the promise unresolved.\r\n }\r\n }\r\n }\r\n clearInstance(identifier = DEFAULT_ENTRY_NAME) {\r\n this.instancesDeferred.delete(identifier);\r\n this.instancesOptions.delete(identifier);\r\n this.instances.delete(identifier);\r\n }\r\n // app.delete() will call this method on every provider to delete the services\r\n // TODO: should we mark the provider as deleted?\r\n async delete() {\r\n const services = Array.from(this.instances.values());\r\n await Promise.all([\r\n ...services\r\n .filter(service => 'INTERNAL' in service) // legacy services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service.INTERNAL.delete()),\r\n ...services\r\n .filter(service => '_delete' in service) // modularized services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service._delete())\r\n ]);\r\n }\r\n isComponentSet() {\r\n return this.component != null;\r\n }\r\n isInitialized(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instances.has(identifier);\r\n }\r\n getOptions(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instancesOptions.get(identifier) || {};\r\n }\r\n initialize(opts = {}) {\r\n const { options = {} } = opts;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);\r\n if (this.isInitialized(normalizedIdentifier)) {\r\n throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);\r\n }\r\n if (!this.isComponentSet()) {\r\n throw Error(`Component ${this.name} has not been registered yet`);\r\n }\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier,\r\n options\r\n });\r\n // resolve any pending promise waiting for the service instance\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\r\n instanceDeferred.resolve(instance);\r\n }\r\n }\r\n return instance;\r\n }\r\n /**\r\n *\r\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\r\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\r\n *\r\n * @param identifier An optional instance identifier\r\n * @returns a function to unregister the callback\r\n */\r\n onInit(callback, identifier) {\r\n var _a;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();\r\n existingCallbacks.add(callback);\r\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\r\n const existingInstance = this.instances.get(normalizedIdentifier);\r\n if (existingInstance) {\r\n callback(existingInstance, normalizedIdentifier);\r\n }\r\n return () => {\r\n existingCallbacks.delete(callback);\r\n };\r\n }\r\n /**\r\n * Invoke onInit callbacks synchronously\r\n * @param instance the service instance`\r\n */\r\n invokeOnInitCallbacks(instance, identifier) {\r\n const callbacks = this.onInitCallbacks.get(identifier);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n try {\r\n callback(instance, identifier);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInit callback\r\n }\r\n }\r\n }\r\n getOrInitializeService({ instanceIdentifier, options = {} }) {\r\n let instance = this.instances.get(instanceIdentifier);\r\n if (!instance && this.component) {\r\n instance = this.component.instanceFactory(this.container, {\r\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\r\n options\r\n });\r\n this.instances.set(instanceIdentifier, instance);\r\n this.instancesOptions.set(instanceIdentifier, options);\r\n /**\r\n * Invoke onInit listeners.\r\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\r\n * while onInit listeners are registered by consumers of the provider.\r\n */\r\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\r\n /**\r\n * Order is important\r\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\r\n * makes `isInitialized()` return true.\r\n */\r\n if (this.component.onInstanceCreated) {\r\n try {\r\n this.component.onInstanceCreated(this.container, instanceIdentifier, instance);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInstanceCreatedCallback\r\n }\r\n }\r\n }\r\n return instance || null;\r\n }\r\n normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {\r\n if (this.component) {\r\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\r\n }\r\n else {\r\n return identifier; // assume multiple instances are supported before the component is provided.\r\n }\r\n }\r\n shouldAutoInitialize() {\r\n return (!!this.component &&\r\n this.component.instantiationMode !== \"EXPLICIT\" /* InstantiationMode.EXPLICIT */);\r\n }\r\n}\r\n// undefined should be passed to the service factory for the default instance\r\nfunction normalizeIdentifierForFactory(identifier) {\r\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\r\n}\r\nfunction isComponentEager(component) {\r\n return component.instantiationMode === \"EAGER\" /* InstantiationMode.EAGER */;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass ComponentContainer {\r\n constructor(name) {\r\n this.name = name;\r\n this.providers = new Map();\r\n }\r\n /**\r\n *\r\n * @param component Component being added\r\n * @param overwrite When a component with the same name has already been registered,\r\n * if overwrite is true: overwrite the existing component with the new component and create a new\r\n * provider with the new component. It can be useful in tests where you want to use different mocks\r\n * for different tests.\r\n * if overwrite is false: throw an exception\r\n */\r\n addComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n throw new Error(`Component ${component.name} has already been registered with ${this.name}`);\r\n }\r\n provider.setComponent(component);\r\n }\r\n addOrOverwriteComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n // delete the existing provider from the container, so we can register the new component\r\n this.providers.delete(component.name);\r\n }\r\n this.addComponent(component);\r\n }\r\n /**\r\n * getProvider provides a type safe interface where it can only be called with a field name\r\n * present in NameServiceMapping interface.\r\n *\r\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\r\n * themselves.\r\n */\r\n getProvider(name) {\r\n if (this.providers.has(name)) {\r\n return this.providers.get(name);\r\n }\r\n // create a Provider for a service that hasn't registered with Firebase\r\n const provider = new Provider(name, this);\r\n this.providers.set(name, provider);\r\n return provider;\r\n }\r\n getProviders() {\r\n return Array.from(this.providers.values());\r\n }\r\n}\n\nexport { Component, ComponentContainer, Provider };\n//# sourceMappingURL=index.esm2017.js.map\n","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A container for all of the Logger instances\r\n */\r\nconst instances = [];\r\n/**\r\n * The JS SDK supports 5 log levels and also allows a user the ability to\r\n * silence the logs altogether.\r\n *\r\n * The order is a follows:\r\n * DEBUG < VERBOSE < INFO < WARN < ERROR\r\n *\r\n * All of the log types above the current log level will be captured (i.e. if\r\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\r\n * `VERBOSE` logs will not)\r\n */\r\nvar LogLevel;\r\n(function (LogLevel) {\r\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\r\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\r\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\r\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\r\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\r\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\r\n})(LogLevel || (LogLevel = {}));\r\nconst levelStringToEnum = {\r\n 'debug': LogLevel.DEBUG,\r\n 'verbose': LogLevel.VERBOSE,\r\n 'info': LogLevel.INFO,\r\n 'warn': LogLevel.WARN,\r\n 'error': LogLevel.ERROR,\r\n 'silent': LogLevel.SILENT\r\n};\r\n/**\r\n * The default log level\r\n */\r\nconst defaultLogLevel = LogLevel.INFO;\r\n/**\r\n * By default, `console.debug` is not displayed in the developer console (in\r\n * chrome). To avoid forcing users to have to opt-in to these logs twice\r\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\r\n * logs to the `console.log` function.\r\n */\r\nconst ConsoleMethod = {\r\n [LogLevel.DEBUG]: 'log',\r\n [LogLevel.VERBOSE]: 'log',\r\n [LogLevel.INFO]: 'info',\r\n [LogLevel.WARN]: 'warn',\r\n [LogLevel.ERROR]: 'error'\r\n};\r\n/**\r\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\r\n * messages on to their corresponding console counterparts (if the log method\r\n * is supported by the current log level)\r\n */\r\nconst defaultLogHandler = (instance, logType, ...args) => {\r\n if (logType < instance.logLevel) {\r\n return;\r\n }\r\n const now = new Date().toISOString();\r\n const method = ConsoleMethod[logType];\r\n if (method) {\r\n console[method](`[${now}] ${instance.name}:`, ...args);\r\n }\r\n else {\r\n throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);\r\n }\r\n};\r\nclass Logger {\r\n /**\r\n * Gives you an instance of a Logger to capture messages according to\r\n * Firebase's logging scheme.\r\n *\r\n * @param name The name that the logs will be associated with\r\n */\r\n constructor(name) {\r\n this.name = name;\r\n /**\r\n * The log level of the given Logger instance.\r\n */\r\n this._logLevel = defaultLogLevel;\r\n /**\r\n * The main (internal) log handler for the Logger instance.\r\n * Can be set to a new function in internal package code but not by user.\r\n */\r\n this._logHandler = defaultLogHandler;\r\n /**\r\n * The optional, additional, user-defined log handler for the Logger instance.\r\n */\r\n this._userLogHandler = null;\r\n /**\r\n * Capture the current instance for later use\r\n */\r\n instances.push(this);\r\n }\r\n get logLevel() {\r\n return this._logLevel;\r\n }\r\n set logLevel(val) {\r\n if (!(val in LogLevel)) {\r\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\r\n }\r\n this._logLevel = val;\r\n }\r\n // Workaround for setter/getter having to be the same type.\r\n setLogLevel(val) {\r\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\r\n }\r\n get logHandler() {\r\n return this._logHandler;\r\n }\r\n set logHandler(val) {\r\n if (typeof val !== 'function') {\r\n throw new TypeError('Value assigned to `logHandler` must be a function');\r\n }\r\n this._logHandler = val;\r\n }\r\n get userLogHandler() {\r\n return this._userLogHandler;\r\n }\r\n set userLogHandler(val) {\r\n this._userLogHandler = val;\r\n }\r\n /**\r\n * The functions below are all based on the `console` interface\r\n */\r\n debug(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\r\n this._logHandler(this, LogLevel.DEBUG, ...args);\r\n }\r\n log(...args) {\r\n this._userLogHandler &&\r\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\r\n this._logHandler(this, LogLevel.VERBOSE, ...args);\r\n }\r\n info(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\r\n this._logHandler(this, LogLevel.INFO, ...args);\r\n }\r\n warn(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\r\n this._logHandler(this, LogLevel.WARN, ...args);\r\n }\r\n error(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\r\n this._logHandler(this, LogLevel.ERROR, ...args);\r\n }\r\n}\r\nfunction setLogLevel(level) {\r\n instances.forEach(inst => {\r\n inst.setLogLevel(level);\r\n });\r\n}\r\nfunction setUserLogHandler(logCallback, options) {\r\n for (const instance of instances) {\r\n let customLogLevel = null;\r\n if (options && options.level) {\r\n customLogLevel = levelStringToEnum[options.level];\r\n }\r\n if (logCallback === null) {\r\n instance.userLogHandler = null;\r\n }\r\n else {\r\n instance.userLogHandler = (instance, level, ...args) => {\r\n const message = args\r\n .map(arg => {\r\n if (arg == null) {\r\n return null;\r\n }\r\n else if (typeof arg === 'string') {\r\n return arg;\r\n }\r\n else if (typeof arg === 'number' || typeof arg === 'boolean') {\r\n return arg.toString();\r\n }\r\n else if (arg instanceof Error) {\r\n return arg.message;\r\n }\r\n else {\r\n try {\r\n return JSON.stringify(arg);\r\n }\r\n catch (ignored) {\r\n return null;\r\n }\r\n }\r\n })\r\n .filter(arg => arg)\r\n .join(' ');\r\n if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) {\r\n logCallback({\r\n level: LogLevel[level].toLowerCase(),\r\n message,\r\n args,\r\n type: instance.name\r\n });\r\n }\r\n };\r\n }\r\n }\r\n}\n\nexport { LogLevel, Logger, setLogLevel, setUserLogHandler };\n//# sourceMappingURL=index.esm2017.js.map\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","import { Component, ComponentContainer } from '@firebase/component';\nimport { Logger, setUserLogHandler, setLogLevel as setLogLevel$1 } from '@firebase/logger';\nimport { ErrorFactory, getDefaultAppConfig, deepEqual, isBrowser, FirebaseError, base64urlEncodeWithoutPadding, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';\nexport { FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PlatformLoggerServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n }\r\n // In initial implementation, this will be called by installations on\r\n // auth token refresh, and installations will send this string.\r\n getPlatformInfoString() {\r\n const providers = this.container.getProviders();\r\n // Loop through providers and get library/version pairs from any that are\r\n // version components.\r\n return providers\r\n .map(provider => {\r\n if (isVersionServiceProvider(provider)) {\r\n const service = provider.getImmediate();\r\n return `${service.library}/${service.version}`;\r\n }\r\n else {\r\n return null;\r\n }\r\n })\r\n .filter(logString => logString)\r\n .join(' ');\r\n }\r\n}\r\n/**\r\n *\r\n * @param provider check if this provider provides a VersionService\r\n *\r\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\r\n * provides VersionService. The provider is not necessarily a 'app-version'\r\n * provider.\r\n */\r\nfunction isVersionServiceProvider(provider) {\r\n const component = provider.getComponent();\r\n return (component === null || component === void 0 ? void 0 : component.type) === \"VERSION\" /* ComponentType.VERSION */;\r\n}\n\nconst name$p = \"@firebase/app\";\nconst version$1 = \"0.10.4\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logger = new Logger('@firebase/app');\n\nconst name$o = \"@firebase/app-compat\";\n\nconst name$n = \"@firebase/analytics-compat\";\n\nconst name$m = \"@firebase/analytics\";\n\nconst name$l = \"@firebase/app-check-compat\";\n\nconst name$k = \"@firebase/app-check\";\n\nconst name$j = \"@firebase/auth\";\n\nconst name$i = \"@firebase/auth-compat\";\n\nconst name$h = \"@firebase/database\";\n\nconst name$g = \"@firebase/database-compat\";\n\nconst name$f = \"@firebase/functions\";\n\nconst name$e = \"@firebase/functions-compat\";\n\nconst name$d = \"@firebase/installations\";\n\nconst name$c = \"@firebase/installations-compat\";\n\nconst name$b = \"@firebase/messaging\";\n\nconst name$a = \"@firebase/messaging-compat\";\n\nconst name$9 = \"@firebase/performance\";\n\nconst name$8 = \"@firebase/performance-compat\";\n\nconst name$7 = \"@firebase/remote-config\";\n\nconst name$6 = \"@firebase/remote-config-compat\";\n\nconst name$5 = \"@firebase/storage\";\n\nconst name$4 = \"@firebase/storage-compat\";\n\nconst name$3 = \"@firebase/firestore\";\n\nconst name$2 = \"@firebase/vertexai-preview\";\n\nconst name$1 = \"@firebase/firestore-compat\";\n\nconst name = \"firebase\";\nconst version = \"10.12.1\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The default app name\r\n *\r\n * @internal\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\r\nconst PLATFORM_LOG_STRING = {\r\n [name$p]: 'fire-core',\r\n [name$o]: 'fire-core-compat',\r\n [name$m]: 'fire-analytics',\r\n [name$n]: 'fire-analytics-compat',\r\n [name$k]: 'fire-app-check',\r\n [name$l]: 'fire-app-check-compat',\r\n [name$j]: 'fire-auth',\r\n [name$i]: 'fire-auth-compat',\r\n [name$h]: 'fire-rtdb',\r\n [name$g]: 'fire-rtdb-compat',\r\n [name$f]: 'fire-fn',\r\n [name$e]: 'fire-fn-compat',\r\n [name$d]: 'fire-iid',\r\n [name$c]: 'fire-iid-compat',\r\n [name$b]: 'fire-fcm',\r\n [name$a]: 'fire-fcm-compat',\r\n [name$9]: 'fire-perf',\r\n [name$8]: 'fire-perf-compat',\r\n [name$7]: 'fire-rc',\r\n [name$6]: 'fire-rc-compat',\r\n [name$5]: 'fire-gcs',\r\n [name$4]: 'fire-gcs-compat',\r\n [name$3]: 'fire-fst',\r\n [name$1]: 'fire-fst-compat',\r\n [name$2]: 'fire-vertex',\r\n 'fire-js': 'fire-js',\r\n [name]: 'fire-js-all'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @internal\r\n */\r\nconst _apps = new Map();\r\n/**\r\n * @internal\r\n */\r\nconst _serverApps = new Map();\r\n/**\r\n * Registered components.\r\n *\r\n * @internal\r\n */\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nconst _components = new Map();\r\n/**\r\n * @param component - the component being added to this app's container\r\n *\r\n * @internal\r\n */\r\nfunction _addComponent(app, component) {\r\n try {\r\n app.container.addComponent(component);\r\n }\r\n catch (e) {\r\n logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);\r\n }\r\n}\r\n/**\r\n *\r\n * @internal\r\n */\r\nfunction _addOrOverwriteComponent(app, component) {\r\n app.container.addOrOverwriteComponent(component);\r\n}\r\n/**\r\n *\r\n * @param component - the component to register\r\n * @returns whether or not the component is registered successfully\r\n *\r\n * @internal\r\n */\r\nfunction _registerComponent(component) {\r\n const componentName = component.name;\r\n if (_components.has(componentName)) {\r\n logger.debug(`There were multiple attempts to register component ${componentName}.`);\r\n return false;\r\n }\r\n _components.set(componentName, component);\r\n // add the component to existing app instances\r\n for (const app of _apps.values()) {\r\n _addComponent(app, component);\r\n }\r\n for (const serverApp of _serverApps.values()) {\r\n _addComponent(serverApp, component);\r\n }\r\n return true;\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n *\r\n * @returns the provider for the service with the matching name\r\n *\r\n * @internal\r\n */\r\nfunction _getProvider(app, name) {\r\n const heartbeatController = app.container\r\n .getProvider('heartbeat')\r\n .getImmediate({ optional: true });\r\n if (heartbeatController) {\r\n void heartbeatController.triggerHeartbeat();\r\n }\r\n return app.container.getProvider(name);\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\r\n *\r\n * @internal\r\n */\r\nfunction _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {\r\n _getProvider(app, name).clearInstance(instanceIdentifier);\r\n}\r\n/**\r\n *\r\n * @param obj - an object of type FirebaseApp or FirebaseOptions.\r\n *\r\n * @returns true if the provide object is of type FirebaseApp.\r\n *\r\n * @internal\r\n */\r\nfunction _isFirebaseApp(obj) {\r\n return obj.options !== undefined;\r\n}\r\n/**\r\n *\r\n * @param obj - an object of type FirebaseApp.\r\n *\r\n * @returns true if the provided object is of type FirebaseServerAppImpl.\r\n *\r\n * @internal\r\n */\r\nfunction _isFirebaseServerApp(obj) {\r\n return obj.settings !== undefined;\r\n}\r\n/**\r\n * Test only\r\n *\r\n * @internal\r\n */\r\nfunction _clearComponents() {\r\n _components.clear();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERRORS = {\r\n [\"no-app\" /* AppError.NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\r\n 'call initializeApp() first',\r\n [\"bad-app-name\" /* AppError.BAD_APP_NAME */]: \"Illegal App name: '{$appName}'\",\r\n [\"duplicate-app\" /* AppError.DUPLICATE_APP */]: \"Firebase App named '{$appName}' already exists with different options or config\",\r\n [\"app-deleted\" /* AppError.APP_DELETED */]: \"Firebase App named '{$appName}' already deleted\",\r\n [\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted',\r\n [\"no-options\" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',\r\n [\"invalid-app-argument\" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\r\n 'Firebase App instance.',\r\n [\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',\r\n [\"idb-open\" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-get\" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-set\" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-delete\" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',\r\n [\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FirebaseAppImpl {\r\n constructor(options, config, container) {\r\n this._isDeleted = false;\r\n this._options = Object.assign({}, options);\r\n this._config = Object.assign({}, config);\r\n this._name = config.name;\r\n this._automaticDataCollectionEnabled =\r\n config.automaticDataCollectionEnabled;\r\n this._container = container;\r\n this.container.addComponent(new Component('app', () => this, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n }\r\n get automaticDataCollectionEnabled() {\r\n this.checkDestroyed();\r\n return this._automaticDataCollectionEnabled;\r\n }\r\n set automaticDataCollectionEnabled(val) {\r\n this.checkDestroyed();\r\n this._automaticDataCollectionEnabled = val;\r\n }\r\n get name() {\r\n this.checkDestroyed();\r\n return this._name;\r\n }\r\n get options() {\r\n this.checkDestroyed();\r\n return this._options;\r\n }\r\n get config() {\r\n this.checkDestroyed();\r\n return this._config;\r\n }\r\n get container() {\r\n return this._container;\r\n }\r\n get isDeleted() {\r\n return this._isDeleted;\r\n }\r\n set isDeleted(val) {\r\n this._isDeleted = val;\r\n }\r\n /**\r\n * This function will throw an Error if the App has already been deleted -\r\n * use before performing API actions on the App.\r\n */\r\n checkDestroyed() {\r\n if (this.isDeleted) {\r\n throw ERROR_FACTORY.create(\"app-deleted\" /* AppError.APP_DELETED */, { appName: this._name });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2023 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FirebaseServerAppImpl extends FirebaseAppImpl {\r\n constructor(options, serverConfig, name, container) {\r\n // Build configuration parameters for the FirebaseAppImpl base class.\r\n const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined\r\n ? serverConfig.automaticDataCollectionEnabled\r\n : false;\r\n // Create the FirebaseAppSettings object for the FirebaseAppImp constructor.\r\n const config = {\r\n name,\r\n automaticDataCollectionEnabled\r\n };\r\n if (options.apiKey !== undefined) {\r\n // Construct the parent FirebaseAppImp object.\r\n super(options, config, container);\r\n }\r\n else {\r\n const appImpl = options;\r\n super(appImpl.options, config, container);\r\n }\r\n // Now construct the data for the FirebaseServerAppImpl.\r\n this._serverConfig = Object.assign({ automaticDataCollectionEnabled }, serverConfig);\r\n this._finalizationRegistry = new FinalizationRegistry(() => {\r\n this.automaticCleanup();\r\n });\r\n this._refCount = 0;\r\n this.incRefCount(this._serverConfig.releaseOnDeref);\r\n // Do not retain a hard reference to the dref object, otherwise the FinalizationRegisry\r\n // will never trigger.\r\n this._serverConfig.releaseOnDeref = undefined;\r\n serverConfig.releaseOnDeref = undefined;\r\n registerVersion(name$p, version$1, 'serverapp');\r\n }\r\n toJSON() {\r\n return undefined;\r\n }\r\n get refCount() {\r\n return this._refCount;\r\n }\r\n // Increment the reference count of this server app. If an object is provided, register it\r\n // with the finalization registry.\r\n incRefCount(obj) {\r\n if (this.isDeleted) {\r\n return;\r\n }\r\n this._refCount++;\r\n if (obj !== undefined) {\r\n this._finalizationRegistry.register(obj, this);\r\n }\r\n }\r\n // Decrement the reference count.\r\n decRefCount() {\r\n if (this.isDeleted) {\r\n return 0;\r\n }\r\n return --this._refCount;\r\n }\r\n // Invoked by the FinalizationRegistry callback to note that this app should go through its\r\n // reference counts and delete itself if no reference count remain. The coordinating logic that\r\n // handles this is in deleteApp(...).\r\n automaticCleanup() {\r\n void deleteApp(this);\r\n }\r\n get settings() {\r\n this.checkDestroyed();\r\n return this._serverConfig;\r\n }\r\n /**\r\n * This function will throw an Error if the App has already been deleted -\r\n * use before performing API actions on the App.\r\n */\r\n checkDestroyed() {\r\n if (this.isDeleted) {\r\n throw ERROR_FACTORY.create(\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The current SDK version.\r\n *\r\n * @public\r\n */\r\nconst SDK_VERSION = version;\r\nfunction initializeApp(_options, rawConfig = {}) {\r\n let options = _options;\r\n if (typeof rawConfig !== 'object') {\r\n const name = rawConfig;\r\n rawConfig = { name };\r\n }\r\n const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);\r\n const name = config.name;\r\n if (typeof name !== 'string' || !name) {\r\n throw ERROR_FACTORY.create(\"bad-app-name\" /* AppError.BAD_APP_NAME */, {\r\n appName: String(name)\r\n });\r\n }\r\n options || (options = getDefaultAppConfig());\r\n if (!options) {\r\n throw ERROR_FACTORY.create(\"no-options\" /* AppError.NO_OPTIONS */);\r\n }\r\n const existingApp = _apps.get(name);\r\n if (existingApp) {\r\n // return the existing app if options and config deep equal the ones in the existing app.\r\n if (deepEqual(options, existingApp.options) &&\r\n deepEqual(config, existingApp.config)) {\r\n return existingApp;\r\n }\r\n else {\r\n throw ERROR_FACTORY.create(\"duplicate-app\" /* AppError.DUPLICATE_APP */, { appName: name });\r\n }\r\n }\r\n const container = new ComponentContainer(name);\r\n for (const component of _components.values()) {\r\n container.addComponent(component);\r\n }\r\n const newApp = new FirebaseAppImpl(options, config, container);\r\n _apps.set(name, newApp);\r\n return newApp;\r\n}\r\nfunction initializeServerApp(_options, _serverAppConfig) {\r\n if (isBrowser()) {\r\n // FirebaseServerApp isn't designed to be run in browsers.\r\n throw ERROR_FACTORY.create(\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */);\r\n }\r\n if (_serverAppConfig.automaticDataCollectionEnabled === undefined) {\r\n _serverAppConfig.automaticDataCollectionEnabled = false;\r\n }\r\n let appOptions;\r\n if (_isFirebaseApp(_options)) {\r\n appOptions = _options.options;\r\n }\r\n else {\r\n appOptions = _options;\r\n }\r\n // Build an app name based on a hash of the configuration options.\r\n const nameObj = Object.assign(Object.assign({}, _serverAppConfig), appOptions);\r\n // However, Do not mangle the name based on releaseOnDeref, since it will vary between the\r\n // construction of FirebaseServerApp instances. For example, if the object is the request headers.\r\n if (nameObj.releaseOnDeref !== undefined) {\r\n delete nameObj.releaseOnDeref;\r\n }\r\n const hashCode = (s) => {\r\n return [...s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0);\r\n };\r\n if (_serverAppConfig.releaseOnDeref !== undefined) {\r\n if (typeof FinalizationRegistry === 'undefined') {\r\n throw ERROR_FACTORY.create(\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {});\r\n }\r\n }\r\n const nameString = '' + hashCode(JSON.stringify(nameObj));\r\n const existingApp = _serverApps.get(nameString);\r\n if (existingApp) {\r\n existingApp.incRefCount(_serverAppConfig.releaseOnDeref);\r\n return existingApp;\r\n }\r\n const container = new ComponentContainer(nameString);\r\n for (const component of _components.values()) {\r\n container.addComponent(component);\r\n }\r\n const newApp = new FirebaseServerAppImpl(appOptions, _serverAppConfig, nameString, container);\r\n _serverApps.set(nameString, newApp);\r\n return newApp;\r\n}\r\n/**\r\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * When called with no arguments, the default app is returned. When an app name\r\n * is provided, the app corresponding to that name is returned.\r\n *\r\n * An exception is thrown if the app being retrieved has not yet been\r\n * initialized.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return the default app\r\n * const app = getApp();\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return a named app\r\n * const otherApp = getApp(\"otherApp\");\r\n * ```\r\n *\r\n * @param name - Optional name of the app to return. If no name is\r\n * provided, the default is `\"[DEFAULT]\"`.\r\n *\r\n * @returns The app corresponding to the provided app name.\r\n * If no app name is provided, the default app is returned.\r\n *\r\n * @public\r\n */\r\nfunction getApp(name = DEFAULT_ENTRY_NAME) {\r\n const app = _apps.get(name);\r\n if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\r\n return initializeApp();\r\n }\r\n if (!app) {\r\n throw ERROR_FACTORY.create(\"no-app\" /* AppError.NO_APP */, { appName: name });\r\n }\r\n return app;\r\n}\r\n/**\r\n * A (read-only) array of all initialized apps.\r\n * @public\r\n */\r\nfunction getApps() {\r\n return Array.from(_apps.values());\r\n}\r\n/**\r\n * Renders this app unusable and frees the resources of all associated\r\n * services.\r\n *\r\n * @example\r\n * ```javascript\r\n * deleteApp(app)\r\n * .then(function() {\r\n * console.log(\"App deleted successfully\");\r\n * })\r\n * .catch(function(error) {\r\n * console.log(\"Error deleting app:\", error);\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nasync function deleteApp(app) {\r\n let cleanupProviders = false;\r\n const name = app.name;\r\n if (_apps.has(name)) {\r\n cleanupProviders = true;\r\n _apps.delete(name);\r\n }\r\n else if (_serverApps.has(name)) {\r\n const firebaseServerApp = app;\r\n if (firebaseServerApp.decRefCount() <= 0) {\r\n _serverApps.delete(name);\r\n cleanupProviders = true;\r\n }\r\n }\r\n if (cleanupProviders) {\r\n await Promise.all(app.container\r\n .getProviders()\r\n .map(provider => provider.delete()));\r\n app.isDeleted = true;\r\n }\r\n}\r\n/**\r\n * Registers a library's name and version for platform logging purposes.\r\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\r\n * @param version - Current version of that library.\r\n * @param variant - Bundle variant, e.g., node, rn, etc.\r\n *\r\n * @public\r\n */\r\nfunction registerVersion(libraryKeyOrName, version, variant) {\r\n var _a;\r\n // TODO: We can use this check to whitelist strings when/if we set up\r\n // a good whitelist system.\r\n let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;\r\n if (variant) {\r\n library += `-${variant}`;\r\n }\r\n const libraryMismatch = library.match(/\\s|\\//);\r\n const versionMismatch = version.match(/\\s|\\//);\r\n if (libraryMismatch || versionMismatch) {\r\n const warning = [\r\n `Unable to register library \"${library}\" with version \"${version}\":`\r\n ];\r\n if (libraryMismatch) {\r\n warning.push(`library name \"${library}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n if (libraryMismatch && versionMismatch) {\r\n warning.push('and');\r\n }\r\n if (versionMismatch) {\r\n warning.push(`version name \"${version}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n logger.warn(warning.join(' '));\r\n return;\r\n }\r\n _registerComponent(new Component(`${library}-version`, () => ({ library, version }), \"VERSION\" /* ComponentType.VERSION */));\r\n}\r\n/**\r\n * Sets log handler for all Firebase SDKs.\r\n * @param logCallback - An optional custom log handler that executes user code whenever\r\n * the Firebase SDK makes a logging call.\r\n *\r\n * @public\r\n */\r\nfunction onLog(logCallback, options) {\r\n if (logCallback !== null && typeof logCallback !== 'function') {\r\n throw ERROR_FACTORY.create(\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */);\r\n }\r\n setUserLogHandler(logCallback, options);\r\n}\r\n/**\r\n * Sets log level for all Firebase SDKs.\r\n *\r\n * All of the log types above the current log level are captured (i.e. if\r\n * you set the log level to `info`, errors are logged, but `debug` and\r\n * `verbose` logs are not).\r\n *\r\n * @public\r\n */\r\nfunction setLogLevel(logLevel) {\r\n setLogLevel$1(logLevel);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebase-heartbeat-database';\r\nconst DB_VERSION = 1;\r\nconst STORE_NAME = 'firebase-heartbeat-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DB_NAME, DB_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n try {\r\n db.createObjectStore(STORE_NAME);\r\n }\r\n catch (e) {\r\n // Safari/iOS browsers throw occasional exceptions on\r\n // db.createObjectStore() that may be a bug. Avoid blocking\r\n // the rest of the app functionality.\r\n console.warn(e);\r\n }\r\n }\r\n }\r\n }).catch(e => {\r\n throw ERROR_FACTORY.create(\"idb-open\" /* AppError.IDB_OPEN */, {\r\n originalErrorMessage: e.message\r\n });\r\n });\r\n }\r\n return dbPromise;\r\n}\r\nasync function readHeartbeatsFromIndexedDB(app) {\r\n try {\r\n const db = await getDbPromise();\r\n const tx = db.transaction(STORE_NAME);\r\n const result = await tx.objectStore(STORE_NAME).get(computeKey(app));\r\n // We already have the value but tx.done can throw,\r\n // so we need to await it here to catch errors\r\n await tx.done;\r\n return result;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-get\" /* AppError.IDB_GET */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nasync function writeHeartbeatsToIndexedDB(app, heartbeatObject) {\r\n try {\r\n const db = await getDbPromise();\r\n const tx = db.transaction(STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(STORE_NAME);\r\n await objectStore.put(heartbeatObject, computeKey(app));\r\n await tx.done;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-set\" /* AppError.IDB_WRITE */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nfunction computeKey(app) {\r\n return `${app.name}!${app.options.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst MAX_HEADER_BYTES = 1024;\r\n// 30 days\r\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\r\nclass HeartbeatServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n /**\r\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\r\n * the header string.\r\n * Stores one record per date. This will be consolidated into the standard\r\n * format of one record per user agent string before being sent as a header.\r\n * Populated from indexedDB when the controller is instantiated and should\r\n * be kept in sync with indexedDB.\r\n * Leave public for easier testing.\r\n */\r\n this._heartbeatsCache = null;\r\n const app = this.container.getProvider('app').getImmediate();\r\n this._storage = new HeartbeatStorageImpl(app);\r\n this._heartbeatsCachePromise = this._storage.read().then(result => {\r\n this._heartbeatsCache = result;\r\n return result;\r\n });\r\n }\r\n /**\r\n * Called to report a heartbeat. The function will generate\r\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\r\n * to IndexedDB.\r\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\r\n * already logged, subsequent calls to this function in the same day will be ignored.\r\n */\r\n async triggerHeartbeat() {\r\n var _a, _b;\r\n const platformLogger = this.container\r\n .getProvider('platform-logger')\r\n .getImmediate();\r\n // This is the \"Firebase user agent\" string from the platform logger\r\n // service, not the browser user agent.\r\n const agent = platformLogger.getPlatformInfoString();\r\n const date = getUTCDateString();\r\n if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null) {\r\n this._heartbeatsCache = await this._heartbeatsCachePromise;\r\n // If we failed to construct a heartbeats cache, then return immediately.\r\n if (((_b = this._heartbeatsCache) === null || _b === void 0 ? void 0 : _b.heartbeats) == null) {\r\n return;\r\n }\r\n }\r\n // Do not store a heartbeat if one is already stored for this day\r\n // or if a header has already been sent today.\r\n if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\r\n this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\r\n return;\r\n }\r\n else {\r\n // There is no entry for this date. Create one.\r\n this._heartbeatsCache.heartbeats.push({ date, agent });\r\n }\r\n // Remove entries older than 30 days.\r\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {\r\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\r\n const now = Date.now();\r\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\r\n });\r\n return this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n /**\r\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\r\n * It also clears all heartbeats from memory as well as in IndexedDB.\r\n *\r\n * NOTE: Consuming product SDKs should not send the header if this method\r\n * returns an empty string.\r\n */\r\n async getHeartbeatsHeader() {\r\n var _a;\r\n if (this._heartbeatsCache === null) {\r\n await this._heartbeatsCachePromise;\r\n }\r\n // If it's still null or the array is empty, there is no data to send.\r\n if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null ||\r\n this._heartbeatsCache.heartbeats.length === 0) {\r\n return '';\r\n }\r\n const date = getUTCDateString();\r\n // Extract as many heartbeats from the cache as will fit under the size limit.\r\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);\r\n const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));\r\n // Store last sent date to prevent another being logged/sent for the same day.\r\n this._heartbeatsCache.lastSentHeartbeatDate = date;\r\n if (unsentEntries.length > 0) {\r\n // Store any unsent entries if they exist.\r\n this._heartbeatsCache.heartbeats = unsentEntries;\r\n // This seems more likely than emptying the array (below) to lead to some odd state\r\n // since the cache isn't empty and this will be called again on the next request,\r\n // and is probably safest if we await it.\r\n await this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n else {\r\n this._heartbeatsCache.heartbeats = [];\r\n // Do not wait for this, to reduce latency.\r\n void this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n return headerString;\r\n }\r\n}\r\nfunction getUTCDateString() {\r\n const today = new Date();\r\n // Returns date format 'YYYY-MM-DD'\r\n return today.toISOString().substring(0, 10);\r\n}\r\nfunction extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {\r\n // Heartbeats grouped by user agent in the standard format to be sent in\r\n // the header.\r\n const heartbeatsToSend = [];\r\n // Single date format heartbeats that are not sent.\r\n let unsentEntries = heartbeatsCache.slice();\r\n for (const singleDateHeartbeat of heartbeatsCache) {\r\n // Look for an existing entry with the same user agent.\r\n const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);\r\n if (!heartbeatEntry) {\r\n // If no entry for this user agent exists, create one.\r\n heartbeatsToSend.push({\r\n agent: singleDateHeartbeat.agent,\r\n dates: [singleDateHeartbeat.date]\r\n });\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n // If the header would exceed max size, remove the added heartbeat\r\n // entry and stop adding to the header.\r\n heartbeatsToSend.pop();\r\n break;\r\n }\r\n }\r\n else {\r\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\r\n // If the header would exceed max size, remove the added date\r\n // and stop adding to the header.\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n heartbeatEntry.dates.pop();\r\n break;\r\n }\r\n }\r\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\r\n // quota and the loop breaks early.)\r\n unsentEntries = unsentEntries.slice(1);\r\n }\r\n return {\r\n heartbeatsToSend,\r\n unsentEntries\r\n };\r\n}\r\nclass HeartbeatStorageImpl {\r\n constructor(app) {\r\n this.app = app;\r\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\r\n }\r\n async runIndexedDBEnvironmentCheck() {\r\n if (!isIndexedDBAvailable()) {\r\n return false;\r\n }\r\n else {\r\n return validateIndexedDBOpenable()\r\n .then(() => true)\r\n .catch(() => false);\r\n }\r\n }\r\n /**\r\n * Read all heartbeats.\r\n */\r\n async read() {\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return { heartbeats: [] };\r\n }\r\n else {\r\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\r\n if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) {\r\n return idbHeartbeatObject;\r\n }\r\n else {\r\n return { heartbeats: [] };\r\n }\r\n }\r\n }\r\n // overwrite the storage with the provided heartbeats\r\n async overwrite(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: heartbeatsObject.heartbeats\r\n });\r\n }\r\n }\r\n // add heartbeats\r\n async add(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: [\r\n ...existingHeartbeatsObject.heartbeats,\r\n ...heartbeatsObject.heartbeats\r\n ]\r\n });\r\n }\r\n }\r\n}\r\n/**\r\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\r\n * in a platform logging header JSON object, stringified, and converted\r\n * to base 64.\r\n */\r\nfunction countBytes(heartbeatsCache) {\r\n // base64 has a restricted set of characters, all of which should be 1 byte.\r\n return base64urlEncodeWithoutPadding(\r\n // heartbeatsCache wrapper properties\r\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerCoreComponents(variant) {\r\n _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n // Register `app` package.\r\n registerVersion(name$p, version$1, variant);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name$p, version$1, 'esm2017');\r\n // Register platform SDK identifier (no version).\r\n registerVersion('fire-js', '');\r\n}\n\n/**\r\n * Firebase App\r\n *\r\n * @remarks This package coordinates the communication between the different Firebase components\r\n * @packageDocumentation\r\n */\r\nregisterCoreComponents('');\n\nexport { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _isFirebaseApp, _isFirebaseServerApp, _registerComponent, _removeServiceInstance, _serverApps, deleteApp, getApp, getApps, initializeApp, initializeServerApp, onLog, registerVersion, setLogLevel };\n//# sourceMappingURL=index.esm2017.js.map\n","import { registerVersion } from '@firebase/app';\nexport * from '@firebase/app';\n\nvar name = \"firebase\";\nvar version = \"10.12.1\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nregisterVersion(name, version, 'app');\n//# sourceMappingURL=index.esm.js.map\n","import { SDK_VERSION, _isFirebaseServerApp, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';\nimport { ErrorFactory, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, getUA, isIE, createSubscribe, deepEqual, querystringDecode, extractQuerystring, isEmpty, getExperimentalSetting, getDefaultEmulatorHost } from '@firebase/util';\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { __rest } from 'tslib';\nimport { Component } from '@firebase/component';\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An enum of factors that may be used for multifactor authentication.\r\n *\r\n * @public\r\n */\r\nconst FactorId = {\r\n /** Phone as second factor */\r\n PHONE: 'phone',\r\n TOTP: 'totp'\r\n};\r\n/**\r\n * Enumeration of supported providers.\r\n *\r\n * @public\r\n */\r\nconst ProviderId = {\r\n /** Facebook provider ID */\r\n FACEBOOK: 'facebook.com',\r\n /** GitHub provider ID */\r\n GITHUB: 'github.com',\r\n /** Google provider ID */\r\n GOOGLE: 'google.com',\r\n /** Password provider */\r\n PASSWORD: 'password',\r\n /** Phone provider */\r\n PHONE: 'phone',\r\n /** Twitter provider ID */\r\n TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported sign-in methods.\r\n *\r\n * @public\r\n */\r\nconst SignInMethod = {\r\n /** Email link sign in method */\r\n EMAIL_LINK: 'emailLink',\r\n /** Email/password sign in method */\r\n EMAIL_PASSWORD: 'password',\r\n /** Facebook sign in method */\r\n FACEBOOK: 'facebook.com',\r\n /** GitHub sign in method */\r\n GITHUB: 'github.com',\r\n /** Google sign in method */\r\n GOOGLE: 'google.com',\r\n /** Phone sign in method */\r\n PHONE: 'phone',\r\n /** Twitter sign in method */\r\n TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported operation types.\r\n *\r\n * @public\r\n */\r\nconst OperationType = {\r\n /** Operation involving linking an additional provider to an already signed-in user. */\r\n LINK: 'link',\r\n /** Operation involving using a provider to reauthenticate an already signed-in user. */\r\n REAUTHENTICATE: 'reauthenticate',\r\n /** Operation involving signing in a user. */\r\n SIGN_IN: 'signIn'\r\n};\r\n/**\r\n * An enumeration of the possible email action types.\r\n *\r\n * @public\r\n */\r\nconst ActionCodeOperation = {\r\n /** The email link sign-in action. */\r\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\r\n /** The password reset action. */\r\n PASSWORD_RESET: 'PASSWORD_RESET',\r\n /** The email revocation action. */\r\n RECOVER_EMAIL: 'RECOVER_EMAIL',\r\n /** The revert second factor addition email action. */\r\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\r\n /** The revert second factor addition email action. */\r\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\r\n /** The email verification action. */\r\n VERIFY_EMAIL: 'VERIFY_EMAIL'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _debugErrorMap() {\r\n return {\r\n [\"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */]: 'This operation is restricted to administrators only.',\r\n [\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */]: '',\r\n [\"app-not-authorized\" /* AuthErrorCode.APP_NOT_AUTHORIZED */]: \"This app, identified by the domain where it's hosted, is not \" +\r\n 'authorized to use Firebase Authentication with the provided API key. ' +\r\n 'Review your key configuration in the Google API console.',\r\n [\"app-not-installed\" /* AuthErrorCode.APP_NOT_INSTALLED */]: 'The requested mobile application corresponding to the identifier (' +\r\n 'Android package name or iOS bundle ID) provided is not installed on ' +\r\n 'this device.',\r\n [\"captcha-check-failed\" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */]: 'The reCAPTCHA response token provided is either invalid, expired, ' +\r\n 'already used or the domain associated with it does not match the list ' +\r\n 'of whitelisted domains.',\r\n [\"code-expired\" /* AuthErrorCode.CODE_EXPIRED */]: 'The SMS code has expired. Please re-send the verification code to try ' +\r\n 'again.',\r\n [\"cordova-not-ready\" /* AuthErrorCode.CORDOVA_NOT_READY */]: 'Cordova framework is not ready.',\r\n [\"cors-unsupported\" /* AuthErrorCode.CORS_UNSUPPORTED */]: 'This browser is not supported.',\r\n [\"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */]: 'This credential is already associated with a different user account.',\r\n [\"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */]: 'The custom token corresponds to a different audience.',\r\n [\"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: 'This operation is sensitive and requires recent authentication. Log in ' +\r\n 'again before retrying this request.',\r\n [\"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n 'starting any other Firebase SDK.',\r\n [\"dynamic-link-not-activated\" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */]: 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\r\n 'conditions.',\r\n [\"email-change-needs-verification\" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */]: 'Multi-factor users must always have a verified email.',\r\n [\"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */]: 'The email address is already in use by another account.',\r\n [\"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */]: 'Auth instance has already been used to make a network call. Auth can ' +\r\n 'no longer be configured to use the emulator. Try calling ' +\r\n '\"connectAuthEmulator()\" sooner.',\r\n [\"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */]: 'The action code has expired.',\r\n [\"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */]: 'This operation has been cancelled due to another conflicting popup being opened.',\r\n [\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */]: 'An internal AuthError has occurred.',\r\n [\"invalid-app-credential\" /* AuthErrorCode.INVALID_APP_CREDENTIAL */]: 'The phone verification request contains an invalid application verifier.' +\r\n ' The reCAPTCHA token response is either invalid or expired.',\r\n [\"invalid-app-id\" /* AuthErrorCode.INVALID_APP_ID */]: 'The mobile app identifier is not registed for the current project.',\r\n [\"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */]: \"This user's credential isn't valid for this project. This can happen \" +\r\n \"if the user's token has been tampered with, or if the user isn't for \" +\r\n 'the project associated with this API key.',\r\n [\"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n [\"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */]: 'The SMS verification code used to create the phone auth credential is ' +\r\n 'invalid. Please resend the verification code sms and be sure to use the ' +\r\n 'verification code provided by the user.',\r\n [\"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */]: 'The continue URL provided in the request is invalid.',\r\n [\"invalid-cordova-configuration\" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */]: 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\r\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\r\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\r\n 'cordova-plugin-customurlscheme.',\r\n [\"invalid-custom-token\" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */]: 'The custom token format is incorrect. Please check the documentation.',\r\n [\"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */]: 'The provided dynamic link domain is not configured or authorized for the current project.',\r\n [\"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */]: 'The email address is badly formatted.',\r\n [\"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */]: 'Emulator URL must start with a valid scheme (http:// or https://).',\r\n [\"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */]: 'Your API key is invalid, please check you have copied it correctly.',\r\n [\"invalid-cert-hash\" /* AuthErrorCode.INVALID_CERT_HASH */]: 'The SHA-1 certificate hash provided is invalid.',\r\n [\"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */]: 'The supplied auth credential is incorrect, malformed or has expired.',\r\n [\"invalid-message-payload\" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */]: 'The email template corresponding to this action contains invalid characters in its message. ' +\r\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n [\"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */]: 'The request does not contain a valid proof of first factor successful sign-in.',\r\n [\"invalid-oauth-provider\" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */]: 'EmailAuthProvider is not supported for this operation. This operation ' +\r\n 'only supports OAuth providers.',\r\n [\"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */]: 'The OAuth client ID provided is either invalid or does not match the ' +\r\n 'specified API key.',\r\n [\"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */]: 'This domain is not authorized for OAuth operations for your Firebase ' +\r\n 'project. Edit the list of authorized domains from the Firebase console.',\r\n [\"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */]: 'The action code is invalid. This can happen if the code is malformed, ' +\r\n 'expired, or has already been used.',\r\n [\"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */]: 'The password is invalid or the user does not have a password.',\r\n [\"invalid-persistence-type\" /* AuthErrorCode.INVALID_PERSISTENCE */]: 'The specified persistence type is invalid. It can only be local, session or none.',\r\n [\"invalid-phone-number\" /* AuthErrorCode.INVALID_PHONE_NUMBER */]: 'The format of the phone number provided is incorrect. Please enter the ' +\r\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\r\n 'phone numbers are written in the format [+][country code][subscriber ' +\r\n 'number including area code].',\r\n [\"invalid-provider-id\" /* AuthErrorCode.INVALID_PROVIDER_ID */]: 'The specified provider ID is invalid.',\r\n [\"invalid-recipient-email\" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */]: 'The email corresponding to this action failed to send as the provided ' +\r\n 'recipient email address is invalid.',\r\n [\"invalid-sender\" /* AuthErrorCode.INVALID_SENDER */]: 'The email template corresponding to this action contains an invalid sender email or name. ' +\r\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n [\"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */]: 'The verification ID used to create the phone auth credential is invalid.',\r\n [\"invalid-tenant-id\" /* AuthErrorCode.INVALID_TENANT_ID */]: \"The Auth instance's tenant ID is invalid.\",\r\n [\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */]: 'Login blocked by user-provided method: {$originalMessage}',\r\n [\"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */]: 'An Android Package Name must be provided if the Android App is required to be installed.',\r\n [\"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */]: 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\r\n 'by following the instructions in the Firebase console.',\r\n [\"missing-app-credential\" /* AuthErrorCode.MISSING_APP_CREDENTIAL */]: 'The phone verification request is missing an application verifier ' +\r\n 'assertion. A reCAPTCHA response token needs to be provided.',\r\n [\"missing-verification-code\" /* AuthErrorCode.MISSING_CODE */]: 'The phone auth credential was created with an empty SMS verification code.',\r\n [\"missing-continue-uri\" /* AuthErrorCode.MISSING_CONTINUE_URI */]: 'A continue URL must be provided in the request.',\r\n [\"missing-iframe-start\" /* AuthErrorCode.MISSING_IFRAME_START */]: 'An internal AuthError has occurred.',\r\n [\"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */]: 'An iOS Bundle ID must be provided if an App Store ID is provided.',\r\n [\"missing-or-invalid-nonce\" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */]: 'The request does not contain a valid nonce. This can occur if the ' +\r\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\r\n 'in the ID token payload.',\r\n [\"missing-password\" /* AuthErrorCode.MISSING_PASSWORD */]: 'A non-empty password must be provided',\r\n [\"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */]: 'No second factor identifier is provided.',\r\n [\"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */]: 'The request is missing proof of first factor successful sign-in.',\r\n [\"missing-phone-number\" /* AuthErrorCode.MISSING_PHONE_NUMBER */]: 'To send verification codes, provide a phone number for the recipient.',\r\n [\"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */]: 'The phone auth credential was created with an empty verification ID.',\r\n [\"app-deleted\" /* AuthErrorCode.MODULE_DESTROYED */]: 'This instance of FirebaseApp has been deleted.',\r\n [\"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */]: 'The user does not have a second factor matching the identifier provided.',\r\n [\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */]: 'Proof of ownership of a second factor is required to complete sign-in.',\r\n [\"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */]: 'An account already exists with the same email address but different ' +\r\n 'sign-in credentials. Sign in using a provider associated with this ' +\r\n 'email address.',\r\n [\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */]: 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\r\n [\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n [\"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */]: 'User was not linked to an account with the given provider.',\r\n [\"null-user\" /* AuthErrorCode.NULL_USER */]: 'A null user object was provided as the argument for an operation which ' +\r\n 'requires a non-null user object.',\r\n [\"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */]: 'The given sign-in provider is disabled for this Firebase project. ' +\r\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\r\n 'Auth section.',\r\n [\"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */]: 'This operation is not supported in the environment this application is ' +\r\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\r\n ' and web storage must be enabled.',\r\n [\"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */]: 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\r\n [\"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */]: 'The popup has been closed by the user before finalizing the operation.',\r\n [\"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */]: 'User can only be linked to one identity for the given provider.',\r\n [\"quota-exceeded\" /* AuthErrorCode.QUOTA_EXCEEDED */]: \"The project's quota for this operation has been exceeded.\",\r\n [\"redirect-cancelled-by-user\" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */]: 'The redirect operation has been cancelled by the user before finalizing.',\r\n [\"redirect-operation-pending\" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */]: 'A redirect sign-in operation is already pending.',\r\n [\"rejected-credential\" /* AuthErrorCode.REJECTED_CREDENTIAL */]: 'The request contains malformed or mismatching credentials.',\r\n [\"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */]: 'The second factor is already enrolled on this account.',\r\n [\"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */]: 'The maximum allowed number of second factors on a user has been exceeded.',\r\n [\"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */]: \"The provided tenant ID does not match the Auth instance's tenant ID\",\r\n [\"timeout\" /* AuthErrorCode.TIMEOUT */]: 'The operation has timed out.',\r\n [\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */]: \"The user's credential is no longer valid. The user must sign in again.\",\r\n [\"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */]: 'We have blocked all requests from this device due to unusual activity. ' +\r\n 'Try again later.',\r\n [\"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */]: 'The domain of the continue URL is not whitelisted. Please whitelist ' +\r\n 'the domain in the Firebase console.',\r\n [\"unsupported-first-factor\" /* AuthErrorCode.UNSUPPORTED_FIRST_FACTOR */]: 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\r\n [\"unsupported-persistence-type\" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */]: 'The current environment does not support the specified persistence type.',\r\n [\"unsupported-tenant-operation\" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */]: 'This operation is not supported in a multi-tenant context.',\r\n [\"unverified-email\" /* AuthErrorCode.UNVERIFIED_EMAIL */]: 'The operation requires a verified email.',\r\n [\"user-cancelled\" /* AuthErrorCode.USER_CANCELLED */]: 'The user did not grant your application the permissions it requested.',\r\n [\"user-not-found\" /* AuthErrorCode.USER_DELETED */]: 'There is no user record corresponding to this identifier. The user may ' +\r\n 'have been deleted.',\r\n [\"user-disabled\" /* AuthErrorCode.USER_DISABLED */]: 'The user account has been disabled by an administrator.',\r\n [\"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */]: 'The supplied credentials do not correspond to the previously signed in user.',\r\n [\"user-signed-out\" /* AuthErrorCode.USER_SIGNED_OUT */]: '',\r\n [\"weak-password\" /* AuthErrorCode.WEAK_PASSWORD */]: 'The password must be 6 characters long or more.',\r\n [\"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */]: 'This browser is not supported or 3rd party cookies and data may be disabled.',\r\n [\"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */]: 'initializeAuth() has already been called with ' +\r\n 'different options. To avoid this error, call initializeAuth() with the ' +\r\n 'same options as when it was originally called, or call getAuth() to return the' +\r\n ' already initialized instance.',\r\n [\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is missing when sending request to the backend.',\r\n [\"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is invalid when sending request to the backend.',\r\n [\"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */]: 'The reCAPTCHA action is invalid when sending request to the backend.',\r\n [\"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */]: 'reCAPTCHA Enterprise integration is not enabled for this project.',\r\n [\"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */]: 'The reCAPTCHA client type is missing when sending request to the backend.',\r\n [\"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is missing when sending request to the backend.',\r\n [\"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */]: 'Invalid request parameters.',\r\n [\"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is invalid when sending request to the backend.',\r\n [\"unsupported-password-policy-schema-version\" /* AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION */]: 'The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.',\r\n [\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */]: 'The password does not meet the requirements.'\r\n };\r\n}\r\nfunction _prodErrorMap() {\r\n // We will include this one message in the prod error map since by the very\r\n // nature of this error, developers will never be able to see the message\r\n // using the debugErrorMap (which is installed during auth initialization).\r\n return {\r\n [\"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n 'starting any other Firebase SDK.'\r\n };\r\n}\r\n/**\r\n * A verbose error map with detailed descriptions for most error codes.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst debugErrorMap = _debugErrorMap;\r\n/**\r\n * A minimal error map with all verbose error messages stripped.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst prodErrorMap = _prodErrorMap;\r\nconst _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());\r\n/**\r\n * A map of potential `Auth` error codes, for easier comparison with errors\r\n * thrown by the SDK.\r\n *\r\n * @remarks\r\n * Note that you can't tree-shake individual keys\r\n * in the map, so by using the map you might substantially increase your\r\n * bundle size.\r\n *\r\n * @public\r\n */\r\nconst AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\r\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\r\n ARGUMENT_ERROR: 'auth/argument-error',\r\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\r\n APP_NOT_INSTALLED: 'auth/app-not-installed',\r\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\r\n CODE_EXPIRED: 'auth/code-expired',\r\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\r\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\r\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\r\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\r\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\r\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\r\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\r\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\r\n EMAIL_EXISTS: 'auth/email-already-in-use',\r\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\r\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\r\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\r\n INTERNAL_ERROR: 'auth/internal-error',\r\n INVALID_API_KEY: 'auth/invalid-api-key',\r\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\r\n INVALID_APP_ID: 'auth/invalid-app-id',\r\n INVALID_AUTH: 'auth/invalid-user-token',\r\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\r\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\r\n INVALID_CODE: 'auth/invalid-verification-code',\r\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\r\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\r\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\r\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\r\n INVALID_EMAIL: 'auth/invalid-email',\r\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\r\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\r\n INVALID_LOGIN_CREDENTIALS: 'auth/invalid-credential',\r\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\r\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\r\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\r\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\r\n INVALID_OOB_CODE: 'auth/invalid-action-code',\r\n INVALID_ORIGIN: 'auth/unauthorized-domain',\r\n INVALID_PASSWORD: 'auth/wrong-password',\r\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\r\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\r\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\r\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\r\n INVALID_SENDER: 'auth/invalid-sender',\r\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\r\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\r\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\r\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\r\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\r\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\r\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\r\n MISSING_CODE: 'auth/missing-verification-code',\r\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\r\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\r\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\r\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\r\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\r\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\r\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\r\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\r\n MODULE_DESTROYED: 'auth/app-deleted',\r\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\r\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\r\n NULL_USER: 'auth/null-user',\r\n NO_AUTH_EVENT: 'auth/no-auth-event',\r\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\r\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\r\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\r\n POPUP_BLOCKED: 'auth/popup-blocked',\r\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\r\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\r\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\r\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\r\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\r\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\r\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\r\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\r\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\r\n TIMEOUT: 'auth/timeout',\r\n TOKEN_EXPIRED: 'auth/user-token-expired',\r\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\r\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\r\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\r\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\r\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\r\n UNVERIFIED_EMAIL: 'auth/unverified-email',\r\n USER_CANCELLED: 'auth/user-cancelled',\r\n USER_DELETED: 'auth/user-not-found',\r\n USER_DISABLED: 'auth/user-disabled',\r\n USER_MISMATCH: 'auth/user-mismatch',\r\n USER_SIGNED_OUT: 'auth/user-signed-out',\r\n WEAK_PASSWORD: 'auth/weak-password',\r\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\r\n ALREADY_INITIALIZED: 'auth/already-initialized',\r\n RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',\r\n MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',\r\n INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',\r\n INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',\r\n MISSING_CLIENT_TYPE: 'auth/missing-client-type',\r\n MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',\r\n INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',\r\n INVALID_REQ_TYPE: 'auth/invalid-req-type'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logClient = new Logger('@firebase/auth');\r\nfunction _logWarn(msg, ...args) {\r\n if (logClient.logLevel <= LogLevel.WARN) {\r\n logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);\r\n }\r\n}\r\nfunction _logError(msg, ...args) {\r\n if (logClient.logLevel <= LogLevel.ERROR) {\r\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _fail(authOrCode, ...rest) {\r\n throw createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _createError(authOrCode, ...rest) {\r\n return createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _errorWithCustomMessage(auth, code, message) {\r\n const errorMap = Object.assign(Object.assign({}, prodErrorMap()), { [code]: message });\r\n const factory = new ErrorFactory('auth', 'Firebase', errorMap);\r\n return factory.create(code, {\r\n appName: auth.name\r\n });\r\n}\r\nfunction _serverAppCurrentUserOperationNotSupportedError(auth) {\r\n return _errorWithCustomMessage(auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */, 'Operations that alter the current user are not supported in conjunction with FirebaseServerApp');\r\n}\r\nfunction _assertInstanceOf(auth, object, instance) {\r\n const constructorInstance = instance;\r\n if (!(object instanceof constructorInstance)) {\r\n if (constructorInstance.name !== object.constructor.name) {\r\n _fail(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n }\r\n throw _errorWithCustomMessage(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, `Type of ${object.constructor.name} does not match expected instance.` +\r\n `Did you pass a reference from a different Auth SDK?`);\r\n }\r\n}\r\nfunction createErrorInternal(authOrCode, ...rest) {\r\n if (typeof authOrCode !== 'string') {\r\n const code = rest[0];\r\n const fullParams = [...rest.slice(1)];\r\n if (fullParams[0]) {\r\n fullParams[0].appName = authOrCode.name;\r\n }\r\n return authOrCode._errorFactory.create(code, ...fullParams);\r\n }\r\n return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest);\r\n}\r\nfunction _assert(assertion, authOrCode, ...rest) {\r\n if (!assertion) {\r\n throw createErrorInternal(authOrCode, ...rest);\r\n }\r\n}\r\n/**\r\n * Unconditionally fails, throwing an internal error with the given message.\r\n *\r\n * @param failure type of failure encountered\r\n * @throws Error\r\n */\r\nfunction debugFail(failure) {\r\n // Log the failure in addition to throw an exception, just in case the\r\n // exception is swallowed.\r\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\r\n _logError(message);\r\n // NOTE: We don't use FirebaseError here because these are internal failures\r\n // that cannot be handled by the user. (Also it would create a circular\r\n // dependency between the error and assert modules which doesn't work.)\r\n throw new Error(message);\r\n}\r\n/**\r\n * Fails if the given assertion condition is false, throwing an Error with the\r\n * given message if it did.\r\n *\r\n * @param assertion\r\n * @param message\r\n */\r\nfunction debugAssert(assertion, message) {\r\n if (!assertion) {\r\n debugFail(message);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _getCurrentUrl() {\r\n var _a;\r\n return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';\r\n}\r\nfunction _isHttpOrHttps() {\r\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\r\n}\r\nfunction _getCurrentScheme() {\r\n var _a;\r\n return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine whether the browser is working online\r\n */\r\nfunction _isOnline() {\r\n if (typeof navigator !== 'undefined' &&\r\n navigator &&\r\n 'onLine' in navigator &&\r\n typeof navigator.onLine === 'boolean' &&\r\n // Apply only for traditional web apps and Chrome extensions.\r\n // This is especially true for Cordova apps which have unreliable\r\n // navigator.onLine behavior unless cordova-plugin-network-information is\r\n // installed which overwrites the native navigator.onLine value and\r\n // defines navigator.connection.\r\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {\r\n return navigator.onLine;\r\n }\r\n // If we can't determine the state, assume it is online.\r\n return true;\r\n}\r\nfunction _getUserLanguage() {\r\n if (typeof navigator === 'undefined') {\r\n return null;\r\n }\r\n const navigatorLanguage = navigator;\r\n return (\r\n // Most reliable, but only supported in Chrome/Firefox.\r\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\r\n // Supported in most browsers, but returns the language of the browser\r\n // UI, not the language set in browser settings.\r\n navigatorLanguage.language ||\r\n // Couldn't determine language.\r\n null);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A structure to help pick between a range of long and short delay durations\r\n * depending on the current environment. In general, the long delay is used for\r\n * mobile environments whereas short delays are used for desktop environments.\r\n */\r\nclass Delay {\r\n constructor(shortDelay, longDelay) {\r\n this.shortDelay = shortDelay;\r\n this.longDelay = longDelay;\r\n // Internal error when improperly initialized.\r\n debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');\r\n this.isMobile = isMobileCordova() || isReactNative();\r\n }\r\n get() {\r\n if (!_isOnline()) {\r\n // Pick the shorter timeout.\r\n return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);\r\n }\r\n // If running in a mobile environment, return the long delay, otherwise\r\n // return the short delay.\r\n // This could be improved in the future to dynamically change based on other\r\n // variables instead of just reading the current environment.\r\n return this.isMobile ? this.longDelay : this.shortDelay;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _emulatorUrl(config, path) {\r\n debugAssert(config.emulator, 'Emulator should always be set here');\r\n const { url } = config.emulator;\r\n if (!path) {\r\n return url;\r\n }\r\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FetchProvider {\r\n static initialize(fetchImpl, headersImpl, responseImpl) {\r\n this.fetchImpl = fetchImpl;\r\n if (headersImpl) {\r\n this.headersImpl = headersImpl;\r\n }\r\n if (responseImpl) {\r\n this.responseImpl = responseImpl;\r\n }\r\n }\r\n static fetch() {\r\n if (this.fetchImpl) {\r\n return this.fetchImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'fetch' in self) {\r\n return self.fetch;\r\n }\r\n if (typeof globalThis !== 'undefined' && globalThis.fetch) {\r\n return globalThis.fetch;\r\n }\r\n if (typeof fetch !== 'undefined') {\r\n return fetch;\r\n }\r\n debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n static headers() {\r\n if (this.headersImpl) {\r\n return this.headersImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'Headers' in self) {\r\n return self.Headers;\r\n }\r\n if (typeof globalThis !== 'undefined' && globalThis.Headers) {\r\n return globalThis.Headers;\r\n }\r\n if (typeof Headers !== 'undefined') {\r\n return Headers;\r\n }\r\n debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n static response() {\r\n if (this.responseImpl) {\r\n return this.responseImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'Response' in self) {\r\n return self.Response;\r\n }\r\n if (typeof globalThis !== 'undefined' && globalThis.Response) {\r\n return globalThis.Response;\r\n }\r\n if (typeof Response !== 'undefined') {\r\n return Response;\r\n }\r\n debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Map from errors returned by the server to errors to developer visible errors\r\n */\r\nconst SERVER_ERROR_MAP = {\r\n // Custom token errors.\r\n [\"CREDENTIAL_MISMATCH\" /* ServerError.CREDENTIAL_MISMATCH */]: \"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_CUSTOM_TOKEN\" /* ServerError.MISSING_CUSTOM_TOKEN */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Create Auth URI errors.\r\n [\"INVALID_IDENTIFIER\" /* ServerError.INVALID_IDENTIFIER */]: \"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_CONTINUE_URI\" /* ServerError.MISSING_CONTINUE_URI */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Sign in with email and password errors (some apply to sign up too).\r\n [\"INVALID_PASSWORD\" /* ServerError.INVALID_PASSWORD */]: \"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_PASSWORD\" /* ServerError.MISSING_PASSWORD */]: \"missing-password\" /* AuthErrorCode.MISSING_PASSWORD */,\r\n // Thrown if Email Enumeration Protection is enabled in the project and the email or password is\r\n // invalid.\r\n [\"INVALID_LOGIN_CREDENTIALS\" /* ServerError.INVALID_LOGIN_CREDENTIALS */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\r\n // Sign up with email and password errors.\r\n [\"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */]: \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */,\r\n [\"PASSWORD_LOGIN_DISABLED\" /* ServerError.PASSWORD_LOGIN_DISABLED */]: \"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,\r\n // Verify assertion for sign in with credential errors:\r\n [\"INVALID_IDP_RESPONSE\" /* ServerError.INVALID_IDP_RESPONSE */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\r\n [\"INVALID_PENDING_TOKEN\" /* ServerError.INVALID_PENDING_TOKEN */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\r\n [\"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */]: \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_REQ_TYPE\" /* ServerError.MISSING_REQ_TYPE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Send Password reset email errors:\r\n [\"EMAIL_NOT_FOUND\" /* ServerError.EMAIL_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */,\r\n [\"RESET_PASSWORD_EXCEED_LIMIT\" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n [\"EXPIRED_OOB_CODE\" /* ServerError.EXPIRED_OOB_CODE */]: \"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */,\r\n [\"INVALID_OOB_CODE\" /* ServerError.INVALID_OOB_CODE */]: \"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_OOB_CODE\" /* ServerError.MISSING_OOB_CODE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Operations that require ID token in request:\r\n [\"CREDENTIAL_TOO_OLD_LOGIN_AGAIN\" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: \"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,\r\n [\"INVALID_ID_TOKEN\" /* ServerError.INVALID_ID_TOKEN */]: \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */,\r\n [\"TOKEN_EXPIRED\" /* ServerError.TOKEN_EXPIRED */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\r\n [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\r\n // Other errors.\r\n [\"TOO_MANY_ATTEMPTS_TRY_LATER\" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n [\"PASSWORD_DOES_NOT_MEET_REQUIREMENTS\" /* ServerError.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */]: \"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */,\r\n // Phone Auth related errors.\r\n [\"INVALID_CODE\" /* ServerError.INVALID_CODE */]: \"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */,\r\n [\"INVALID_SESSION_INFO\" /* ServerError.INVALID_SESSION_INFO */]: \"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */,\r\n [\"INVALID_TEMPORARY_PROOF\" /* ServerError.INVALID_TEMPORARY_PROOF */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\r\n [\"MISSING_SESSION_INFO\" /* ServerError.MISSING_SESSION_INFO */]: \"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */,\r\n [\"SESSION_EXPIRED\" /* ServerError.SESSION_EXPIRED */]: \"code-expired\" /* AuthErrorCode.CODE_EXPIRED */,\r\n // Other action code errors when additional settings passed.\r\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\r\n // This is OK as this error will be caught by client side validation.\r\n [\"MISSING_ANDROID_PACKAGE_NAME\" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */]: \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,\r\n [\"UNAUTHORIZED_DOMAIN\" /* ServerError.UNAUTHORIZED_DOMAIN */]: \"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,\r\n // getProjectConfig errors when clientId is passed.\r\n [\"INVALID_OAUTH_CLIENT_ID\" /* ServerError.INVALID_OAUTH_CLIENT_ID */]: \"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,\r\n // User actions (sign-up or deletion) disabled errors.\r\n [\"ADMIN_ONLY_OPERATION\" /* ServerError.ADMIN_ONLY_OPERATION */]: \"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,\r\n // Multi factor related errors.\r\n [\"INVALID_MFA_PENDING_CREDENTIAL\" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */]: \"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */,\r\n [\"MFA_ENROLLMENT_NOT_FOUND\" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */]: \"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,\r\n [\"MISSING_MFA_ENROLLMENT_ID\" /* ServerError.MISSING_MFA_ENROLLMENT_ID */]: \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */,\r\n [\"MISSING_MFA_PENDING_CREDENTIAL\" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */]: \"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */,\r\n [\"SECOND_FACTOR_EXISTS\" /* ServerError.SECOND_FACTOR_EXISTS */]: \"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,\r\n [\"SECOND_FACTOR_LIMIT_EXCEEDED\" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */]: \"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,\r\n // Blocking functions related errors.\r\n [\"BLOCKING_FUNCTION_ERROR_RESPONSE\" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Recaptcha related errors.\r\n [\"RECAPTCHA_NOT_ENABLED\" /* ServerError.RECAPTCHA_NOT_ENABLED */]: \"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */,\r\n [\"MISSING_RECAPTCHA_TOKEN\" /* ServerError.MISSING_RECAPTCHA_TOKEN */]: \"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */,\r\n [\"INVALID_RECAPTCHA_TOKEN\" /* ServerError.INVALID_RECAPTCHA_TOKEN */]: \"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */,\r\n [\"INVALID_RECAPTCHA_ACTION\" /* ServerError.INVALID_RECAPTCHA_ACTION */]: \"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */,\r\n [\"MISSING_CLIENT_TYPE\" /* ServerError.MISSING_CLIENT_TYPE */]: \"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */,\r\n [\"MISSING_RECAPTCHA_VERSION\" /* ServerError.MISSING_RECAPTCHA_VERSION */]: \"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */,\r\n [\"INVALID_RECAPTCHA_VERSION\" /* ServerError.INVALID_RECAPTCHA_VERSION */]: \"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */,\r\n [\"INVALID_REQ_TYPE\" /* ServerError.INVALID_REQ_TYPE */]: \"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);\r\nfunction _addTidIfNecessary(auth, request) {\r\n if (auth.tenantId && !request.tenantId) {\r\n return Object.assign(Object.assign({}, request), { tenantId: auth.tenantId });\r\n }\r\n return request;\r\n}\r\nasync function _performApiRequest(auth, method, path, request, customErrorMap = {}) {\r\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\r\n let body = {};\r\n let params = {};\r\n if (request) {\r\n if (method === \"GET\" /* HttpMethod.GET */) {\r\n params = request;\r\n }\r\n else {\r\n body = {\r\n body: JSON.stringify(request)\r\n };\r\n }\r\n }\r\n const query = querystring(Object.assign({ key: auth.config.apiKey }, params)).slice(1);\r\n const headers = await auth._getAdditionalHeaders();\r\n headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/json';\r\n if (auth.languageCode) {\r\n headers[\"X-Firebase-Locale\" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;\r\n }\r\n return FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), Object.assign({ method,\r\n headers, referrerPolicy: 'no-referrer' }, body));\r\n });\r\n}\r\nasync function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {\r\n auth._canInitEmulator = false;\r\n const errorMap = Object.assign(Object.assign({}, SERVER_ERROR_MAP), customErrorMap);\r\n try {\r\n const networkTimeout = new NetworkTimeout(auth);\r\n const response = await Promise.race([\r\n fetchFn(),\r\n networkTimeout.promise\r\n ]);\r\n // If we've reached this point, the fetch succeeded and the networkTimeout\r\n // didn't throw; clear the network timeout delay so that Node won't hang\r\n networkTimeout.clearNetworkTimeout();\r\n const json = await response.json();\r\n if ('needConfirmation' in json) {\r\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, json);\r\n }\r\n if (response.ok && !('errorMessage' in json)) {\r\n return json;\r\n }\r\n else {\r\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\r\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\r\n if (serverErrorCode === \"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {\r\n throw _makeTaggedError(auth, \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);\r\n }\r\n else if (serverErrorCode === \"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */) {\r\n throw _makeTaggedError(auth, \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */, json);\r\n }\r\n else if (serverErrorCode === \"USER_DISABLED\" /* ServerError.USER_DISABLED */) {\r\n throw _makeTaggedError(auth, \"user-disabled\" /* AuthErrorCode.USER_DISABLED */, json);\r\n }\r\n const authError = errorMap[serverErrorCode] ||\r\n serverErrorCode\r\n .toLowerCase()\r\n .replace(/[_\\s]+/g, '-');\r\n if (serverErrorMessage) {\r\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\r\n }\r\n else {\r\n _fail(auth, authError);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n throw e;\r\n }\r\n // Changing this to a different error code will log user out when there is a network error\r\n // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.\r\n // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316\r\n _fail(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */, { 'message': String(e) });\r\n }\r\n}\r\nasync function _performSignInRequest(auth, method, path, request, customErrorMap = {}) {\r\n const serverResponse = (await _performApiRequest(auth, method, path, request, customErrorMap));\r\n if ('mfaPendingCredential' in serverResponse) {\r\n _fail(auth, \"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */, {\r\n _serverResponse: serverResponse\r\n });\r\n }\r\n return serverResponse;\r\n}\r\nfunction _getFinalTarget(auth, host, path, query) {\r\n const base = `${host}${path}?${query}`;\r\n if (!auth.config.emulator) {\r\n return `${auth.config.apiScheme}://${base}`;\r\n }\r\n return _emulatorUrl(auth.config, base);\r\n}\r\nfunction _parseEnforcementState(enforcementStateStr) {\r\n switch (enforcementStateStr) {\r\n case 'ENFORCE':\r\n return \"ENFORCE\" /* EnforcementState.ENFORCE */;\r\n case 'AUDIT':\r\n return \"AUDIT\" /* EnforcementState.AUDIT */;\r\n case 'OFF':\r\n return \"OFF\" /* EnforcementState.OFF */;\r\n default:\r\n return \"ENFORCEMENT_STATE_UNSPECIFIED\" /* EnforcementState.ENFORCEMENT_STATE_UNSPECIFIED */;\r\n }\r\n}\r\nclass NetworkTimeout {\r\n constructor(auth) {\r\n this.auth = auth;\r\n // Node timers and browser timers are fundamentally incompatible, but we\r\n // don't care about the value here\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.timer = null;\r\n this.promise = new Promise((_, reject) => {\r\n this.timer = setTimeout(() => {\r\n return reject(_createError(this.auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }, DEFAULT_API_TIMEOUT_MS.get());\r\n });\r\n }\r\n clearNetworkTimeout() {\r\n clearTimeout(this.timer);\r\n }\r\n}\r\nfunction _makeTaggedError(auth, code, response) {\r\n const errorParams = {\r\n appName: auth.name\r\n };\r\n if (response.email) {\r\n errorParams.email = response.email;\r\n }\r\n if (response.phoneNumber) {\r\n errorParams.phoneNumber = response.phoneNumber;\r\n }\r\n const error = _createError(auth, code, errorParams);\r\n // We know customData is defined on error because errorParams is defined\r\n error.customData._tokenResponse = response;\r\n return error;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isV2(grecaptcha) {\r\n return (grecaptcha !== undefined &&\r\n grecaptcha.getResponse !== undefined);\r\n}\r\nfunction isEnterprise(grecaptcha) {\r\n return (grecaptcha !== undefined &&\r\n grecaptcha.enterprise !== undefined);\r\n}\r\nclass RecaptchaConfig {\r\n constructor(response) {\r\n /**\r\n * The reCAPTCHA site key.\r\n */\r\n this.siteKey = '';\r\n /**\r\n * The list of providers and their enablement status for reCAPTCHA Enterprise.\r\n */\r\n this.recaptchaEnforcementState = [];\r\n if (response.recaptchaKey === undefined) {\r\n throw new Error('recaptchaKey undefined');\r\n }\r\n // Example response.recaptchaKey: \"projects/proj123/keys/sitekey123\"\r\n this.siteKey = response.recaptchaKey.split('/')[3];\r\n this.recaptchaEnforcementState = response.recaptchaEnforcementState;\r\n }\r\n /**\r\n * Returns the reCAPTCHA Enterprise enforcement state for the given provider.\r\n *\r\n * @param providerStr - The provider whose enforcement state is to be returned.\r\n * @returns The reCAPTCHA Enterprise enforcement state for the given provider.\r\n */\r\n getProviderEnforcementState(providerStr) {\r\n if (!this.recaptchaEnforcementState ||\r\n this.recaptchaEnforcementState.length === 0) {\r\n return null;\r\n }\r\n for (const recaptchaEnforcementState of this.recaptchaEnforcementState) {\r\n if (recaptchaEnforcementState.provider &&\r\n recaptchaEnforcementState.provider === providerStr) {\r\n return _parseEnforcementState(recaptchaEnforcementState.enforcementState);\r\n }\r\n }\r\n return null;\r\n }\r\n /**\r\n * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT.\r\n *\r\n * @param providerStr - The provider whose enablement state is to be returned.\r\n * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider.\r\n */\r\n isProviderEnabled(providerStr) {\r\n return (this.getProviderEnforcementState(providerStr) ===\r\n \"ENFORCE\" /* EnforcementState.ENFORCE */ ||\r\n this.getProviderEnforcementState(providerStr) === \"AUDIT\" /* EnforcementState.AUDIT */);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function getRecaptchaParams(auth) {\r\n return ((await _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/recaptchaParams\" /* Endpoint.GET_RECAPTCHA_PARAM */)).recaptchaSiteKey || '');\r\n}\r\nasync function getRecaptchaConfig(auth, request) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v2/recaptchaConfig\" /* Endpoint.GET_RECAPTCHA_CONFIG */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteAccount(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:delete\" /* Endpoint.DELETE_ACCOUNT */, request);\r\n}\r\nasync function deleteLinkedAccounts(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\r\nasync function getAccountInfo(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:lookup\" /* Endpoint.GET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction utcTimestampToDateString(utcTimestamp) {\r\n if (!utcTimestamp) {\r\n return undefined;\r\n }\r\n try {\r\n // Convert to date object.\r\n const date = new Date(Number(utcTimestamp));\r\n // Test date is valid.\r\n if (!isNaN(date.getTime())) {\r\n // Convert to UTC date string.\r\n return date.toUTCString();\r\n }\r\n }\r\n catch (e) {\r\n // Do nothing. undefined will be returned.\r\n }\r\n return undefined;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nfunction getIdToken(user, forceRefresh = false) {\r\n return getModularInstance(user).getIdToken(forceRefresh);\r\n}\r\n/**\r\n * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nasync function getIdTokenResult(user, forceRefresh = false) {\r\n const userInternal = getModularInstance(user);\r\n const token = await userInternal.getIdToken(forceRefresh);\r\n const claims = _parseToken(token);\r\n _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;\r\n const signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];\r\n return {\r\n claims,\r\n token,\r\n authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),\r\n issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),\r\n expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),\r\n signInProvider: signInProvider || null,\r\n signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null\r\n };\r\n}\r\nfunction secondsStringToMilliseconds(seconds) {\r\n return Number(seconds) * 1000;\r\n}\r\nfunction _parseToken(token) {\r\n const [algorithm, payload, signature] = token.split('.');\r\n if (algorithm === undefined ||\r\n payload === undefined ||\r\n signature === undefined) {\r\n _logError('JWT malformed, contained fewer than 3 sections');\r\n return null;\r\n }\r\n try {\r\n const decoded = base64Decode(payload);\r\n if (!decoded) {\r\n _logError('Failed to decode base64 JWT payload');\r\n return null;\r\n }\r\n return JSON.parse(decoded);\r\n }\r\n catch (e) {\r\n _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());\r\n return null;\r\n }\r\n}\r\n/**\r\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\r\n */\r\nfunction _tokenExpiresIn(token) {\r\n const parsedToken = _parseToken(token);\r\n _assert(parsedToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.exp !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.iat !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return Number(parsedToken.exp) - Number(parsedToken.iat);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _logoutIfInvalidated(user, promise, bypassAuthState = false) {\r\n if (bypassAuthState) {\r\n return promise;\r\n }\r\n try {\r\n return await promise;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\r\n if (user.auth.currentUser === user) {\r\n await user.auth.signOut();\r\n }\r\n }\r\n throw e;\r\n }\r\n}\r\nfunction isUserInvalidated({ code }) {\r\n return (code === `auth/${\"user-disabled\" /* AuthErrorCode.USER_DISABLED */}` ||\r\n code === `auth/${\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */}`);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ProactiveRefresh {\r\n constructor(user) {\r\n this.user = user;\r\n this.isRunning = false;\r\n // Node timers and browser timers return fundamentally different types.\r\n // We don't actually care what the value is but TS won't accept unknown and\r\n // we can't cast properly in both environments.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.timerId = null;\r\n this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\r\n }\r\n _start() {\r\n if (this.isRunning) {\r\n return;\r\n }\r\n this.isRunning = true;\r\n this.schedule();\r\n }\r\n _stop() {\r\n if (!this.isRunning) {\r\n return;\r\n }\r\n this.isRunning = false;\r\n if (this.timerId !== null) {\r\n clearTimeout(this.timerId);\r\n }\r\n }\r\n getInterval(wasError) {\r\n var _a;\r\n if (wasError) {\r\n const interval = this.errorBackoff;\r\n this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);\r\n return interval;\r\n }\r\n else {\r\n // Reset the error backoff\r\n this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\r\n const expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;\r\n const interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;\r\n return Math.max(0, interval);\r\n }\r\n }\r\n schedule(wasError = false) {\r\n if (!this.isRunning) {\r\n // Just in case...\r\n return;\r\n }\r\n const interval = this.getInterval(wasError);\r\n this.timerId = setTimeout(async () => {\r\n await this.iteration();\r\n }, interval);\r\n }\r\n async iteration() {\r\n try {\r\n await this.user.getIdToken(true);\r\n }\r\n catch (e) {\r\n // Only retry on network errors\r\n if ((e === null || e === void 0 ? void 0 : e.code) ===\r\n `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {\r\n this.schedule(/* wasError */ true);\r\n }\r\n return;\r\n }\r\n this.schedule();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserMetadata {\r\n constructor(createdAt, lastLoginAt) {\r\n this.createdAt = createdAt;\r\n this.lastLoginAt = lastLoginAt;\r\n this._initializeTime();\r\n }\r\n _initializeTime() {\r\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\r\n this.creationTime = utcTimestampToDateString(this.createdAt);\r\n }\r\n _copy(metadata) {\r\n this.createdAt = metadata.createdAt;\r\n this.lastLoginAt = metadata.lastLoginAt;\r\n this._initializeTime();\r\n }\r\n toJSON() {\r\n return {\r\n createdAt: this.createdAt,\r\n lastLoginAt: this.lastLoginAt\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reloadWithoutSaving(user) {\r\n var _a;\r\n const auth = user.auth;\r\n const idToken = await user.getIdToken();\r\n const response = await _logoutIfInvalidated(user, getAccountInfo(auth, { idToken }));\r\n _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const coreAccount = response.users[0];\r\n user._notifyReloadListener(coreAccount);\r\n const newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)\r\n ? extractProviderData(coreAccount.providerUserInfo)\r\n : [];\r\n const providerData = mergeProviderData(user.providerData, newProviderData);\r\n // Preserves the non-nonymous status of the stored user, even if no more\r\n // credentials (federated or email/password) are linked to the user. If\r\n // the user was previously anonymous, then use provider data to update.\r\n // On the other hand, if it was not anonymous before, it should never be\r\n // considered anonymous now.\r\n const oldIsAnonymous = user.isAnonymous;\r\n const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);\r\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\r\n const updates = {\r\n uid: coreAccount.localId,\r\n displayName: coreAccount.displayName || null,\r\n photoURL: coreAccount.photoUrl || null,\r\n email: coreAccount.email || null,\r\n emailVerified: coreAccount.emailVerified || false,\r\n phoneNumber: coreAccount.phoneNumber || null,\r\n tenantId: coreAccount.tenantId || null,\r\n providerData,\r\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\r\n isAnonymous\r\n };\r\n Object.assign(user, updates);\r\n}\r\n/**\r\n * Reloads user account data, if signed in.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function reload(user) {\r\n const userInternal = getModularInstance(user);\r\n await _reloadWithoutSaving(userInternal);\r\n // Even though the current user hasn't changed, update\r\n // current user will trigger a persistence update w/ the\r\n // new info.\r\n await userInternal.auth._persistUserIfCurrent(userInternal);\r\n userInternal.auth._notifyListenersIfCurrent(userInternal);\r\n}\r\nfunction mergeProviderData(original, newData) {\r\n const deduped = original.filter(o => !newData.some(n => n.providerId === o.providerId));\r\n return [...deduped, ...newData];\r\n}\r\nfunction extractProviderData(providers) {\r\n return providers.map((_a) => {\r\n var { providerId } = _a, provider = __rest(_a, [\"providerId\"]);\r\n return {\r\n providerId,\r\n uid: provider.rawId || '',\r\n displayName: provider.displayName || null,\r\n email: provider.email || null,\r\n phoneNumber: provider.phoneNumber || null,\r\n photoURL: provider.photoUrl || null\r\n };\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function requestStsToken(auth, refreshToken) {\r\n const response = await _performFetchWithErrorHandling(auth, {}, async () => {\r\n const body = querystring({\r\n 'grant_type': 'refresh_token',\r\n 'refresh_token': refreshToken\r\n }).slice(1);\r\n const { tokenApiHost, apiKey } = auth.config;\r\n const url = _getFinalTarget(auth, tokenApiHost, \"/v1/token\" /* Endpoint.TOKEN */, `key=${apiKey}`);\r\n const headers = await auth._getAdditionalHeaders();\r\n headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';\r\n return FetchProvider.fetch()(url, {\r\n method: \"POST\" /* HttpMethod.POST */,\r\n headers,\r\n body\r\n });\r\n });\r\n // The response comes back in snake_case. Convert to camel:\r\n return {\r\n accessToken: response.access_token,\r\n expiresIn: response.expires_in,\r\n refreshToken: response.refresh_token\r\n };\r\n}\r\nasync function revokeToken(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts:revokeToken\" /* Endpoint.REVOKE_TOKEN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\r\n * it references AuthInternal which has a circular dependency with UserInternal.\r\n *\r\n * @internal\r\n */\r\nclass StsTokenManager {\r\n constructor() {\r\n this.refreshToken = null;\r\n this.accessToken = null;\r\n this.expirationTime = null;\r\n }\r\n get isExpired() {\r\n return (!this.expirationTime ||\r\n Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);\r\n }\r\n updateFromServerResponse(response) {\r\n _assert(response.idToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof response.idToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof response.refreshToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\r\n ? Number(response.expiresIn)\r\n : _tokenExpiresIn(response.idToken);\r\n this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);\r\n }\r\n updateFromIdToken(idToken) {\r\n _assert(idToken.length !== 0, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const expiresIn = _tokenExpiresIn(idToken);\r\n this.updateTokensAndExpiration(idToken, null, expiresIn);\r\n }\r\n async getToken(auth, forceRefresh = false) {\r\n if (!forceRefresh && this.accessToken && !this.isExpired) {\r\n return this.accessToken;\r\n }\r\n _assert(this.refreshToken, auth, \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */);\r\n if (this.refreshToken) {\r\n await this.refresh(auth, this.refreshToken);\r\n return this.accessToken;\r\n }\r\n return null;\r\n }\r\n clearRefreshToken() {\r\n this.refreshToken = null;\r\n }\r\n async refresh(auth, oldToken) {\r\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth, oldToken);\r\n this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));\r\n }\r\n updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) {\r\n this.refreshToken = refreshToken || null;\r\n this.accessToken = accessToken || null;\r\n this.expirationTime = Date.now() + expiresInSec * 1000;\r\n }\r\n static fromJSON(appName, object) {\r\n const { refreshToken, accessToken, expirationTime } = object;\r\n const manager = new StsTokenManager();\r\n if (refreshToken) {\r\n _assert(typeof refreshToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.refreshToken = refreshToken;\r\n }\r\n if (accessToken) {\r\n _assert(typeof accessToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.accessToken = accessToken;\r\n }\r\n if (expirationTime) {\r\n _assert(typeof expirationTime === 'number', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.expirationTime = expirationTime;\r\n }\r\n return manager;\r\n }\r\n toJSON() {\r\n return {\r\n refreshToken: this.refreshToken,\r\n accessToken: this.accessToken,\r\n expirationTime: this.expirationTime\r\n };\r\n }\r\n _assign(stsTokenManager) {\r\n this.accessToken = stsTokenManager.accessToken;\r\n this.refreshToken = stsTokenManager.refreshToken;\r\n this.expirationTime = stsTokenManager.expirationTime;\r\n }\r\n _clone() {\r\n return Object.assign(new StsTokenManager(), this.toJSON());\r\n }\r\n _performRefresh() {\r\n return debugFail('not implemented');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction assertStringOrUndefined(assertion, appName) {\r\n _assert(typeof assertion === 'string' || typeof assertion === 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, { appName });\r\n}\r\nclass UserImpl {\r\n constructor(_a) {\r\n var { uid, auth, stsTokenManager } = _a, opt = __rest(_a, [\"uid\", \"auth\", \"stsTokenManager\"]);\r\n // For the user object, provider is always Firebase.\r\n this.providerId = \"firebase\" /* ProviderId.FIREBASE */;\r\n this.proactiveRefresh = new ProactiveRefresh(this);\r\n this.reloadUserInfo = null;\r\n this.reloadListener = null;\r\n this.uid = uid;\r\n this.auth = auth;\r\n this.stsTokenManager = stsTokenManager;\r\n this.accessToken = stsTokenManager.accessToken;\r\n this.displayName = opt.displayName || null;\r\n this.email = opt.email || null;\r\n this.emailVerified = opt.emailVerified || false;\r\n this.phoneNumber = opt.phoneNumber || null;\r\n this.photoURL = opt.photoURL || null;\r\n this.isAnonymous = opt.isAnonymous || false;\r\n this.tenantId = opt.tenantId || null;\r\n this.providerData = opt.providerData ? [...opt.providerData] : [];\r\n this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);\r\n }\r\n async getIdToken(forceRefresh) {\r\n const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh));\r\n _assert(accessToken, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n if (this.accessToken !== accessToken) {\r\n this.accessToken = accessToken;\r\n await this.auth._persistUserIfCurrent(this);\r\n this.auth._notifyListenersIfCurrent(this);\r\n }\r\n return accessToken;\r\n }\r\n getIdTokenResult(forceRefresh) {\r\n return getIdTokenResult(this, forceRefresh);\r\n }\r\n reload() {\r\n return reload(this);\r\n }\r\n _assign(user) {\r\n if (this === user) {\r\n return;\r\n }\r\n _assert(this.uid === user.uid, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.displayName = user.displayName;\r\n this.photoURL = user.photoURL;\r\n this.email = user.email;\r\n this.emailVerified = user.emailVerified;\r\n this.phoneNumber = user.phoneNumber;\r\n this.isAnonymous = user.isAnonymous;\r\n this.tenantId = user.tenantId;\r\n this.providerData = user.providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n this.metadata._copy(user.metadata);\r\n this.stsTokenManager._assign(user.stsTokenManager);\r\n }\r\n _clone(auth) {\r\n const newUser = new UserImpl(Object.assign(Object.assign({}, this), { auth, stsTokenManager: this.stsTokenManager._clone() }));\r\n newUser.metadata._copy(this.metadata);\r\n return newUser;\r\n }\r\n _onReload(callback) {\r\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\r\n _assert(!this.reloadListener, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.reloadListener = callback;\r\n if (this.reloadUserInfo) {\r\n this._notifyReloadListener(this.reloadUserInfo);\r\n this.reloadUserInfo = null;\r\n }\r\n }\r\n _notifyReloadListener(userInfo) {\r\n if (this.reloadListener) {\r\n this.reloadListener(userInfo);\r\n }\r\n else {\r\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\r\n this.reloadUserInfo = userInfo;\r\n }\r\n }\r\n _startProactiveRefresh() {\r\n this.proactiveRefresh._start();\r\n }\r\n _stopProactiveRefresh() {\r\n this.proactiveRefresh._stop();\r\n }\r\n async _updateTokensIfNecessary(response, reload = false) {\r\n let tokensRefreshed = false;\r\n if (response.idToken &&\r\n response.idToken !== this.stsTokenManager.accessToken) {\r\n this.stsTokenManager.updateFromServerResponse(response);\r\n tokensRefreshed = true;\r\n }\r\n if (reload) {\r\n await _reloadWithoutSaving(this);\r\n }\r\n await this.auth._persistUserIfCurrent(this);\r\n if (tokensRefreshed) {\r\n this.auth._notifyListenersIfCurrent(this);\r\n }\r\n }\r\n async delete() {\r\n if (_isFirebaseServerApp(this.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth));\r\n }\r\n const idToken = await this.getIdToken();\r\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\r\n this.stsTokenManager.clearRefreshToken();\r\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\r\n // cancels pending actions...\r\n return this.auth.signOut();\r\n }\r\n toJSON() {\r\n return Object.assign(Object.assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(userInfo => (Object.assign({}, userInfo))), stsTokenManager: this.stsTokenManager.toJSON(), \r\n // Redirect event ID must be maintained in case there is a pending\r\n // redirect event.\r\n _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), { \r\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\r\n apiKey: this.auth.config.apiKey, appName: this.auth.name });\r\n }\r\n get refreshToken() {\r\n return this.stsTokenManager.refreshToken || '';\r\n }\r\n static _fromJSON(auth, object) {\r\n var _a, _b, _c, _d, _e, _f, _g, _h;\r\n const displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;\r\n const email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;\r\n const phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;\r\n const photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;\r\n const tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;\r\n const _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;\r\n const createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;\r\n const lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;\r\n const { uid, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object;\r\n _assert(uid && plainObjectTokenManager, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);\r\n _assert(typeof uid === 'string', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n assertStringOrUndefined(displayName, auth.name);\r\n assertStringOrUndefined(email, auth.name);\r\n _assert(typeof emailVerified === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof isAnonymous === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n assertStringOrUndefined(phoneNumber, auth.name);\r\n assertStringOrUndefined(photoURL, auth.name);\r\n assertStringOrUndefined(tenantId, auth.name);\r\n assertStringOrUndefined(_redirectEventId, auth.name);\r\n assertStringOrUndefined(createdAt, auth.name);\r\n assertStringOrUndefined(lastLoginAt, auth.name);\r\n const user = new UserImpl({\r\n uid,\r\n auth,\r\n email,\r\n emailVerified,\r\n displayName,\r\n isAnonymous,\r\n photoURL,\r\n phoneNumber,\r\n tenantId,\r\n stsTokenManager,\r\n createdAt,\r\n lastLoginAt\r\n });\r\n if (providerData && Array.isArray(providerData)) {\r\n user.providerData = providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n }\r\n if (_redirectEventId) {\r\n user._redirectEventId = _redirectEventId;\r\n }\r\n return user;\r\n }\r\n /**\r\n * Initialize a User from an idToken server response\r\n * @param auth\r\n * @param idTokenResponse\r\n */\r\n static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {\r\n const stsTokenManager = new StsTokenManager();\r\n stsTokenManager.updateFromServerResponse(idTokenResponse);\r\n // Initialize the Firebase Auth user.\r\n const user = new UserImpl({\r\n uid: idTokenResponse.localId,\r\n auth,\r\n stsTokenManager,\r\n isAnonymous\r\n });\r\n // Updates the user info and data and resolves with a user instance.\r\n await _reloadWithoutSaving(user);\r\n return user;\r\n }\r\n /**\r\n * Initialize a User from an idToken server response\r\n * @param auth\r\n * @param idTokenResponse\r\n */\r\n static async _fromGetAccountInfoResponse(auth, response, idToken) {\r\n const coreAccount = response.users[0];\r\n _assert(coreAccount.localId !== undefined, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const providerData = coreAccount.providerUserInfo !== undefined\r\n ? extractProviderData(coreAccount.providerUserInfo)\r\n : [];\r\n const isAnonymous = !(coreAccount.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);\r\n const stsTokenManager = new StsTokenManager();\r\n stsTokenManager.updateFromIdToken(idToken);\r\n // Initialize the Firebase Auth user.\r\n const user = new UserImpl({\r\n uid: coreAccount.localId,\r\n auth,\r\n stsTokenManager,\r\n isAnonymous\r\n });\r\n // update the user with data from the GetAccountInfo response.\r\n const updates = {\r\n uid: coreAccount.localId,\r\n displayName: coreAccount.displayName || null,\r\n photoURL: coreAccount.photoUrl || null,\r\n email: coreAccount.email || null,\r\n emailVerified: coreAccount.emailVerified || false,\r\n phoneNumber: coreAccount.phoneNumber || null,\r\n tenantId: coreAccount.tenantId || null,\r\n providerData,\r\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\r\n isAnonymous: !(coreAccount.email && coreAccount.passwordHash) &&\r\n !(providerData === null || providerData === void 0 ? void 0 : providerData.length)\r\n };\r\n Object.assign(user, updates);\r\n return user;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst instanceCache = new Map();\r\nfunction _getInstance(cls) {\r\n debugAssert(cls instanceof Function, 'Expected a class definition');\r\n let instance = instanceCache.get(cls);\r\n if (instance) {\r\n debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');\r\n return instance;\r\n }\r\n instance = new cls();\r\n instanceCache.set(cls, instance);\r\n return instance;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass InMemoryPersistence {\r\n constructor() {\r\n this.type = \"NONE\" /* PersistenceType.NONE */;\r\n this.storage = {};\r\n }\r\n async _isAvailable() {\r\n return true;\r\n }\r\n async _set(key, value) {\r\n this.storage[key] = value;\r\n }\r\n async _get(key) {\r\n const value = this.storage[key];\r\n return value === undefined ? null : value;\r\n }\r\n async _remove(key) {\r\n delete this.storage[key];\r\n }\r\n _addListener(_key, _listener) {\r\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n return;\r\n }\r\n _removeListener(_key, _listener) {\r\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n return;\r\n }\r\n}\r\nInMemoryPersistence.type = 'NONE';\r\n/**\r\n * An implementation of {@link Persistence} of type 'NONE'.\r\n *\r\n * @public\r\n */\r\nconst inMemoryPersistence = InMemoryPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _persistenceKeyName(key, apiKey, appName) {\r\n return `${\"firebase\" /* Namespace.PERSISTENCE */}:${key}:${apiKey}:${appName}`;\r\n}\r\nclass PersistenceUserManager {\r\n constructor(persistence, auth, userKey) {\r\n this.persistence = persistence;\r\n this.auth = auth;\r\n this.userKey = userKey;\r\n const { config, name } = this.auth;\r\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\r\n this.fullPersistenceKey = _persistenceKeyName(\"persistence\" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);\r\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\r\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\r\n }\r\n setCurrentUser(user) {\r\n return this.persistence._set(this.fullUserKey, user.toJSON());\r\n }\r\n async getCurrentUser() {\r\n const blob = await this.persistence._get(this.fullUserKey);\r\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\r\n }\r\n removeCurrentUser() {\r\n return this.persistence._remove(this.fullUserKey);\r\n }\r\n savePersistenceForRedirect() {\r\n return this.persistence._set(this.fullPersistenceKey, this.persistence.type);\r\n }\r\n async setPersistence(newPersistence) {\r\n if (this.persistence === newPersistence) {\r\n return;\r\n }\r\n const currentUser = await this.getCurrentUser();\r\n await this.removeCurrentUser();\r\n this.persistence = newPersistence;\r\n if (currentUser) {\r\n return this.setCurrentUser(currentUser);\r\n }\r\n }\r\n delete() {\r\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\r\n }\r\n static async create(auth, persistenceHierarchy, userKey = \"authUser\" /* KeyName.AUTH_USER */) {\r\n if (!persistenceHierarchy.length) {\r\n return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey);\r\n }\r\n // Eliminate any persistences that are not available\r\n const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n if (await persistence._isAvailable()) {\r\n return persistence;\r\n }\r\n return undefined;\r\n }))).filter(persistence => persistence);\r\n // Fall back to the first persistence listed, or in memory if none available\r\n let selectedPersistence = availablePersistences[0] ||\r\n _getInstance(inMemoryPersistence);\r\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\r\n // Pull out the existing user, setting the chosen persistence to that\r\n // persistence if the user exists.\r\n let userToMigrate = null;\r\n // Note, here we check for a user in _all_ persistences, not just the\r\n // ones deemed available. If we can migrate a user out of a broken\r\n // persistence, we will (but only if that persistence supports migration).\r\n for (const persistence of persistenceHierarchy) {\r\n try {\r\n const blob = await persistence._get(key);\r\n if (blob) {\r\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\r\n if (persistence !== selectedPersistence) {\r\n userToMigrate = user;\r\n }\r\n selectedPersistence = persistence;\r\n break;\r\n }\r\n }\r\n catch (_a) { }\r\n }\r\n // If we find the user in a persistence that does support migration, use\r\n // that migration path (of only persistences that support migration)\r\n const migrationHierarchy = availablePersistences.filter(p => p._shouldAllowMigration);\r\n // If the persistence does _not_ allow migration, just finish off here\r\n if (!selectedPersistence._shouldAllowMigration ||\r\n !migrationHierarchy.length) {\r\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n }\r\n selectedPersistence = migrationHierarchy[0];\r\n if (userToMigrate) {\r\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\r\n // we'll just let it bubble to surface the error.\r\n await selectedPersistence._set(key, userToMigrate.toJSON());\r\n }\r\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\r\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\r\n await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n if (persistence !== selectedPersistence) {\r\n try {\r\n await persistence._remove(key);\r\n }\r\n catch (_a) { }\r\n }\r\n }));\r\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine the browser for the purposes of reporting usage to the API\r\n */\r\nfunction _getBrowserName(userAgent) {\r\n const ua = userAgent.toLowerCase();\r\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\r\n return \"Opera\" /* BrowserName.OPERA */;\r\n }\r\n else if (_isIEMobile(ua)) {\r\n // Windows phone IEMobile browser.\r\n return \"IEMobile\" /* BrowserName.IEMOBILE */;\r\n }\r\n else if (ua.includes('msie') || ua.includes('trident/')) {\r\n return \"IE\" /* BrowserName.IE */;\r\n }\r\n else if (ua.includes('edge/')) {\r\n return \"Edge\" /* BrowserName.EDGE */;\r\n }\r\n else if (_isFirefox(ua)) {\r\n return \"Firefox\" /* BrowserName.FIREFOX */;\r\n }\r\n else if (ua.includes('silk/')) {\r\n return \"Silk\" /* BrowserName.SILK */;\r\n }\r\n else if (_isBlackBerry(ua)) {\r\n // Blackberry browser.\r\n return \"Blackberry\" /* BrowserName.BLACKBERRY */;\r\n }\r\n else if (_isWebOS(ua)) {\r\n // WebOS default browser.\r\n return \"Webos\" /* BrowserName.WEBOS */;\r\n }\r\n else if (_isSafari(ua)) {\r\n return \"Safari\" /* BrowserName.SAFARI */;\r\n }\r\n else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&\r\n !ua.includes('edge/')) {\r\n return \"Chrome\" /* BrowserName.CHROME */;\r\n }\r\n else if (_isAndroid(ua)) {\r\n // Android stock browser.\r\n return \"Android\" /* BrowserName.ANDROID */;\r\n }\r\n else {\r\n // Most modern browsers have name/version at end of user agent string.\r\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\r\n const matches = userAgent.match(re);\r\n if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {\r\n return matches[1];\r\n }\r\n }\r\n return \"Other\" /* BrowserName.OTHER */;\r\n}\r\nfunction _isFirefox(ua = getUA()) {\r\n return /firefox\\//i.test(ua);\r\n}\r\nfunction _isSafari(userAgent = getUA()) {\r\n const ua = userAgent.toLowerCase();\r\n return (ua.includes('safari/') &&\r\n !ua.includes('chrome/') &&\r\n !ua.includes('crios/') &&\r\n !ua.includes('android'));\r\n}\r\nfunction _isChromeIOS(ua = getUA()) {\r\n return /crios\\//i.test(ua);\r\n}\r\nfunction _isIEMobile(ua = getUA()) {\r\n return /iemobile/i.test(ua);\r\n}\r\nfunction _isAndroid(ua = getUA()) {\r\n return /android/i.test(ua);\r\n}\r\nfunction _isBlackBerry(ua = getUA()) {\r\n return /blackberry/i.test(ua);\r\n}\r\nfunction _isWebOS(ua = getUA()) {\r\n return /webos/i.test(ua);\r\n}\r\nfunction _isIOS(ua = getUA()) {\r\n return (/iphone|ipad|ipod/i.test(ua) ||\r\n (/macintosh/i.test(ua) && /mobile/i.test(ua)));\r\n}\r\nfunction _isIOS7Or8(ua = getUA()) {\r\n return (/(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\r\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua));\r\n}\r\nfunction _isIOSStandalone(ua = getUA()) {\r\n var _a;\r\n return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);\r\n}\r\nfunction _isIE10() {\r\n return isIE() && document.documentMode === 10;\r\n}\r\nfunction _isMobileBrowser(ua = getUA()) {\r\n // TODO: implement getBrowserName equivalent for OS.\r\n return (_isIOS(ua) ||\r\n _isAndroid(ua) ||\r\n _isWebOS(ua) ||\r\n _isBlackBerry(ua) ||\r\n /windows phone/i.test(ua) ||\r\n _isIEMobile(ua));\r\n}\r\nfunction _isIframe() {\r\n try {\r\n // Check that the current window is not the top window.\r\n // If so, return true.\r\n return !!(window && window !== window.top);\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/*\r\n * Determine the SDK version string\r\n */\r\nfunction _getClientVersion(clientPlatform, frameworks = []) {\r\n let reportedPlatform;\r\n switch (clientPlatform) {\r\n case \"Browser\" /* ClientPlatform.BROWSER */:\r\n // In a browser environment, report the browser name.\r\n reportedPlatform = _getBrowserName(getUA());\r\n break;\r\n case \"Worker\" /* ClientPlatform.WORKER */:\r\n // Technically a worker runs from a browser but we need to differentiate a\r\n // worker from a browser.\r\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\r\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\r\n break;\r\n default:\r\n reportedPlatform = clientPlatform;\r\n }\r\n const reportedFrameworks = frameworks.length\r\n ? frameworks.join(',')\r\n : 'FirebaseCore-web'; /* default value if no other framework is used */\r\n return `${reportedPlatform}/${\"JsCore\" /* ClientImplementation.CORE */}/${SDK_VERSION}/${reportedFrameworks}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthMiddlewareQueue {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.queue = [];\r\n }\r\n pushCallback(callback, onAbort) {\r\n // The callback could be sync or async. Wrap it into a\r\n // function that is always async.\r\n const wrappedCallback = (user) => new Promise((resolve, reject) => {\r\n try {\r\n const result = callback(user);\r\n // Either resolve with existing promise or wrap a non-promise\r\n // return value into a promise.\r\n resolve(result);\r\n }\r\n catch (e) {\r\n // Sync callback throws.\r\n reject(e);\r\n }\r\n });\r\n // Attach the onAbort if present\r\n wrappedCallback.onAbort = onAbort;\r\n this.queue.push(wrappedCallback);\r\n const index = this.queue.length - 1;\r\n return () => {\r\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\r\n // indexing of other elements.\r\n this.queue[index] = () => Promise.resolve();\r\n };\r\n }\r\n async runMiddleware(nextUser) {\r\n if (this.auth.currentUser === nextUser) {\r\n return;\r\n }\r\n // While running the middleware, build a temporary stack of onAbort\r\n // callbacks to call if one middleware callback rejects.\r\n const onAbortStack = [];\r\n try {\r\n for (const beforeStateCallback of this.queue) {\r\n await beforeStateCallback(nextUser);\r\n // Only push the onAbort if the callback succeeds\r\n if (beforeStateCallback.onAbort) {\r\n onAbortStack.push(beforeStateCallback.onAbort);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // Run all onAbort, with separate try/catch to ignore any errors and\r\n // continue\r\n onAbortStack.reverse();\r\n for (const onAbort of onAbortStack) {\r\n try {\r\n onAbort();\r\n }\r\n catch (_) {\r\n /* swallow error */\r\n }\r\n }\r\n throw this.auth._errorFactory.create(\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */, {\r\n originalMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2023 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Fetches the password policy for the currently set tenant or the project if no tenant is set.\r\n *\r\n * @param auth Auth object.\r\n * @param request Password policy request.\r\n * @returns Password policy response.\r\n */\r\nasync function _getPasswordPolicy(auth, request = {}) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v2/passwordPolicy\" /* Endpoint.GET_PASSWORD_POLICY */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2023 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Minimum min password length enforced by the backend, even if no minimum length is set.\r\nconst MINIMUM_MIN_PASSWORD_LENGTH = 6;\r\n/**\r\n * Stores password policy requirements and provides password validation against the policy.\r\n *\r\n * @internal\r\n */\r\nclass PasswordPolicyImpl {\r\n constructor(response) {\r\n var _a, _b, _c, _d;\r\n // Only include custom strength options defined in the response.\r\n const responseOptions = response.customStrengthOptions;\r\n this.customStrengthOptions = {};\r\n // TODO: Remove once the backend is updated to include the minimum min password length instead of undefined when there is no minimum length set.\r\n this.customStrengthOptions.minPasswordLength =\r\n (_a = responseOptions.minPasswordLength) !== null && _a !== void 0 ? _a : MINIMUM_MIN_PASSWORD_LENGTH;\r\n if (responseOptions.maxPasswordLength) {\r\n this.customStrengthOptions.maxPasswordLength =\r\n responseOptions.maxPasswordLength;\r\n }\r\n if (responseOptions.containsLowercaseCharacter !== undefined) {\r\n this.customStrengthOptions.containsLowercaseLetter =\r\n responseOptions.containsLowercaseCharacter;\r\n }\r\n if (responseOptions.containsUppercaseCharacter !== undefined) {\r\n this.customStrengthOptions.containsUppercaseLetter =\r\n responseOptions.containsUppercaseCharacter;\r\n }\r\n if (responseOptions.containsNumericCharacter !== undefined) {\r\n this.customStrengthOptions.containsNumericCharacter =\r\n responseOptions.containsNumericCharacter;\r\n }\r\n if (responseOptions.containsNonAlphanumericCharacter !== undefined) {\r\n this.customStrengthOptions.containsNonAlphanumericCharacter =\r\n responseOptions.containsNonAlphanumericCharacter;\r\n }\r\n this.enforcementState = response.enforcementState;\r\n if (this.enforcementState === 'ENFORCEMENT_STATE_UNSPECIFIED') {\r\n this.enforcementState = 'OFF';\r\n }\r\n // Use an empty string if no non-alphanumeric characters are specified in the response.\r\n this.allowedNonAlphanumericCharacters =\r\n (_c = (_b = response.allowedNonAlphanumericCharacters) === null || _b === void 0 ? void 0 : _b.join('')) !== null && _c !== void 0 ? _c : '';\r\n this.forceUpgradeOnSignin = (_d = response.forceUpgradeOnSignin) !== null && _d !== void 0 ? _d : false;\r\n this.schemaVersion = response.schemaVersion;\r\n }\r\n validatePassword(password) {\r\n var _a, _b, _c, _d, _e, _f;\r\n const status = {\r\n isValid: true,\r\n passwordPolicy: this\r\n };\r\n // Check the password length and character options.\r\n this.validatePasswordLengthOptions(password, status);\r\n this.validatePasswordCharacterOptions(password, status);\r\n // Combine the status into single isValid property.\r\n status.isValid && (status.isValid = (_a = status.meetsMinPasswordLength) !== null && _a !== void 0 ? _a : true);\r\n status.isValid && (status.isValid = (_b = status.meetsMaxPasswordLength) !== null && _b !== void 0 ? _b : true);\r\n status.isValid && (status.isValid = (_c = status.containsLowercaseLetter) !== null && _c !== void 0 ? _c : true);\r\n status.isValid && (status.isValid = (_d = status.containsUppercaseLetter) !== null && _d !== void 0 ? _d : true);\r\n status.isValid && (status.isValid = (_e = status.containsNumericCharacter) !== null && _e !== void 0 ? _e : true);\r\n status.isValid && (status.isValid = (_f = status.containsNonAlphanumericCharacter) !== null && _f !== void 0 ? _f : true);\r\n return status;\r\n }\r\n /**\r\n * Validates that the password meets the length options for the policy.\r\n *\r\n * @param password Password to validate.\r\n * @param status Validation status.\r\n */\r\n validatePasswordLengthOptions(password, status) {\r\n const minPasswordLength = this.customStrengthOptions.minPasswordLength;\r\n const maxPasswordLength = this.customStrengthOptions.maxPasswordLength;\r\n if (minPasswordLength) {\r\n status.meetsMinPasswordLength = password.length >= minPasswordLength;\r\n }\r\n if (maxPasswordLength) {\r\n status.meetsMaxPasswordLength = password.length <= maxPasswordLength;\r\n }\r\n }\r\n /**\r\n * Validates that the password meets the character options for the policy.\r\n *\r\n * @param password Password to validate.\r\n * @param status Validation status.\r\n */\r\n validatePasswordCharacterOptions(password, status) {\r\n // Assign statuses for requirements even if the password is an empty string.\r\n this.updatePasswordCharacterOptionsStatuses(status, \r\n /* containsLowercaseCharacter= */ false, \r\n /* containsUppercaseCharacter= */ false, \r\n /* containsNumericCharacter= */ false, \r\n /* containsNonAlphanumericCharacter= */ false);\r\n let passwordChar;\r\n for (let i = 0; i < password.length; i++) {\r\n passwordChar = password.charAt(i);\r\n this.updatePasswordCharacterOptionsStatuses(status, \r\n /* containsLowercaseCharacter= */ passwordChar >= 'a' &&\r\n passwordChar <= 'z', \r\n /* containsUppercaseCharacter= */ passwordChar >= 'A' &&\r\n passwordChar <= 'Z', \r\n /* containsNumericCharacter= */ passwordChar >= '0' &&\r\n passwordChar <= '9', \r\n /* containsNonAlphanumericCharacter= */ this.allowedNonAlphanumericCharacters.includes(passwordChar));\r\n }\r\n }\r\n /**\r\n * Updates the running validation status with the statuses for the character options.\r\n * Expected to be called each time a character is processed to update each option status\r\n * based on the current character.\r\n *\r\n * @param status Validation status.\r\n * @param containsLowercaseCharacter Whether the character is a lowercase letter.\r\n * @param containsUppercaseCharacter Whether the character is an uppercase letter.\r\n * @param containsNumericCharacter Whether the character is a numeric character.\r\n * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character.\r\n */\r\n updatePasswordCharacterOptionsStatuses(status, containsLowercaseCharacter, containsUppercaseCharacter, containsNumericCharacter, containsNonAlphanumericCharacter) {\r\n if (this.customStrengthOptions.containsLowercaseLetter) {\r\n status.containsLowercaseLetter || (status.containsLowercaseLetter = containsLowercaseCharacter);\r\n }\r\n if (this.customStrengthOptions.containsUppercaseLetter) {\r\n status.containsUppercaseLetter || (status.containsUppercaseLetter = containsUppercaseCharacter);\r\n }\r\n if (this.customStrengthOptions.containsNumericCharacter) {\r\n status.containsNumericCharacter || (status.containsNumericCharacter = containsNumericCharacter);\r\n }\r\n if (this.customStrengthOptions.containsNonAlphanumericCharacter) {\r\n status.containsNonAlphanumericCharacter || (status.containsNonAlphanumericCharacter = containsNonAlphanumericCharacter);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthImpl {\r\n constructor(app, heartbeatServiceProvider, appCheckServiceProvider, config) {\r\n this.app = app;\r\n this.heartbeatServiceProvider = heartbeatServiceProvider;\r\n this.appCheckServiceProvider = appCheckServiceProvider;\r\n this.config = config;\r\n this.currentUser = null;\r\n this.emulatorConfig = null;\r\n this.operations = Promise.resolve();\r\n this.authStateSubscription = new Subscription(this);\r\n this.idTokenSubscription = new Subscription(this);\r\n this.beforeStateQueue = new AuthMiddlewareQueue(this);\r\n this.redirectUser = null;\r\n this.isProactiveRefreshEnabled = false;\r\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION = 1;\r\n // Any network calls will set this to true and prevent subsequent emulator\r\n // initialization\r\n this._canInitEmulator = true;\r\n this._isInitialized = false;\r\n this._deleted = false;\r\n this._initializationPromise = null;\r\n this._popupRedirectResolver = null;\r\n this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;\r\n this._agentRecaptchaConfig = null;\r\n this._tenantRecaptchaConfigs = {};\r\n this._projectPasswordPolicy = null;\r\n this._tenantPasswordPolicies = {};\r\n // Tracks the last notified UID for state change listeners to prevent\r\n // repeated calls to the callbacks. Undefined means it's never been\r\n // called, whereas null means it's been called with a signed out user\r\n this.lastNotifiedUid = undefined;\r\n this.languageCode = null;\r\n this.tenantId = null;\r\n this.settings = { appVerificationDisabledForTesting: false };\r\n this.frameworks = [];\r\n this.name = app.name;\r\n this.clientVersion = config.sdkClientVersion;\r\n }\r\n _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) {\r\n if (popupRedirectResolver) {\r\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\r\n }\r\n // Have to check for app deletion throughout initialization (after each\r\n // promise resolution)\r\n this._initializationPromise = this.queue(async () => {\r\n var _a, _b;\r\n if (this._deleted) {\r\n return;\r\n }\r\n this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy);\r\n if (this._deleted) {\r\n return;\r\n }\r\n // Initialize the resolver early if necessary (only applicable to web:\r\n // this will cause the iframe to load immediately in certain cases)\r\n if ((_a = this._popupRedirectResolver) === null || _a === void 0 ? void 0 : _a._shouldInitProactively) {\r\n // If this fails, don't halt auth loading\r\n try {\r\n await this._popupRedirectResolver._initialize(this);\r\n }\r\n catch (e) {\r\n /* Ignore the error */\r\n }\r\n }\r\n await this.initializeCurrentUser(popupRedirectResolver);\r\n this.lastNotifiedUid = ((_b = this.currentUser) === null || _b === void 0 ? void 0 : _b.uid) || null;\r\n if (this._deleted) {\r\n return;\r\n }\r\n this._isInitialized = true;\r\n });\r\n return this._initializationPromise;\r\n }\r\n /**\r\n * If the persistence is changed in another window, the user manager will let us know\r\n */\r\n async _onStorageEvent() {\r\n if (this._deleted) {\r\n return;\r\n }\r\n const user = await this.assertedPersistence.getCurrentUser();\r\n if (!this.currentUser && !user) {\r\n // No change, do nothing (was signed out and remained signed out).\r\n return;\r\n }\r\n // If the same user is to be synchronized.\r\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\r\n // Data update, simply copy data changes.\r\n this._currentUser._assign(user);\r\n // If tokens changed from previous user tokens, this will trigger\r\n // notifyAuthListeners_.\r\n await this.currentUser.getIdToken();\r\n return;\r\n }\r\n // Update current Auth state. Either a new login or logout.\r\n // Skip blocking callbacks, they should not apply to a change in another tab.\r\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\r\n }\r\n async initializeCurrentUserFromIdToken(idToken) {\r\n try {\r\n const response = await getAccountInfo(this, { idToken });\r\n const user = await UserImpl._fromGetAccountInfoResponse(this, response, idToken);\r\n await this.directlySetCurrentUser(user);\r\n }\r\n catch (err) {\r\n console.warn('FirebaseServerApp could not login user with provided authIdToken: ', err);\r\n await this.directlySetCurrentUser(null);\r\n }\r\n }\r\n async initializeCurrentUser(popupRedirectResolver) {\r\n var _a;\r\n if (_isFirebaseServerApp(this.app)) {\r\n const idToken = this.app.settings.authIdToken;\r\n if (idToken) {\r\n // Start the auth operation in the next tick to allow a moment for the customer's app to\r\n // attach an emulator, if desired.\r\n return new Promise(resolve => {\r\n setTimeout(() => this.initializeCurrentUserFromIdToken(idToken).then(resolve, resolve));\r\n });\r\n }\r\n else {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n // First check to see if we have a pending redirect event.\r\n const previouslyStoredUser = (await this.assertedPersistence.getCurrentUser());\r\n let futureCurrentUser = previouslyStoredUser;\r\n let needsTocheckMiddleware = false;\r\n if (popupRedirectResolver && this.config.authDomain) {\r\n await this.getOrInitRedirectPersistenceManager();\r\n const redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;\r\n const storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;\r\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\r\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\r\n // matches the redirect user, then we want to initially sign in with the\r\n // new user object from result.\r\n // TODO(samgho): More thoroughly test all of this\r\n if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\r\n (result === null || result === void 0 ? void 0 : result.user)) {\r\n futureCurrentUser = result.user;\r\n needsTocheckMiddleware = true;\r\n }\r\n }\r\n // If no user in persistence, there is no current user. Set to null.\r\n if (!futureCurrentUser) {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n if (!futureCurrentUser._redirectEventId) {\r\n // This isn't a redirect link operation, we can reload and bail.\r\n // First though, ensure that we check the middleware is happy.\r\n if (needsTocheckMiddleware) {\r\n try {\r\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\r\n }\r\n catch (e) {\r\n futureCurrentUser = previouslyStoredUser;\r\n // We know this is available since the bit is only set when the\r\n // resolver is available\r\n this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(e));\r\n }\r\n }\r\n if (futureCurrentUser) {\r\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\r\n }\r\n else {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n _assert(this._popupRedirectResolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n await this.getOrInitRedirectPersistenceManager();\r\n // If the redirect user's event ID matches the current user's event ID,\r\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\r\n // This is important for the reauthenticateWithRedirect() flow.\r\n if (this.redirectUser &&\r\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {\r\n return this.directlySetCurrentUser(futureCurrentUser);\r\n }\r\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\r\n }\r\n async tryRedirectSignIn(redirectResolver) {\r\n // The redirect user needs to be checked (and signed in if available)\r\n // during auth initialization. All of the normal sign in and link/reauth\r\n // flows call back into auth and push things onto the promise queue. We\r\n // need to await the result of the redirect sign in *inside the promise\r\n // queue*. This presents a problem: we run into deadlock. See:\r\n // ┌> [Initialization] ─────┐\r\n // ┌> [] │\r\n // └─ [getRedirectResult] <─┘\r\n // where [] are tasks on the queue and arrows denote awaits\r\n // Initialization will never complete because it's waiting on something\r\n // that's waiting for initialization to complete!\r\n //\r\n // Instead, this method calls getRedirectResult() (stored in\r\n // _completeRedirectFn) with an optional parameter that instructs all of\r\n // the underlying auth operations to skip anything that mutates auth state.\r\n let result = null;\r\n try {\r\n // We know this._popupRedirectResolver is set since redirectResolver\r\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\r\n result = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true);\r\n }\r\n catch (e) {\r\n // Swallow any errors here; the code can retrieve them in\r\n // getRedirectResult().\r\n await this._setRedirectUser(null);\r\n }\r\n return result;\r\n }\r\n async reloadAndSetCurrentUserOrClear(user) {\r\n try {\r\n await _reloadWithoutSaving(user);\r\n }\r\n catch (e) {\r\n if ((e === null || e === void 0 ? void 0 : e.code) !==\r\n `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {\r\n // Something's wrong with the user's token. Log them out and remove\r\n // them from storage\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n return this.directlySetCurrentUser(user);\r\n }\r\n useDeviceLanguage() {\r\n this.languageCode = _getUserLanguage();\r\n }\r\n async _delete() {\r\n this._deleted = true;\r\n }\r\n async updateCurrentUser(userExtern) {\r\n if (_isFirebaseServerApp(this.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\r\n }\r\n // The public updateCurrentUser method needs to make a copy of the user,\r\n // and also check that the project matches\r\n const user = userExtern\r\n ? getModularInstance(userExtern)\r\n : null;\r\n if (user) {\r\n _assert(user.auth.config.apiKey === this.config.apiKey, this, \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */);\r\n }\r\n return this._updateCurrentUser(user && user._clone(this));\r\n }\r\n async _updateCurrentUser(user, skipBeforeStateCallbacks = false) {\r\n if (this._deleted) {\r\n return;\r\n }\r\n if (user) {\r\n _assert(this.tenantId === user.tenantId, this, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\r\n }\r\n if (!skipBeforeStateCallbacks) {\r\n await this.beforeStateQueue.runMiddleware(user);\r\n }\r\n return this.queue(async () => {\r\n await this.directlySetCurrentUser(user);\r\n this.notifyAuthListeners();\r\n });\r\n }\r\n async signOut() {\r\n if (_isFirebaseServerApp(this.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\r\n }\r\n // Run first, to block _setRedirectUser() if any callbacks fail.\r\n await this.beforeStateQueue.runMiddleware(null);\r\n // Clear the redirect user when signOut is called\r\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\r\n await this._setRedirectUser(null);\r\n }\r\n // Prevent callbacks from being called again in _updateCurrentUser, as\r\n // they were already called in the first line.\r\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\r\n }\r\n setPersistence(persistence) {\r\n if (_isFirebaseServerApp(this.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\r\n }\r\n return this.queue(async () => {\r\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\r\n });\r\n }\r\n _getRecaptchaConfig() {\r\n if (this.tenantId == null) {\r\n return this._agentRecaptchaConfig;\r\n }\r\n else {\r\n return this._tenantRecaptchaConfigs[this.tenantId];\r\n }\r\n }\r\n async validatePassword(password) {\r\n if (!this._getPasswordPolicyInternal()) {\r\n await this._updatePasswordPolicy();\r\n }\r\n // Password policy will be defined after fetching.\r\n const passwordPolicy = this._getPasswordPolicyInternal();\r\n // Check that the policy schema version is supported by the SDK.\r\n // TODO: Update this logic to use a max supported policy schema version once we have multiple schema versions.\r\n if (passwordPolicy.schemaVersion !==\r\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION) {\r\n return Promise.reject(this._errorFactory.create(\"unsupported-password-policy-schema-version\" /* AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION */, {}));\r\n }\r\n return passwordPolicy.validatePassword(password);\r\n }\r\n _getPasswordPolicyInternal() {\r\n if (this.tenantId === null) {\r\n return this._projectPasswordPolicy;\r\n }\r\n else {\r\n return this._tenantPasswordPolicies[this.tenantId];\r\n }\r\n }\r\n async _updatePasswordPolicy() {\r\n const response = await _getPasswordPolicy(this);\r\n const passwordPolicy = new PasswordPolicyImpl(response);\r\n if (this.tenantId === null) {\r\n this._projectPasswordPolicy = passwordPolicy;\r\n }\r\n else {\r\n this._tenantPasswordPolicies[this.tenantId] = passwordPolicy;\r\n }\r\n }\r\n _getPersistence() {\r\n return this.assertedPersistence.persistence.type;\r\n }\r\n _updateErrorMap(errorMap) {\r\n this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());\r\n }\r\n onAuthStateChanged(nextOrObserver, error, completed) {\r\n return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);\r\n }\r\n beforeAuthStateChanged(callback, onAbort) {\r\n return this.beforeStateQueue.pushCallback(callback, onAbort);\r\n }\r\n onIdTokenChanged(nextOrObserver, error, completed) {\r\n return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);\r\n }\r\n authStateReady() {\r\n return new Promise((resolve, reject) => {\r\n if (this.currentUser) {\r\n resolve();\r\n }\r\n else {\r\n const unsubscribe = this.onAuthStateChanged(() => {\r\n unsubscribe();\r\n resolve();\r\n }, reject);\r\n }\r\n });\r\n }\r\n /**\r\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\r\n */\r\n async revokeAccessToken(token) {\r\n if (this.currentUser) {\r\n const idToken = await this.currentUser.getIdToken();\r\n // Generalize this to accept other providers once supported.\r\n const request = {\r\n providerId: 'apple.com',\r\n tokenType: \"ACCESS_TOKEN\" /* TokenType.ACCESS_TOKEN */,\r\n token,\r\n idToken\r\n };\r\n if (this.tenantId != null) {\r\n request.tenantId = this.tenantId;\r\n }\r\n await revokeToken(this, request);\r\n }\r\n }\r\n toJSON() {\r\n var _a;\r\n return {\r\n apiKey: this.config.apiKey,\r\n authDomain: this.config.authDomain,\r\n appName: this.name,\r\n currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()\r\n };\r\n }\r\n async _setRedirectUser(user, popupRedirectResolver) {\r\n const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver);\r\n return user === null\r\n ? redirectManager.removeCurrentUser()\r\n : redirectManager.setCurrentUser(user);\r\n }\r\n async getOrInitRedirectPersistenceManager(popupRedirectResolver) {\r\n if (!this.redirectPersistenceManager) {\r\n const resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\r\n this._popupRedirectResolver;\r\n _assert(resolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.redirectPersistenceManager = await PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], \"redirectUser\" /* KeyName.REDIRECT_USER */);\r\n this.redirectUser =\r\n await this.redirectPersistenceManager.getCurrentUser();\r\n }\r\n return this.redirectPersistenceManager;\r\n }\r\n async _redirectUserForId(id) {\r\n var _a, _b;\r\n // Make sure we've cleared any pending persistence actions if we're not in\r\n // the initializer\r\n if (this._isInitialized) {\r\n await this.queue(async () => { });\r\n }\r\n if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {\r\n return this._currentUser;\r\n }\r\n if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {\r\n return this.redirectUser;\r\n }\r\n return null;\r\n }\r\n async _persistUserIfCurrent(user) {\r\n if (user === this.currentUser) {\r\n return this.queue(async () => this.directlySetCurrentUser(user));\r\n }\r\n }\r\n /** Notifies listeners only if the user is current */\r\n _notifyListenersIfCurrent(user) {\r\n if (user === this.currentUser) {\r\n this.notifyAuthListeners();\r\n }\r\n }\r\n _key() {\r\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\r\n }\r\n _startProactiveRefresh() {\r\n this.isProactiveRefreshEnabled = true;\r\n if (this.currentUser) {\r\n this._currentUser._startProactiveRefresh();\r\n }\r\n }\r\n _stopProactiveRefresh() {\r\n this.isProactiveRefreshEnabled = false;\r\n if (this.currentUser) {\r\n this._currentUser._stopProactiveRefresh();\r\n }\r\n }\r\n /** Returns the current user cast as the internal type */\r\n get _currentUser() {\r\n return this.currentUser;\r\n }\r\n notifyAuthListeners() {\r\n var _a, _b;\r\n if (!this._isInitialized) {\r\n return;\r\n }\r\n this.idTokenSubscription.next(this.currentUser);\r\n const currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;\r\n if (this.lastNotifiedUid !== currentUid) {\r\n this.lastNotifiedUid = currentUid;\r\n this.authStateSubscription.next(this.currentUser);\r\n }\r\n }\r\n registerStateListener(subscription, nextOrObserver, error, completed) {\r\n if (this._deleted) {\r\n return () => { };\r\n }\r\n const cb = typeof nextOrObserver === 'function'\r\n ? nextOrObserver\r\n : nextOrObserver.next.bind(nextOrObserver);\r\n let isUnsubscribed = false;\r\n const promise = this._isInitialized\r\n ? Promise.resolve()\r\n : this._initializationPromise;\r\n _assert(promise, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n // The callback needs to be called asynchronously per the spec.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n promise.then(() => {\r\n if (isUnsubscribed) {\r\n return;\r\n }\r\n cb(this.currentUser);\r\n });\r\n if (typeof nextOrObserver === 'function') {\r\n const unsubscribe = subscription.addObserver(nextOrObserver, error, completed);\r\n return () => {\r\n isUnsubscribed = true;\r\n unsubscribe();\r\n };\r\n }\r\n else {\r\n const unsubscribe = subscription.addObserver(nextOrObserver);\r\n return () => {\r\n isUnsubscribed = true;\r\n unsubscribe();\r\n };\r\n }\r\n }\r\n /**\r\n * Unprotected (from race conditions) method to set the current user. This\r\n * should only be called from within a queued callback. This is necessary\r\n * because the queue shouldn't rely on another queued callback.\r\n */\r\n async directlySetCurrentUser(user) {\r\n if (this.currentUser && this.currentUser !== user) {\r\n this._currentUser._stopProactiveRefresh();\r\n }\r\n if (user && this.isProactiveRefreshEnabled) {\r\n user._startProactiveRefresh();\r\n }\r\n this.currentUser = user;\r\n if (user) {\r\n await this.assertedPersistence.setCurrentUser(user);\r\n }\r\n else {\r\n await this.assertedPersistence.removeCurrentUser();\r\n }\r\n }\r\n queue(action) {\r\n // In case something errors, the callback still should be called in order\r\n // to keep the promise chain alive\r\n this.operations = this.operations.then(action, action);\r\n return this.operations;\r\n }\r\n get assertedPersistence() {\r\n _assert(this.persistenceManager, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.persistenceManager;\r\n }\r\n _logFramework(framework) {\r\n if (!framework || this.frameworks.includes(framework)) {\r\n return;\r\n }\r\n this.frameworks.push(framework);\r\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\r\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\r\n this.frameworks.sort();\r\n this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());\r\n }\r\n _getFrameworks() {\r\n return this.frameworks;\r\n }\r\n async _getAdditionalHeaders() {\r\n var _a;\r\n // Additional headers on every request\r\n const headers = {\r\n [\"X-Client-Version\" /* HttpHeader.X_CLIENT_VERSION */]: this.clientVersion\r\n };\r\n if (this.app.options.appId) {\r\n headers[\"X-Firebase-gmpid\" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;\r\n }\r\n // If the heartbeat service exists, add the heartbeat string\r\n const heartbeatsHeader = await ((_a = this.heartbeatServiceProvider\r\n .getImmediate({\r\n optional: true\r\n })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader());\r\n if (heartbeatsHeader) {\r\n headers[\"X-Firebase-Client\" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;\r\n }\r\n // If the App Check service exists, add the App Check token in the headers\r\n const appCheckToken = await this._getAppCheckToken();\r\n if (appCheckToken) {\r\n headers[\"X-Firebase-AppCheck\" /* HttpHeader.X_FIREBASE_APP_CHECK */] = appCheckToken;\r\n }\r\n return headers;\r\n }\r\n async _getAppCheckToken() {\r\n var _a;\r\n const appCheckTokenResult = await ((_a = this.appCheckServiceProvider\r\n .getImmediate({ optional: true })) === null || _a === void 0 ? void 0 : _a.getToken());\r\n if (appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.error) {\r\n // Context: appCheck.getToken() will never throw even if an error happened.\r\n // In the error case, a dummy token will be returned along with an error field describing\r\n // the error. In general, we shouldn't care about the error condition and just use\r\n // the token (actual or dummy) to send requests.\r\n _logWarn(`Error while retrieving App Check token: ${appCheckTokenResult.error}`);\r\n }\r\n return appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.token;\r\n }\r\n}\r\n/**\r\n * Method to be used to cast down to our private implmentation of Auth.\r\n * It will also handle unwrapping from the compat type if necessary\r\n *\r\n * @param auth Auth object passed in from developer\r\n */\r\nfunction _castAuth(auth) {\r\n return getModularInstance(auth);\r\n}\r\n/** Helper class to wrap subscriber logic */\r\nclass Subscription {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.observer = null;\r\n this.addObserver = createSubscribe(observer => (this.observer = observer));\r\n }\r\n get next() {\r\n _assert(this.observer, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.observer.next.bind(this.observer);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet externalJSProvider = {\r\n async loadJS() {\r\n throw new Error('Unable to load external scripts');\r\n },\r\n recaptchaV2Script: '',\r\n recaptchaEnterpriseScript: '',\r\n gapiScript: ''\r\n};\r\nfunction _setExternalJSProvider(p) {\r\n externalJSProvider = p;\r\n}\r\nfunction _loadJS(url) {\r\n return externalJSProvider.loadJS(url);\r\n}\r\nfunction _recaptchaV2ScriptUrl() {\r\n return externalJSProvider.recaptchaV2Script;\r\n}\r\nfunction _recaptchaEnterpriseScriptUrl() {\r\n return externalJSProvider.recaptchaEnterpriseScript;\r\n}\r\nfunction _gapiScriptUrl() {\r\n return externalJSProvider.gapiScript;\r\n}\r\nfunction _generateCallbackName(prefix) {\r\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\r\n}\n\n/* eslint-disable @typescript-eslint/no-require-imports */\r\nconst RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';\r\nconst FAKE_TOKEN = 'NO_RECAPTCHA';\r\nclass RecaptchaEnterpriseVerifier {\r\n /**\r\n *\r\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\r\n *\r\n */\r\n constructor(authExtern) {\r\n /**\r\n * Identifies the type of application verifier (e.g. \"recaptcha-enterprise\").\r\n */\r\n this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;\r\n this.auth = _castAuth(authExtern);\r\n }\r\n /**\r\n * Executes the verification process.\r\n *\r\n * @returns A Promise for a token that can be used to assert the validity of a request.\r\n */\r\n async verify(action = 'verify', forceRefresh = false) {\r\n async function retrieveSiteKey(auth) {\r\n if (!forceRefresh) {\r\n if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {\r\n return auth._agentRecaptchaConfig.siteKey;\r\n }\r\n if (auth.tenantId != null &&\r\n auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined) {\r\n return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;\r\n }\r\n }\r\n return new Promise(async (resolve, reject) => {\r\n getRecaptchaConfig(auth, {\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\r\n version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n })\r\n .then(response => {\r\n if (response.recaptchaKey === undefined) {\r\n reject(new Error('recaptcha Enterprise site key undefined'));\r\n }\r\n else {\r\n const config = new RecaptchaConfig(response);\r\n if (auth.tenantId == null) {\r\n auth._agentRecaptchaConfig = config;\r\n }\r\n else {\r\n auth._tenantRecaptchaConfigs[auth.tenantId] = config;\r\n }\r\n return resolve(config.siteKey);\r\n }\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n });\r\n }\r\n function retrieveRecaptchaToken(siteKey, resolve, reject) {\r\n const grecaptcha = window.grecaptcha;\r\n if (isEnterprise(grecaptcha)) {\r\n grecaptcha.enterprise.ready(() => {\r\n grecaptcha.enterprise\r\n .execute(siteKey, { action })\r\n .then(token => {\r\n resolve(token);\r\n })\r\n .catch(() => {\r\n resolve(FAKE_TOKEN);\r\n });\r\n });\r\n }\r\n else {\r\n reject(Error('No reCAPTCHA enterprise script loaded.'));\r\n }\r\n }\r\n return new Promise((resolve, reject) => {\r\n retrieveSiteKey(this.auth)\r\n .then(siteKey => {\r\n if (!forceRefresh && isEnterprise(window.grecaptcha)) {\r\n retrieveRecaptchaToken(siteKey, resolve, reject);\r\n }\r\n else {\r\n if (typeof window === 'undefined') {\r\n reject(new Error('RecaptchaVerifier is only supported in browser'));\r\n return;\r\n }\r\n let url = _recaptchaEnterpriseScriptUrl();\r\n if (url.length !== 0) {\r\n url += siteKey;\r\n }\r\n _loadJS(url)\r\n .then(() => {\r\n retrieveRecaptchaToken(siteKey, resolve, reject);\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n }\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n });\r\n }\r\n}\r\nasync function injectRecaptchaFields(auth, request, action, captchaResp = false) {\r\n const verifier = new RecaptchaEnterpriseVerifier(auth);\r\n let captchaResponse;\r\n try {\r\n captchaResponse = await verifier.verify(action);\r\n }\r\n catch (error) {\r\n captchaResponse = await verifier.verify(action, true);\r\n }\r\n const newRequest = Object.assign({}, request);\r\n if (!captchaResp) {\r\n Object.assign(newRequest, { captchaResponse });\r\n }\r\n else {\r\n Object.assign(newRequest, { 'captchaResp': captchaResponse });\r\n }\r\n Object.assign(newRequest, { 'clientType': \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */ });\r\n Object.assign(newRequest, {\r\n 'recaptchaVersion': \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n });\r\n return newRequest;\r\n}\r\nasync function handleRecaptchaFlow(authInstance, request, actionName, actionMethod) {\r\n var _a;\r\n if ((_a = authInstance\r\n ._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.isProviderEnabled(\"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaProvider.EMAIL_PASSWORD_PROVIDER */)) {\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInstance, request, actionName, actionName === \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */);\r\n return actionMethod(authInstance, requestWithRecaptcha);\r\n }\r\n else {\r\n return actionMethod(authInstance, request).catch(async (error) => {\r\n if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {\r\n console.log(`${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInstance, request, actionName, actionName === \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */);\r\n return actionMethod(authInstance, requestWithRecaptcha);\r\n }\r\n else {\r\n return Promise.reject(error);\r\n }\r\n });\r\n }\r\n}\r\nasync function _initializeRecaptchaConfig(auth) {\r\n const authInternal = _castAuth(auth);\r\n const response = await getRecaptchaConfig(authInternal, {\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\r\n version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n });\r\n const config = new RecaptchaConfig(response);\r\n if (authInternal.tenantId == null) {\r\n authInternal._agentRecaptchaConfig = config;\r\n }\r\n else {\r\n authInternal._tenantRecaptchaConfigs[authInternal.tenantId] = config;\r\n }\r\n if (config.isProviderEnabled(\"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaProvider.EMAIL_PASSWORD_PROVIDER */)) {\r\n const verifier = new RecaptchaEnterpriseVerifier(authInternal);\r\n void verifier.verify();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Initializes an {@link Auth} instance with fine-grained control over\r\n * {@link Dependencies}.\r\n *\r\n * @remarks\r\n *\r\n * This function allows more control over the {@link Auth} instance than\r\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\r\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\r\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\r\n * need control over which persistence layer is used, or to minimize bundle\r\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\r\n *\r\n * For example, if your app only uses anonymous accounts and you only want\r\n * accounts saved for the current session, initialize `Auth` with:\r\n *\r\n * ```js\r\n * const auth = initializeAuth(app, {\r\n * persistence: browserSessionPersistence,\r\n * popupRedirectResolver: undefined,\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nfunction initializeAuth(app, deps) {\r\n const provider = _getProvider(app, 'auth');\r\n if (provider.isInitialized()) {\r\n const auth = provider.getImmediate();\r\n const initialOptions = provider.getOptions();\r\n if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {\r\n return auth;\r\n }\r\n else {\r\n _fail(auth, \"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */);\r\n }\r\n }\r\n const auth = provider.initialize({ options: deps });\r\n return auth;\r\n}\r\nfunction _initializeAuthInstance(auth, deps) {\r\n const persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];\r\n const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);\r\n if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {\r\n auth._updateErrorMap(deps.errorMap);\r\n }\r\n // This promise is intended to float; auth initialization happens in the\r\n // background, meanwhile the auth object may be used by the app.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);\r\n}\n\n/**\r\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\r\n * Firebase Auth services.\r\n *\r\n * @remarks\r\n * This must be called synchronously immediately following the first call to\r\n * {@link initializeAuth}. Do not use with production credentials as emulator\r\n * traffic is not encrypted.\r\n *\r\n *\r\n * @example\r\n * ```javascript\r\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\r\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\r\n * `true` to disable the warning banner attached to the DOM.\r\n *\r\n * @public\r\n */\r\nfunction connectAuthEmulator(auth, url, options) {\r\n const authInternal = _castAuth(auth);\r\n _assert(authInternal._canInitEmulator, authInternal, \"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);\r\n _assert(/^https?:\\/\\//.test(url), authInternal, \"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);\r\n const disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);\r\n const protocol = extractProtocol(url);\r\n const { host, port } = extractHostAndPort(url);\r\n const portStr = port === null ? '' : `:${port}`;\r\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\r\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\r\n authInternal.settings.appVerificationDisabledForTesting = true;\r\n authInternal.emulatorConfig = Object.freeze({\r\n host,\r\n port,\r\n protocol: protocol.replace(':', ''),\r\n options: Object.freeze({ disableWarnings })\r\n });\r\n if (!disableWarnings) {\r\n emitEmulatorWarning();\r\n }\r\n}\r\nfunction extractProtocol(url) {\r\n const protocolEnd = url.indexOf(':');\r\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\r\n}\r\nfunction extractHostAndPort(url) {\r\n const protocol = extractProtocol(url);\r\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\r\n if (!authority) {\r\n return { host: '', port: null };\r\n }\r\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\r\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\r\n if (bracketedIPv6) {\r\n const host = bracketedIPv6[1];\r\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\r\n }\r\n else {\r\n const [host, port] = hostAndPort.split(':');\r\n return { host, port: parsePort(port) };\r\n }\r\n}\r\nfunction parsePort(portStr) {\r\n if (!portStr) {\r\n return null;\r\n }\r\n const port = Number(portStr);\r\n if (isNaN(port)) {\r\n return null;\r\n }\r\n return port;\r\n}\r\nfunction emitEmulatorWarning() {\r\n function attachBanner() {\r\n const el = document.createElement('p');\r\n const sty = el.style;\r\n el.innerText =\r\n 'Running in emulator mode. Do not use with production credentials.';\r\n sty.position = 'fixed';\r\n sty.width = '100%';\r\n sty.backgroundColor = '#ffffff';\r\n sty.border = '.1em solid #000000';\r\n sty.color = '#b50000';\r\n sty.bottom = '0px';\r\n sty.left = '0px';\r\n sty.margin = '0px';\r\n sty.zIndex = '10000';\r\n sty.textAlign = 'center';\r\n el.classList.add('firebase-emulator-warning');\r\n document.body.appendChild(el);\r\n }\r\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\r\n console.info('WARNING: You are using the Auth Emulator,' +\r\n ' which is intended for local testing only. Do not use with' +\r\n ' production credentials.');\r\n }\r\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\r\n if (document.readyState === 'loading') {\r\n window.addEventListener('DOMContentLoaded', attachBanner);\r\n }\r\n else {\r\n attachBanner();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by an {@link AuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass AuthCredential {\r\n /** @internal */\r\n constructor(\r\n /**\r\n * The authentication provider ID for the credential.\r\n *\r\n * @remarks\r\n * For example, 'facebook.com', or 'google.com'.\r\n */\r\n providerId, \r\n /**\r\n * The authentication sign in method for the credential.\r\n *\r\n * @remarks\r\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\r\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\r\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\r\n */\r\n signInMethod) {\r\n this.providerId = providerId;\r\n this.signInMethod = signInMethod;\r\n }\r\n /**\r\n * Returns a JSON-serializable representation of this object.\r\n *\r\n * @returns a JSON-serializable representation of this object.\r\n */\r\n toJSON() {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(_auth) {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _linkToIdToken(_auth, _idToken) {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(_auth) {\r\n return debugFail('not implemented');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function resetPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:resetPassword\" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function updateEmailPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\r\n// Used for linking an email/password account to an existing idToken. Uses the same request/response\r\n// format as updateEmailPassword.\r\nasync function linkEmailPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signUp\" /* Endpoint.SIGN_UP */, request);\r\n}\r\nasync function applyActionCode$1(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithPassword(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPassword\" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendOobCode(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendOobCode\" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendEmailVerification$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function sendPasswordResetEmail$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function sendSignInLinkToEmail$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function verifyAndChangeEmail(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithEmailLink$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithEmailLinkForLinking(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\r\n * {@link ProviderId}.PASSWORD\r\n *\r\n * @remarks\r\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthCredential extends AuthCredential {\r\n /** @internal */\r\n constructor(\r\n /** @internal */\r\n _email, \r\n /** @internal */\r\n _password, signInMethod, \r\n /** @internal */\r\n _tenantId = null) {\r\n super(\"password\" /* ProviderId.PASSWORD */, signInMethod);\r\n this._email = _email;\r\n this._password = _password;\r\n this._tenantId = _tenantId;\r\n }\r\n /** @internal */\r\n static _fromEmailAndPassword(email, password) {\r\n return new EmailAuthCredential(email, password, \"password\" /* SignInMethod.EMAIL_PASSWORD */);\r\n }\r\n /** @internal */\r\n static _fromEmailAndCode(email, oobCode, tenantId = null) {\r\n return new EmailAuthCredential(email, oobCode, \"emailLink\" /* SignInMethod.EMAIL_LINK */, tenantId);\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n email: this._email,\r\n password: this._password,\r\n signInMethod: this.signInMethod,\r\n tenantId: this._tenantId\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\r\n *\r\n * @param json - Either `object` or the stringified representation of the object. When string is\r\n * provided, `JSON.parse` would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {\r\n if (obj.signInMethod === \"password\" /* SignInMethod.EMAIL_PASSWORD */) {\r\n return this._fromEmailAndPassword(obj.email, obj.password);\r\n }\r\n else if (obj.signInMethod === \"emailLink\" /* SignInMethod.EMAIL_LINK */) {\r\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\r\n }\r\n }\r\n return null;\r\n }\r\n /** @internal */\r\n async _getIdTokenResponse(auth) {\r\n switch (this.signInMethod) {\r\n case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\r\n const request = {\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n return handleRecaptchaFlow(auth, request, \"signInWithPassword\" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */, signInWithPassword);\r\n case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\r\n return signInWithEmailLink$1(auth, {\r\n email: this._email,\r\n oobCode: this._password\r\n });\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n /** @internal */\r\n async _linkToIdToken(auth, idToken) {\r\n switch (this.signInMethod) {\r\n case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\r\n const request = {\r\n idToken,\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n return handleRecaptchaFlow(auth, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */, linkEmailPassword);\r\n case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\r\n return signInWithEmailLinkForLinking(auth, {\r\n idToken,\r\n email: this._email,\r\n oobCode: this._password\r\n });\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n return this._getIdTokenResponse(auth);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithIdp(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithIdp\" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI$1 = 'http://localhost';\r\n/**\r\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass OAuthCredential extends AuthCredential {\r\n constructor() {\r\n super(...arguments);\r\n this.pendingToken = null;\r\n }\r\n /** @internal */\r\n static _fromParams(params) {\r\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\r\n if (params.idToken || params.accessToken) {\r\n // OAuth 2 and either ID token or access token.\r\n if (params.idToken) {\r\n cred.idToken = params.idToken;\r\n }\r\n if (params.accessToken) {\r\n cred.accessToken = params.accessToken;\r\n }\r\n // Add nonce if available and no pendingToken is present.\r\n if (params.nonce && !params.pendingToken) {\r\n cred.nonce = params.nonce;\r\n }\r\n if (params.pendingToken) {\r\n cred.pendingToken = params.pendingToken;\r\n }\r\n }\r\n else if (params.oauthToken && params.oauthTokenSecret) {\r\n // OAuth 1 and OAuth token with token secret\r\n cred.accessToken = params.oauthToken;\r\n cred.secret = params.oauthTokenSecret;\r\n }\r\n else {\r\n _fail(\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n }\r\n return cred;\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n idToken: this.idToken,\r\n accessToken: this.accessToken,\r\n secret: this.secret,\r\n nonce: this.nonce,\r\n pendingToken: this.pendingToken,\r\n providerId: this.providerId,\r\n signInMethod: this.signInMethod\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an\r\n * {@link AuthCredential}.\r\n *\r\n * @param json - Input can be either Object or the stringified representation of the object.\r\n * When string is provided, JSON.parse would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n const { providerId, signInMethod } = obj, rest = __rest(obj, [\"providerId\", \"signInMethod\"]);\r\n if (!providerId || !signInMethod) {\r\n return null;\r\n }\r\n const cred = new OAuthCredential(providerId, signInMethod);\r\n cred.idToken = rest.idToken || undefined;\r\n cred.accessToken = rest.accessToken || undefined;\r\n cred.secret = rest.secret;\r\n cred.nonce = rest.nonce;\r\n cred.pendingToken = rest.pendingToken || null;\r\n return cred;\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n const request = this.buildRequest();\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n const request = this.buildRequest();\r\n request.idToken = idToken;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n const request = this.buildRequest();\r\n request.autoCreate = false;\r\n return signInWithIdp(auth, request);\r\n }\r\n buildRequest() {\r\n const request = {\r\n requestUri: IDP_REQUEST_URI$1,\r\n returnSecureToken: true\r\n };\r\n if (this.pendingToken) {\r\n request.pendingToken = this.pendingToken;\r\n }\r\n else {\r\n const postBody = {};\r\n if (this.idToken) {\r\n postBody['id_token'] = this.idToken;\r\n }\r\n if (this.accessToken) {\r\n postBody['access_token'] = this.accessToken;\r\n }\r\n if (this.secret) {\r\n postBody['oauth_token_secret'] = this.secret;\r\n }\r\n postBody['providerId'] = this.providerId;\r\n if (this.nonce && !this.pendingToken) {\r\n postBody['nonce'] = this.nonce;\r\n }\r\n request.postBody = querystring(postBody);\r\n }\r\n return request;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function sendPhoneVerificationCode(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendVerificationCode\" /* Endpoint.SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithPhoneNumber$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function linkWithPhoneNumber$1(auth, request) {\r\n const response = await _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n if (response.temporaryProof) {\r\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, response);\r\n }\r\n return response;\r\n}\r\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = {\r\n [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */\r\n};\r\nasync function verifyPhoneNumberForExisting(auth, request) {\r\n const apiRequest = Object.assign(Object.assign({}, request), { operation: 'REAUTH' });\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Represents the credentials returned by {@link PhoneAuthProvider}.\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthCredential extends AuthCredential {\r\n constructor(params) {\r\n super(\"phone\" /* ProviderId.PHONE */, \"phone\" /* SignInMethod.PHONE */);\r\n this.params = params;\r\n }\r\n /** @internal */\r\n static _fromVerification(verificationId, verificationCode) {\r\n return new PhoneAuthCredential({ verificationId, verificationCode });\r\n }\r\n /** @internal */\r\n static _fromTokenResponse(phoneNumber, temporaryProof) {\r\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n return linkWithPhoneNumber$1(auth, Object.assign({ idToken }, this._makeVerificationRequest()));\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\r\n }\r\n /** @internal */\r\n _makeVerificationRequest() {\r\n const { temporaryProof, phoneNumber, verificationId, verificationCode } = this.params;\r\n if (temporaryProof && phoneNumber) {\r\n return { temporaryProof, phoneNumber };\r\n }\r\n return {\r\n sessionInfo: verificationId,\r\n code: verificationCode\r\n };\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n const obj = {\r\n providerId: this.providerId\r\n };\r\n if (this.params.phoneNumber) {\r\n obj.phoneNumber = this.params.phoneNumber;\r\n }\r\n if (this.params.temporaryProof) {\r\n obj.temporaryProof = this.params.temporaryProof;\r\n }\r\n if (this.params.verificationCode) {\r\n obj.verificationCode = this.params.verificationCode;\r\n }\r\n if (this.params.verificationId) {\r\n obj.verificationId = this.params.verificationId;\r\n }\r\n return obj;\r\n }\r\n /** Generates a phone credential based on a plain object or a JSON string. */\r\n static fromJSON(json) {\r\n if (typeof json === 'string') {\r\n json = JSON.parse(json);\r\n }\r\n const { verificationId, verificationCode, phoneNumber, temporaryProof } = json;\r\n if (!verificationCode &&\r\n !verificationId &&\r\n !phoneNumber &&\r\n !temporaryProof) {\r\n return null;\r\n }\r\n return new PhoneAuthCredential({\r\n verificationId,\r\n verificationCode,\r\n phoneNumber,\r\n temporaryProof\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Maps the mode string in action code URL to Action Code Info operation.\r\n *\r\n * @param mode\r\n */\r\nfunction parseMode(mode) {\r\n switch (mode) {\r\n case 'recoverEmail':\r\n return \"RECOVER_EMAIL\" /* ActionCodeOperation.RECOVER_EMAIL */;\r\n case 'resetPassword':\r\n return \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */;\r\n case 'signIn':\r\n return \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\r\n case 'verifyEmail':\r\n return \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */;\r\n case 'verifyAndChangeEmail':\r\n return \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;\r\n case 'revertSecondFactorAddition':\r\n return \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;\r\n default:\r\n return null;\r\n }\r\n}\r\n/**\r\n * Helper to parse FDL links\r\n *\r\n * @param url\r\n */\r\nfunction parseDeepLink(url) {\r\n const link = querystringDecode(extractQuerystring(url))['link'];\r\n // Double link case (automatic redirect).\r\n const doubleDeepLink = link\r\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\r\n : null;\r\n // iOS custom scheme links.\r\n const iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];\r\n const iOSDoubleDeepLink = iOSDeepLink\r\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\r\n : null;\r\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\r\n}\r\n/**\r\n * A utility class to parse email action URLs such as password reset, email verification,\r\n * email link sign in, etc.\r\n *\r\n * @public\r\n */\r\nclass ActionCodeURL {\r\n /**\r\n * @param actionLink - The link from which to extract the URL.\r\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n *\r\n * @internal\r\n */\r\n constructor(actionLink) {\r\n var _a, _b, _c, _d, _e, _f;\r\n const searchParams = querystringDecode(extractQuerystring(actionLink));\r\n const apiKey = (_a = searchParams[\"apiKey\" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;\r\n const code = (_b = searchParams[\"oobCode\" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;\r\n const operation = parseMode((_c = searchParams[\"mode\" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);\r\n // Validate API key, code and mode.\r\n _assert(apiKey && code && operation, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.apiKey = apiKey;\r\n this.operation = operation;\r\n this.code = code;\r\n this.continueUrl = (_d = searchParams[\"continueUrl\" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;\r\n this.languageCode = (_e = searchParams[\"languageCode\" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;\r\n this.tenantId = (_f = searchParams[\"tenantId\" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;\r\n }\r\n /**\r\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\r\n * otherwise returns null.\r\n *\r\n * @param link - The email action link string.\r\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n *\r\n * @public\r\n */\r\n static parseLink(link) {\r\n const actionLink = parseDeepLink(link);\r\n try {\r\n return new ActionCodeURL(actionLink);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/**\r\n * Parses the email action link string and returns an {@link ActionCodeURL} if\r\n * the link is valid, otherwise returns null.\r\n *\r\n * @public\r\n */\r\nfunction parseActionCodeURL(link) {\r\n return ActionCodeURL.parseLink(link);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating {@link EmailAuthCredential}.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthProvider {\r\n constructor() {\r\n /**\r\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n */\r\n this.providerId = EmailAuthProvider.PROVIDER_ID;\r\n }\r\n /**\r\n * Initialize an {@link AuthCredential} using an email and password.\r\n *\r\n * @example\r\n * ```javascript\r\n * const authCredential = EmailAuthProvider.credential(email, password);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\r\n * ```\r\n *\r\n * @param email - Email address.\r\n * @param password - User account password.\r\n * @returns The auth provider credential.\r\n */\r\n static credential(email, password) {\r\n return EmailAuthCredential._fromEmailAndPassword(email, password);\r\n }\r\n /**\r\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\r\n * email link operation.\r\n *\r\n * @example\r\n * ```javascript\r\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * await sendSignInLinkToEmail(auth, email);\r\n * // Obtain emailLink from user.\r\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance used to verify the link.\r\n * @param email - Email address.\r\n * @param emailLink - Sign-in email link.\r\n * @returns - The auth provider credential.\r\n */\r\n static credentialWithLink(email, emailLink) {\r\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n _assert(actionCodeUrl, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);\r\n }\r\n}\r\n/**\r\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n */\r\nEmailAuthProvider.PROVIDER_ID = \"password\" /* ProviderId.PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\r\n */\r\nEmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = \"password\" /* SignInMethod.EMAIL_PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_LINK.\r\n */\r\nEmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = \"emailLink\" /* SignInMethod.EMAIL_LINK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\r\n *\r\n * This class is not meant to be instantiated directly.\r\n *\r\n * @public\r\n */\r\nclass FederatedAuthProvider {\r\n /**\r\n * Constructor for generic OAuth providers.\r\n *\r\n * @param providerId - Provider for which credentials should be generated.\r\n */\r\n constructor(providerId) {\r\n this.providerId = providerId;\r\n /** @internal */\r\n this.defaultLanguageCode = null;\r\n /** @internal */\r\n this.customParameters = {};\r\n }\r\n /**\r\n * Set the language gode.\r\n *\r\n * @param languageCode - language code\r\n */\r\n setDefaultLanguage(languageCode) {\r\n this.defaultLanguageCode = languageCode;\r\n }\r\n /**\r\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\r\n * operations.\r\n *\r\n * @remarks\r\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\r\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\r\n *\r\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\r\n */\r\n setCustomParameters(customOAuthParameters) {\r\n this.customParameters = customOAuthParameters;\r\n return this;\r\n }\r\n /**\r\n * Retrieve the current list of {@link CustomParameters}.\r\n */\r\n getCustomParameters() {\r\n return this.customParameters;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Common code to all OAuth providers. This is separate from the\r\n * {@link OAuthProvider} so that child providers (like\r\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\r\n * Instead, they rely on a static `credential` method.\r\n */\r\nclass BaseOAuthProvider extends FederatedAuthProvider {\r\n constructor() {\r\n super(...arguments);\r\n /** @internal */\r\n this.scopes = [];\r\n }\r\n /**\r\n * Add an OAuth scope to the credential.\r\n *\r\n * @param scope - Provider OAuth scope to add.\r\n */\r\n addScope(scope) {\r\n // If not already added, add scope to list.\r\n if (!this.scopes.includes(scope)) {\r\n this.scopes.push(scope);\r\n }\r\n return this;\r\n }\r\n /**\r\n * Retrieve the current list of OAuth scopes.\r\n */\r\n getScopes() {\r\n return [...this.scopes];\r\n }\r\n}\r\n/**\r\n * Provider for generating generic {@link OAuthCredential}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new OAuthProvider('google.com');\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a OAuth Access Token for the provider.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new OAuthProvider('google.com');\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a OAuth Access Token for the provider.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass OAuthProvider extends BaseOAuthProvider {\r\n /**\r\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\r\n * @param json - A plain object or a JSON string\r\n */\r\n static credentialFromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n _assert('providerId' in obj && 'signInMethod' in obj, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return OAuthCredential._fromParams(obj);\r\n }\r\n /**\r\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\r\n *\r\n * @remarks\r\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\r\n * the raw nonce must match the nonce field in the ID token.\r\n *\r\n * @example\r\n * ```javascript\r\n * // `googleUser` from the onsuccess Google Sign In callback.\r\n * // Initialize a generate OAuth provider with a `google.com` providerId.\r\n * const provider = new OAuthProvider('google.com');\r\n * const credential = provider.credential({\r\n * idToken: googleUser.getAuthResponse().id_token,\r\n * });\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param params - Either the options object containing the ID token, access token and raw nonce\r\n * or the ID token string.\r\n */\r\n credential(params) {\r\n return this._credential(Object.assign(Object.assign({}, params), { nonce: params.rawNonce }));\r\n }\r\n /** An internal credential method that accepts more permissive options */\r\n _credential(params) {\r\n _assert(params.idToken || params.accessToken, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n // For OAuthCredential, sign in method is same as providerId.\r\n return OAuthCredential._fromParams(Object.assign(Object.assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));\r\n }\r\n static oauthCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce, providerId } = tokenResponse;\r\n if (!oauthAccessToken &&\r\n !oauthTokenSecret &&\r\n !oauthIdToken &&\r\n !pendingToken) {\r\n return null;\r\n }\r\n if (!providerId) {\r\n return null;\r\n }\r\n try {\r\n return new OAuthProvider(providerId)._credential({\r\n idToken: oauthIdToken,\r\n accessToken: oauthAccessToken,\r\n nonce,\r\n pendingToken\r\n });\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('user_birthday');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = FacebookAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * provider.addScope('user_birthday');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = FacebookAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass FacebookAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"facebook.com\" /* ProviderId.FACEBOOK */);\r\n }\r\n /**\r\n * Creates a credential for Facebook.\r\n *\r\n * @example\r\n * ```javascript\r\n * // `event` from the Facebook auth.authResponseChange callback.\r\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param accessToken - Facebook access token.\r\n */\r\n static credential(accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: FacebookAuthProvider.PROVIDER_ID,\r\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return FacebookAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n return null;\r\n }\r\n if (!tokenResponse.oauthAccessToken) {\r\n return null;\r\n }\r\n try {\r\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.FACEBOOK. */\r\nFacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = \"facebook.com\" /* SignInMethod.FACEBOOK */;\r\n/** Always set to {@link ProviderId}.FACEBOOK. */\r\nFacebookAuthProvider.PROVIDER_ID = \"facebook.com\" /* ProviderId.FACEBOOK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GoogleAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Google Access Token.\r\n * const credential = GoogleAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GoogleAuthProvider();\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Google Access Token.\r\n * const credential = GoogleAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass GoogleAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"google.com\" /* ProviderId.GOOGLE */);\r\n this.addScope('profile');\r\n }\r\n /**\r\n * Creates a credential for Google. At least one of ID token and access token is required.\r\n *\r\n * @example\r\n * ```javascript\r\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\r\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param idToken - Google ID token.\r\n * @param accessToken - Google access token.\r\n */\r\n static credential(idToken, accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: GoogleAuthProvider.PROVIDER_ID,\r\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\r\n idToken,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return GoogleAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthIdToken, oauthAccessToken } = tokenResponse;\r\n if (!oauthIdToken && !oauthAccessToken) {\r\n // This could be an oauth 1 credential or a phone credential\r\n return null;\r\n }\r\n try {\r\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.GOOGLE. */\r\nGoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = \"google.com\" /* SignInMethod.GOOGLE */;\r\n/** Always set to {@link ProviderId}.GOOGLE. */\r\nGoogleAuthProvider.PROVIDER_ID = \"google.com\" /* ProviderId.GOOGLE */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\r\n *\r\n * @remarks\r\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\r\n * the {@link signInWithPopup} handler:\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GithubAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('repo');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Github Access Token.\r\n * const credential = GithubAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GithubAuthProvider();\r\n * provider.addScope('repo');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Github Access Token.\r\n * const credential = GithubAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass GithubAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"github.com\" /* ProviderId.GITHUB */);\r\n }\r\n /**\r\n * Creates a credential for Github.\r\n *\r\n * @param accessToken - Github access token.\r\n */\r\n static credential(accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: GithubAuthProvider.PROVIDER_ID,\r\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return GithubAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n return null;\r\n }\r\n if (!tokenResponse.oauthAccessToken) {\r\n return null;\r\n }\r\n try {\r\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.GITHUB. */\r\nGithubAuthProvider.GITHUB_SIGN_IN_METHOD = \"github.com\" /* SignInMethod.GITHUB */;\r\n/** Always set to {@link ProviderId}.GITHUB. */\r\nGithubAuthProvider.PROVIDER_ID = \"github.com\" /* ProviderId.GITHUB */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI = 'http://localhost';\r\n/**\r\n * @public\r\n */\r\nclass SAMLAuthCredential extends AuthCredential {\r\n /** @internal */\r\n constructor(providerId, pendingToken) {\r\n super(providerId, providerId);\r\n this.pendingToken = pendingToken;\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n const request = this.buildRequest();\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n const request = this.buildRequest();\r\n request.idToken = idToken;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n const request = this.buildRequest();\r\n request.autoCreate = false;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n signInMethod: this.signInMethod,\r\n providerId: this.providerId,\r\n pendingToken: this.pendingToken\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an\r\n * {@link AuthCredential}.\r\n *\r\n * @param json - Input can be either Object or the stringified representation of the object.\r\n * When string is provided, JSON.parse would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n const { providerId, signInMethod, pendingToken } = obj;\r\n if (!providerId ||\r\n !signInMethod ||\r\n !pendingToken ||\r\n providerId !== signInMethod) {\r\n return null;\r\n }\r\n return new SAMLAuthCredential(providerId, pendingToken);\r\n }\r\n /**\r\n * Helper static method to avoid exposing the constructor to end users.\r\n *\r\n * @internal\r\n */\r\n static _create(providerId, pendingToken) {\r\n return new SAMLAuthCredential(providerId, pendingToken);\r\n }\r\n buildRequest() {\r\n return {\r\n requestUri: IDP_REQUEST_URI,\r\n returnSecureToken: true,\r\n pendingToken: this.pendingToken\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SAML_PROVIDER_PREFIX = 'saml.';\r\n/**\r\n * An {@link AuthProvider} for SAML.\r\n *\r\n * @public\r\n */\r\nclass SAMLAuthProvider extends FederatedAuthProvider {\r\n /**\r\n * Constructor. The providerId must start with \"saml.\"\r\n * @param providerId - SAML provider ID.\r\n */\r\n constructor(providerId) {\r\n _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n super(providerId);\r\n }\r\n /**\r\n * Generates an {@link AuthCredential} from a {@link UserCredential} after a\r\n * successful SAML flow completes.\r\n *\r\n * @remarks\r\n *\r\n * For example, to get an {@link AuthCredential}, you could write the\r\n * following code:\r\n *\r\n * ```js\r\n * const userCredential = await signInWithPopup(auth, samlProvider);\r\n * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\r\n * ```\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));\r\n }\r\n /**\r\n * Creates an {@link AuthCredential} from a JSON string or a plain object.\r\n * @param json - A plain object or a JSON string\r\n */\r\n static credentialFromJSON(json) {\r\n const credential = SAMLAuthCredential.fromJSON(json);\r\n _assert(credential, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return credential;\r\n }\r\n static samlCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { pendingToken, providerId } = tokenResponse;\r\n if (!pendingToken || !providerId) {\r\n return null;\r\n }\r\n try {\r\n return SAMLAuthCredential._create(providerId, pendingToken);\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new TwitterAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Twitter Access Token and Secret.\r\n * const credential = TwitterAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * const secret = credential.secret;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new TwitterAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Twitter Access Token and Secret.\r\n * const credential = TwitterAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * const secret = credential.secret;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass TwitterAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"twitter.com\" /* ProviderId.TWITTER */);\r\n }\r\n /**\r\n * Creates a credential for Twitter.\r\n *\r\n * @param token - Twitter access token.\r\n * @param secret - Twitter secret.\r\n */\r\n static credential(token, secret) {\r\n return OAuthCredential._fromParams({\r\n providerId: TwitterAuthProvider.PROVIDER_ID,\r\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\r\n oauthToken: token,\r\n oauthTokenSecret: secret\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return TwitterAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthAccessToken, oauthTokenSecret } = tokenResponse;\r\n if (!oauthAccessToken || !oauthTokenSecret) {\r\n return null;\r\n }\r\n try {\r\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.TWITTER. */\r\nTwitterAuthProvider.TWITTER_SIGN_IN_METHOD = \"twitter.com\" /* SignInMethod.TWITTER */;\r\n/** Always set to {@link ProviderId}.TWITTER. */\r\nTwitterAuthProvider.PROVIDER_ID = \"twitter.com\" /* ProviderId.TWITTER */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signUp(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signUp\" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserCredentialImpl {\r\n constructor(params) {\r\n this.user = params.user;\r\n this.providerId = params.providerId;\r\n this._tokenResponse = params._tokenResponse;\r\n this.operationType = params.operationType;\r\n }\r\n static async _fromIdTokenResponse(auth, operationType, idTokenResponse, isAnonymous = false) {\r\n const user = await UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous);\r\n const providerId = providerIdForResponse(idTokenResponse);\r\n const userCred = new UserCredentialImpl({\r\n user,\r\n providerId,\r\n _tokenResponse: idTokenResponse,\r\n operationType\r\n });\r\n return userCred;\r\n }\r\n static async _forOperation(user, operationType, response) {\r\n await user._updateTokensIfNecessary(response, /* reload */ true);\r\n const providerId = providerIdForResponse(response);\r\n return new UserCredentialImpl({\r\n user,\r\n providerId,\r\n _tokenResponse: response,\r\n operationType\r\n });\r\n }\r\n}\r\nfunction providerIdForResponse(response) {\r\n if (response.providerId) {\r\n return response.providerId;\r\n }\r\n if ('phoneNumber' in response) {\r\n return \"phone\" /* ProviderId.PHONE */;\r\n }\r\n return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in as an anonymous user.\r\n *\r\n * @remarks\r\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\r\n * new anonymous user identity will be created and returned.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nasync function signInAnonymously(auth) {\r\n var _a;\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n await authInternal._initializationPromise;\r\n if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {\r\n // If an anonymous user is already signed in, no need to sign them in again.\r\n return new UserCredentialImpl({\r\n user: authInternal.currentUser,\r\n providerId: null,\r\n operationType: \"signIn\" /* OperationType.SIGN_IN */\r\n });\r\n }\r\n const response = await signUp(authInternal, {\r\n returnSecureToken: true\r\n });\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response, true);\r\n await authInternal._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorError extends FirebaseError {\r\n constructor(auth, error, operationType, user) {\r\n var _a;\r\n super(error.code, error.message);\r\n this.operationType = operationType;\r\n this.user = user;\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, MultiFactorError.prototype);\r\n this.customData = {\r\n appName: auth.name,\r\n tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,\r\n _serverResponse: error.customData._serverResponse,\r\n operationType\r\n };\r\n }\r\n static _fromErrorAndOperation(auth, error, operationType, user) {\r\n return new MultiFactorError(auth, error, operationType, user);\r\n }\r\n}\r\nfunction _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {\r\n const idTokenProvider = operationType === \"reauthenticate\" /* OperationType.REAUTHENTICATE */\r\n ? credential._getReauthenticationResolver(auth)\r\n : credential._getIdTokenResponse(auth);\r\n return idTokenProvider.catch(error => {\r\n if (error.code === `auth/${\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */}`) {\r\n throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);\r\n }\r\n throw error;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Takes a set of UserInfo provider data and converts it to a set of names\r\n */\r\nfunction providerDataAsNames(providerData) {\r\n return new Set(providerData\r\n .map(({ providerId }) => providerId)\r\n .filter(pid => !!pid));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Unlinks a provider from a user account.\r\n *\r\n * @param user - The user.\r\n * @param providerId - The provider to unlink.\r\n *\r\n * @public\r\n */\r\nasync function unlink(user, providerId) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(true, userInternal, providerId);\r\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\r\n idToken: await userInternal.getIdToken(),\r\n deleteProvider: [providerId]\r\n });\r\n const providersLeft = providerDataAsNames(providerUserInfo || []);\r\n userInternal.providerData = userInternal.providerData.filter(pd => providersLeft.has(pd.providerId));\r\n if (!providersLeft.has(\"phone\" /* ProviderId.PHONE */)) {\r\n userInternal.phoneNumber = null;\r\n }\r\n await userInternal.auth._persistUserIfCurrent(userInternal);\r\n return userInternal;\r\n}\r\nasync function _link$1(user, credential, bypassAuthState = false) {\r\n const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState);\r\n return UserCredentialImpl._forOperation(user, \"link\" /* OperationType.LINK */, response);\r\n}\r\nasync function _assertLinkedStatus(expected, user, provider) {\r\n await _reloadWithoutSaving(user);\r\n const providerIds = providerDataAsNames(user.providerData);\r\n const code = expected === false\r\n ? \"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */\r\n : \"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */;\r\n _assert(providerIds.has(provider) === expected, user.auth, code);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reauthenticate(user, credential, bypassAuthState = false) {\r\n const { auth } = user;\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const operationType = \"reauthenticate\" /* OperationType.REAUTHENTICATE */;\r\n try {\r\n const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState);\r\n _assert(response.idToken, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const parsed = _parseToken(response.idToken);\r\n _assert(parsed, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const { sub: localId } = parsed;\r\n _assert(user.uid === localId, auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\r\n return UserCredentialImpl._forOperation(user, operationType, response);\r\n }\r\n catch (e) {\r\n // Convert user deleted error into user mismatch\r\n if ((e === null || e === void 0 ? void 0 : e.code) === `auth/${\"user-not-found\" /* AuthErrorCode.USER_DELETED */}`) {\r\n _fail(auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\r\n }\r\n throw e;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _signInWithCredential(auth, credential, bypassAuthState = false) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const operationType = \"signIn\" /* OperationType.SIGN_IN */;\r\n const response = await _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential);\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, operationType, response);\r\n if (!bypassAuthState) {\r\n await auth._updateCurrentUser(userCredential.user);\r\n }\r\n return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCredential(auth, credential) {\r\n return _signInWithCredential(_castAuth(auth), credential);\r\n}\r\n/**\r\n * Links the user account with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function linkWithCredential(user, credential) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(false, userInternal, credential.providerId);\r\n return _link$1(userInternal, credential);\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh credential.\r\n *\r\n * @remarks\r\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\r\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error\r\n * or a `TOKEN_EXPIRED` error.\r\n *\r\n * This method is not supported on any {@link User} signed in by {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithCredential(user, credential) {\r\n return _reauthenticate(getModularInstance(user), credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithCustomToken$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithCustomToken\" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in using a custom token.\r\n *\r\n * @remarks\r\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\r\n * be generated by an auth backend using the\r\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\r\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\r\n *\r\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param customToken - The custom token to sign in with.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCustomToken(auth, customToken) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n const response = await signInWithCustomToken$1(authInternal, {\r\n token: customToken,\r\n returnSecureToken: true\r\n });\r\n const cred = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\r\n await authInternal._updateCurrentUser(cred.user);\r\n return cred;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorInfoImpl {\r\n constructor(factorId, response) {\r\n this.factorId = factorId;\r\n this.uid = response.mfaEnrollmentId;\r\n this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\r\n this.displayName = response.displayName;\r\n }\r\n static _fromServerResponse(auth, enrollment) {\r\n if ('phoneInfo' in enrollment) {\r\n return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\r\n }\r\n else if ('totpInfo' in enrollment) {\r\n return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\r\n }\r\n return _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n}\r\nclass PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl {\r\n constructor(response) {\r\n super(\"phone\" /* FactorId.PHONE */, response);\r\n this.phoneNumber = response.phoneInfo;\r\n }\r\n static _fromServerResponse(_auth, enrollment) {\r\n return new PhoneMultiFactorInfoImpl(enrollment);\r\n }\r\n}\r\nclass TotpMultiFactorInfoImpl extends MultiFactorInfoImpl {\r\n constructor(response) {\r\n super(\"totp\" /* FactorId.TOTP */, response);\r\n }\r\n static _fromServerResponse(_auth, enrollment) {\r\n return new TotpMultiFactorInfoImpl(enrollment);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {\r\n var _a;\r\n _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, \"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */);\r\n _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\r\n actionCodeSettings.dynamicLinkDomain.length > 0, auth, \"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);\r\n request.continueUrl = actionCodeSettings.url;\r\n request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\r\n request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\r\n if (actionCodeSettings.iOS) {\r\n _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, \"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);\r\n request.iOSBundleId = actionCodeSettings.iOS.bundleId;\r\n }\r\n if (actionCodeSettings.android) {\r\n _assert(actionCodeSettings.android.packageName.length > 0, auth, \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);\r\n request.androidInstallApp = actionCodeSettings.android.installApp;\r\n request.androidMinimumVersionCode =\r\n actionCodeSettings.android.minimumVersion;\r\n request.androidPackageName = actionCodeSettings.android.packageName;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates the password policy cached in the {@link Auth} instance if a policy is already\r\n * cached for the project or tenant.\r\n *\r\n * @remarks\r\n * We only fetch the password policy if the password did not meet policy requirements and\r\n * there is an existing policy cached. A developer must call validatePassword at least\r\n * once for the cache to be automatically updated.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @private\r\n */\r\nasync function recachePasswordPolicy(auth) {\r\n const authInternal = _castAuth(auth);\r\n if (authInternal._getPasswordPolicyInternal()) {\r\n await authInternal._updatePasswordPolicy();\r\n }\r\n}\r\n/**\r\n * Sends a password reset email to the given email address. This method does not throw an error when\r\n * there's no user account with the given email address and\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled.\r\n *\r\n * @remarks\r\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\r\n * the email sent to the user, along with the new password specified by the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain code from user.\r\n * await confirmPasswordReset('user@example.com', code);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendPasswordResetEmail(auth, email, actionCodeSettings) {\r\n const authInternal = _castAuth(auth);\r\n const request = {\r\n requestType: \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */,\r\n email,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\r\n }\r\n await handleRecaptchaFlow(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, sendPasswordResetEmail$1);\r\n}\r\n/**\r\n * Completes the password reset process, given a confirmation code and new password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A confirmation code sent to the user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nasync function confirmPasswordReset(auth, oobCode, newPassword) {\r\n await resetPassword(getModularInstance(auth), {\r\n oobCode,\r\n newPassword\r\n })\r\n .catch(async (error) => {\r\n if (error.code ===\r\n `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\r\n void recachePasswordPolicy(auth);\r\n }\r\n throw error;\r\n });\r\n // Do not return the email.\r\n}\r\n/**\r\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function applyActionCode(auth, oobCode) {\r\n await applyActionCode$1(getModularInstance(auth), { oobCode });\r\n}\r\n/**\r\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns metadata about the code.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function checkActionCode(auth, oobCode) {\r\n const authModular = getModularInstance(auth);\r\n const response = await resetPassword(authModular, { oobCode });\r\n // Email could be empty only if the request type is EMAIL_SIGNIN or\r\n // VERIFY_AND_CHANGE_EMAIL.\r\n // New email should not be empty if the request type is\r\n // VERIFY_AND_CHANGE_EMAIL.\r\n // Multi-factor info could not be empty if the request type is\r\n // REVERT_SECOND_FACTOR_ADDITION.\r\n const operation = response.requestType;\r\n _assert(operation, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n switch (operation) {\r\n case \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */:\r\n break;\r\n case \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:\r\n _assert(response.newEmail, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n break;\r\n case \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:\r\n _assert(response.mfaInfo, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n // fall through\r\n default:\r\n _assert(response.email, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n // The multi-factor info for revert second factor addition\r\n let multiFactorInfo = null;\r\n if (response.mfaInfo) {\r\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);\r\n }\r\n return {\r\n data: {\r\n email: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\r\n ? response.newEmail\r\n : response.email) || null,\r\n previousEmail: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\r\n ? response.email\r\n : response.newEmail) || null,\r\n multiFactorInfo\r\n },\r\n operation\r\n };\r\n}\r\n/**\r\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns the user's email address if valid.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param code - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function verifyPasswordResetCode(auth, code) {\r\n const { data } = await checkActionCode(getModularInstance(auth), code);\r\n // Email should always be present since a code was sent to it\r\n return data.email;\r\n}\r\n/**\r\n * Creates a new user account associated with the specified email address and password.\r\n *\r\n * @remarks\r\n * On successful creation of the user account, this user will also be signed in to your application.\r\n *\r\n * User account creation can fail if the account already exists or the password is invalid.\r\n *\r\n * This method is not supported on {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * Note: The email address acts as a unique identifier for the user and enables an email-based\r\n * password reset. This function will create a new user account and set the initial user password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param password - The user's chosen password.\r\n *\r\n * @public\r\n */\r\nasync function createUserWithEmailAndPassword(auth, email, password) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n const request = {\r\n returnSecureToken: true,\r\n email,\r\n password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n const signUpResponse = handleRecaptchaFlow(authInternal, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */, signUp);\r\n const response = await signUpResponse.catch(error => {\r\n if (error.code === `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\r\n void recachePasswordPolicy(auth);\r\n }\r\n throw error;\r\n });\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\r\n await authInternal._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and password.\r\n *\r\n * @remarks\r\n * Fails with an error if the email address and password do not match. When\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled, this method fails with \"auth/invalid-credential\" in case of an invalid\r\n * email/password.\r\n *\r\n * This method is not supported on {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * Note: The user's password is NOT the password used to access the user's email account. The\r\n * email address serves as a unique identifier for the user, and the password is used to access\r\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\r\n *\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The users email address.\r\n * @param password - The users password.\r\n *\r\n * @public\r\n */\r\nfunction signInWithEmailAndPassword(auth, email, password) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password)).catch(async (error) => {\r\n if (error.code === `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\r\n void recachePasswordPolicy(auth);\r\n }\r\n throw error;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sends a sign-in email link to the user with the specified email.\r\n *\r\n * @remarks\r\n * The sign-in operation has to always be completed in the app unlike other out of band email\r\n * actions (password reset and email verifications). This is because, at the end of the flow,\r\n * the user is expected to be signed in and their Auth state persisted within the app.\r\n *\r\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\r\n * address and the email link supplied in the email sent to the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n * @param authInternal - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendSignInLinkToEmail(auth, email, actionCodeSettings) {\r\n const authInternal = _castAuth(auth);\r\n const request = {\r\n requestType: \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */,\r\n email,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n function setActionCodeSettings(request, actionCodeSettings) {\r\n _assert(actionCodeSettings.handleCodeInApp, authInternal, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\r\n }\r\n }\r\n setActionCodeSettings(request, actionCodeSettings);\r\n await handleRecaptchaFlow(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, sendSignInLinkToEmail$1);\r\n}\r\n/**\r\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nfunction isSignInWithEmailLink(auth, emailLink) {\r\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and sign-in email link.\r\n *\r\n * @remarks\r\n * If no link is passed, the link is inferred from the current URL.\r\n *\r\n * Fails with an error if the email address is invalid or OTP in email link expires.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nasync function signInWithEmailLink(auth, email, emailLink) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authModular = getModularInstance(auth);\r\n const credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());\r\n // Check if the tenant ID in the email link matches the tenant ID on Auth\r\n // instance.\r\n _assert(credential._tenantId === (authModular.tenantId || null), authModular, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\r\n return signInWithCredential(authModular, credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function createAuthUri(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:createAuthUri\" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Gets the list of possible sign in methods for the given email address. This method returns an\r\n * empty list when\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled, irrespective of the number of authentication methods available for the given email.\r\n *\r\n * @remarks\r\n * This is useful to differentiate methods of sign-in for the same provider, eg.\r\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\r\n * {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n *\r\n * Deprecated. Migrating off of this method is recommended as a security best-practice.\r\n * Learn more in the Identity Platform documentation for\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}.\r\n * @public\r\n */\r\nasync function fetchSignInMethodsForEmail(auth, email) {\r\n // createAuthUri returns an error if continue URI is not http or https.\r\n // For environments like Cordova, Chrome extensions, native frameworks, file\r\n // systems, etc, use http://localhost as continue URL.\r\n const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\r\n const request = {\r\n identifier: email,\r\n continueUri\r\n };\r\n const { signinMethods } = await createAuthUri(getModularInstance(auth), request);\r\n return signinMethods || [];\r\n}\r\n/**\r\n * Sends a verification email to a user.\r\n *\r\n * @remarks\r\n * The verification process is completed by calling {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendEmailVerification(user, actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendEmailVerification(user, actionCodeSettings) {\r\n const userInternal = getModularInstance(user);\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n requestType: \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */,\r\n idToken\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n }\r\n const { email } = await sendEmailVerification$1(userInternal.auth, request);\r\n if (email !== user.email) {\r\n await user.reload();\r\n }\r\n}\r\n/**\r\n * Sends a verification email to a new email address.\r\n *\r\n * @remarks\r\n * The user's email will be updated to the new one after being verified.\r\n *\r\n * If you have a custom email action handler, you can complete the verification process by calling\r\n * {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address to be verified before update.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {\r\n const userInternal = getModularInstance(user);\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n requestType: \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,\r\n idToken,\r\n newEmail\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n }\r\n const { email } = await verifyAndChangeEmail(userInternal.auth, request);\r\n if (email !== user.email) {\r\n // If the local copy of the email on user is outdated, reload the\r\n // user.\r\n await user.reload();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateProfile$1(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates a user's profile data.\r\n *\r\n * @param user - The user.\r\n * @param profile - The profile's `displayName` and `photoURL` to update.\r\n *\r\n * @public\r\n */\r\nasync function updateProfile(user, { displayName, photoURL: photoUrl }) {\r\n if (displayName === undefined && photoUrl === undefined) {\r\n return;\r\n }\r\n const userInternal = getModularInstance(user);\r\n const idToken = await userInternal.getIdToken();\r\n const profileRequest = {\r\n idToken,\r\n displayName,\r\n photoUrl,\r\n returnSecureToken: true\r\n };\r\n const response = await _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest));\r\n userInternal.displayName = response.displayName || null;\r\n userInternal.photoURL = response.photoUrl || null;\r\n // Update the password provider as well\r\n const passwordProvider = userInternal.providerData.find(({ providerId }) => providerId === \"password\" /* ProviderId.PASSWORD */);\r\n if (passwordProvider) {\r\n passwordProvider.displayName = userInternal.displayName;\r\n passwordProvider.photoURL = userInternal.photoURL;\r\n }\r\n await userInternal._updateTokensIfNecessary(response);\r\n}\r\n/**\r\n * Updates the user's email address.\r\n *\r\n * @remarks\r\n * An email will be sent to the original email address (if it was set) that allows to revoke the\r\n * email address change, in order to protect them from account hijacking.\r\n *\r\n * This method is not supported on any {@link User} signed in by {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address.\r\n *\r\n * Throws \"auth/operation-not-allowed\" error when\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled.\r\n * Deprecated - Use {@link verifyBeforeUpdateEmail} instead.\r\n *\r\n * @public\r\n */\r\nfunction updateEmail(user, newEmail) {\r\n const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n return updateEmailOrPassword(userInternal, newEmail, null);\r\n}\r\n/**\r\n * Updates the user's password.\r\n *\r\n * @remarks\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nfunction updatePassword(user, newPassword) {\r\n return updateEmailOrPassword(getModularInstance(user), null, newPassword);\r\n}\r\nasync function updateEmailOrPassword(user, email, password) {\r\n const { auth } = user;\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n idToken,\r\n returnSecureToken: true\r\n };\r\n if (email) {\r\n request.email = email;\r\n }\r\n if (password) {\r\n request.password = password;\r\n }\r\n const response = await _logoutIfInvalidated(user, updateEmailPassword(auth, request));\r\n await user._updateTokensIfNecessary(response, /* reload */ true);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Parse the `AdditionalUserInfo` from the ID token response.\r\n *\r\n */\r\nfunction _fromIdTokenResponse(idTokenResponse) {\r\n var _a, _b;\r\n if (!idTokenResponse) {\r\n return null;\r\n }\r\n const { providerId } = idTokenResponse;\r\n const profile = idTokenResponse.rawUserInfo\r\n ? JSON.parse(idTokenResponse.rawUserInfo)\r\n : {};\r\n const isNewUser = idTokenResponse.isNewUser ||\r\n idTokenResponse.kind === \"identitytoolkit#SignupNewUserResponse\" /* IdTokenResponseKind.SignupNewUser */;\r\n if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {\r\n const signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];\r\n if (signInProvider) {\r\n const filteredProviderId = signInProvider !== \"anonymous\" /* ProviderId.ANONYMOUS */ &&\r\n signInProvider !== \"custom\" /* ProviderId.CUSTOM */\r\n ? signInProvider\r\n : null;\r\n // Uses generic class in accordance with the legacy SDK.\r\n return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\r\n }\r\n }\r\n if (!providerId) {\r\n return null;\r\n }\r\n switch (providerId) {\r\n case \"facebook.com\" /* ProviderId.FACEBOOK */:\r\n return new FacebookAdditionalUserInfo(isNewUser, profile);\r\n case \"github.com\" /* ProviderId.GITHUB */:\r\n return new GithubAdditionalUserInfo(isNewUser, profile);\r\n case \"google.com\" /* ProviderId.GOOGLE */:\r\n return new GoogleAdditionalUserInfo(isNewUser, profile);\r\n case \"twitter.com\" /* ProviderId.TWITTER */:\r\n return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);\r\n case \"custom\" /* ProviderId.CUSTOM */:\r\n case \"anonymous\" /* ProviderId.ANONYMOUS */:\r\n return new GenericAdditionalUserInfo(isNewUser, null);\r\n default:\r\n return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\r\n }\r\n}\r\nclass GenericAdditionalUserInfo {\r\n constructor(isNewUser, providerId, profile = {}) {\r\n this.isNewUser = isNewUser;\r\n this.providerId = providerId;\r\n this.profile = profile;\r\n }\r\n}\r\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, providerId, profile, username) {\r\n super(isNewUser, providerId, profile);\r\n this.username = username;\r\n }\r\n}\r\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"facebook.com\" /* ProviderId.FACEBOOK */, profile);\r\n }\r\n}\r\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"github.com\" /* ProviderId.GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null);\r\n }\r\n}\r\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"google.com\" /* ProviderId.GOOGLE */, profile);\r\n }\r\n}\r\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n constructor(isNewUser, profile, screenName) {\r\n super(isNewUser, \"twitter.com\" /* ProviderId.TWITTER */, profile, screenName);\r\n }\r\n}\r\n/**\r\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\r\n *\r\n * @param userCredential - The user credential.\r\n *\r\n * @public\r\n */\r\nfunction getAdditionalUserInfo(userCredential) {\r\n const { user, _tokenResponse } = userCredential;\r\n if (user.isAnonymous && !_tokenResponse) {\r\n // Handle the special case where signInAnonymously() gets called twice.\r\n // No network call is made so there's nothing to actually fill this in\r\n return {\r\n providerId: null,\r\n isNewUser: false,\r\n profile: null\r\n };\r\n }\r\n return _fromIdTokenResponse(_tokenResponse);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Non-optional auth methods.\r\n/**\r\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\r\n * `Auth` session and applies this type of persistence for future sign-in requests, including\r\n * sign-in with redirect requests.\r\n *\r\n * @remarks\r\n * This makes it easy for a user signing in to specify whether their session should be\r\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\r\n * that are shared by other users or have sensitive data.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * setPersistence(auth, browserSessionPersistence);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param persistence - The {@link Persistence} to use.\r\n * @returns A `Promise` that resolves once the persistence change has completed\r\n *\r\n * @public\r\n */\r\nfunction setPersistence(auth, persistence) {\r\n return getModularInstance(auth).setPersistence(persistence);\r\n}\r\n/**\r\n * Loads the reCAPTCHA configuration into the `Auth` instance.\r\n *\r\n * @remarks\r\n * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA\r\n * verification flow should be triggered for each auth provider, into the\r\n * current Auth session.\r\n *\r\n * If initializeRecaptchaConfig() is not invoked, the auth flow will always start\r\n * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA\r\n * verification, the SDK will transparently load the reCAPTCHA config and restart the\r\n * auth flows.\r\n *\r\n * Thus, by calling this optional method, you will reduce the latency of future auth flows.\r\n * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * initializeRecaptchaConfig(auth);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction initializeRecaptchaConfig(auth) {\r\n return _initializeRecaptchaConfig(auth);\r\n}\r\n/**\r\n * Validates the password against the password policy configured for the project or tenant.\r\n *\r\n * @remarks\r\n * If no tenant ID is set on the `Auth` instance, then this method will use the password\r\n * policy configured for the project. Otherwise, this method will use the policy configured\r\n * for the tenant. If a password policy has not been configured, then the default policy\r\n * configured for all projects will be used.\r\n *\r\n * If an auth flow fails because a submitted password does not meet the password policy\r\n * requirements and this method has previously been called, then this method will use the\r\n * most recent policy available when called again.\r\n *\r\n * @example\r\n * ```javascript\r\n * validatePassword(auth, 'some-password');\r\n * ```\r\n *\r\n * @param auth The {@link Auth} instance.\r\n * @param password The password to validate.\r\n *\r\n * @public\r\n */\r\nasync function validatePassword(auth, password) {\r\n const authInternal = _castAuth(auth);\r\n return authInternal.validatePassword(password);\r\n}\r\n/**\r\n * Adds an observer for changes to the signed-in user's ID token.\r\n *\r\n * @remarks\r\n * This includes sign-in, sign-out, and token refresh events.\r\n * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - Deprecated. This callback is never triggered. Errors\r\n * on signing in/out can be caught in promises returned from\r\n * sign-in/sign-out functions.\r\n * @param completed - Deprecated. This callback is never triggered.\r\n *\r\n * @public\r\n */\r\nfunction onIdTokenChanged(auth, nextOrObserver, error, completed) {\r\n return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Adds a blocking callback that runs before an auth state change\r\n * sets a new user.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param callback - callback triggered before new user value is set.\r\n * If this throws, it blocks the user from being set.\r\n * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`\r\n * callback throws, allowing you to undo any side effects.\r\n */\r\nfunction beforeAuthStateChanged(auth, callback, onAbort) {\r\n return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);\r\n}\r\n/**\r\n * Adds an observer for changes to the user's sign-in state.\r\n *\r\n * @remarks\r\n * To keep the old behavior, see {@link onIdTokenChanged}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - Deprecated. This callback is never triggered. Errors\r\n * on signing in/out can be caught in promises returned from\r\n * sign-in/sign-out functions.\r\n * @param completed - Deprecated. This callback is never triggered.\r\n *\r\n * @public\r\n */\r\nfunction onAuthStateChanged(auth, nextOrObserver, error, completed) {\r\n return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Sets the current language to the default device/browser preference.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction useDeviceLanguage(auth) {\r\n getModularInstance(auth).useDeviceLanguage();\r\n}\r\n/**\r\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\r\n * {@link Auth} instance.\r\n *\r\n * @remarks\r\n * A new instance copy of the user provided will be made and set as currentUser.\r\n *\r\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\r\n * like other sign in methods.\r\n *\r\n * The operation fails with an error if the user to be updated belongs to a different Firebase\r\n * project.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param user - The new {@link User}.\r\n *\r\n * @public\r\n */\r\nfunction updateCurrentUser(auth, user) {\r\n return getModularInstance(auth).updateCurrentUser(user);\r\n}\r\n/**\r\n * Signs out the current user.\r\n *\r\n * @remarks\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction signOut(auth) {\r\n return getModularInstance(auth).signOut();\r\n}\r\n/**\r\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param token - The Apple OAuth access token.\r\n *\r\n * @public\r\n */\r\nfunction revokeAccessToken(auth, token) {\r\n const authInternal = _castAuth(auth);\r\n return authInternal.revokeAccessToken(token);\r\n}\r\n/**\r\n * Deletes and signs out the user.\r\n *\r\n * @remarks\r\n * Important: this is a security-sensitive operation that requires the user to have recently\r\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function deleteUser(user) {\r\n return getModularInstance(user).delete();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorSessionImpl {\r\n constructor(type, credential, user) {\r\n this.type = type;\r\n this.credential = credential;\r\n this.user = user;\r\n }\r\n static _fromIdtoken(idToken, user) {\r\n return new MultiFactorSessionImpl(\"enroll\" /* MultiFactorSessionType.ENROLL */, idToken, user);\r\n }\r\n static _fromMfaPendingCredential(mfaPendingCredential) {\r\n return new MultiFactorSessionImpl(\"signin\" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);\r\n }\r\n toJSON() {\r\n const key = this.type === \"enroll\" /* MultiFactorSessionType.ENROLL */\r\n ? 'idToken'\r\n : 'pendingCredential';\r\n return {\r\n multiFactorSession: {\r\n [key]: this.credential\r\n }\r\n };\r\n }\r\n static fromJSON(obj) {\r\n var _a, _b;\r\n if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {\r\n if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {\r\n return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);\r\n }\r\n else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {\r\n return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);\r\n }\r\n }\r\n return null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorResolverImpl {\r\n constructor(session, hints, signInResolver) {\r\n this.session = session;\r\n this.hints = hints;\r\n this.signInResolver = signInResolver;\r\n }\r\n /** @internal */\r\n static _fromError(authExtern, error) {\r\n const auth = _castAuth(authExtern);\r\n const serverResponse = error.customData._serverResponse;\r\n const hints = (serverResponse.mfaInfo || []).map(enrollment => MultiFactorInfoImpl._fromServerResponse(auth, enrollment));\r\n _assert(serverResponse.mfaPendingCredential, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);\r\n return new MultiFactorResolverImpl(session, hints, async (assertion) => {\r\n const mfaResponse = await assertion._process(auth, session);\r\n // Clear out the unneeded fields from the old login response\r\n delete serverResponse.mfaInfo;\r\n delete serverResponse.mfaPendingCredential;\r\n // Use in the new token & refresh token in the old response\r\n const idTokenResponse = Object.assign(Object.assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });\r\n // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\r\n switch (error.operationType) {\r\n case \"signIn\" /* OperationType.SIGN_IN */:\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse);\r\n await auth._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n case \"reauthenticate\" /* OperationType.REAUTHENTICATE */:\r\n _assert(error.user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse);\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n });\r\n }\r\n async resolveSignIn(assertionExtern) {\r\n const assertion = assertionExtern;\r\n return this.signInResolver(assertion);\r\n }\r\n}\r\n/**\r\n * Provides a {@link MultiFactorResolver} suitable for completion of a\r\n * multi-factor flow.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\r\n * reauthentication operation.\r\n *\r\n * @public\r\n */\r\nfunction getMultiFactorResolver(auth, error) {\r\n var _a;\r\n const authModular = getModularInstance(auth);\r\n const errorInternal = error;\r\n _assert(error.customData.operationType, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return MultiFactorResolverImpl._fromError(authModular, errorInternal);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startEnrollPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:start\" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeEnrollPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction startEnrollTotpMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:start\" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeEnrollTotpMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction withdrawMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:withdraw\" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));\r\n}\n\nclass MultiFactorUserImpl {\r\n constructor(user) {\r\n this.user = user;\r\n this.enrolledFactors = [];\r\n user._onReload(userInfo => {\r\n if (userInfo.mfaInfo) {\r\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment => MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment));\r\n }\r\n });\r\n }\r\n static _fromUser(user) {\r\n return new MultiFactorUserImpl(user);\r\n }\r\n async getSession() {\r\n return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(), this.user);\r\n }\r\n async enroll(assertionExtern, displayName) {\r\n const assertion = assertionExtern;\r\n const session = (await this.getSession());\r\n const finalizeMfaResponse = await _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName));\r\n // New tokens will be issued after enrollment of the new second factors.\r\n // They need to be updated on the user.\r\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\r\n // The user needs to be reloaded to get the new multi-factor information\r\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\r\n // will be updated.\r\n return this.user.reload();\r\n }\r\n async unenroll(infoOrUid) {\r\n const mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\r\n const idToken = await this.user.getIdToken();\r\n try {\r\n const idTokenResponse = await _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {\r\n idToken,\r\n mfaEnrollmentId\r\n }));\r\n // Remove the second factor from the user's list.\r\n this.enrolledFactors = this.enrolledFactors.filter(({ uid }) => uid !== mfaEnrollmentId);\r\n // Depending on whether the backend decided to revoke the user's session,\r\n // the tokenResponse may be empty. If the tokens were not updated (and they\r\n // are now invalid), reloading the user will discover this and invalidate\r\n // the user's state accordingly.\r\n await this.user._updateTokensIfNecessary(idTokenResponse);\r\n await this.user.reload();\r\n }\r\n catch (e) {\r\n throw e;\r\n }\r\n }\r\n}\r\nconst multiFactorUserCache = new WeakMap();\r\n/**\r\n * The {@link MultiFactorUser} corresponding to the user.\r\n *\r\n * @remarks\r\n * This is used to access all multi-factor properties and operations related to the user.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nfunction multiFactor(user) {\r\n const userModular = getModularInstance(user);\r\n if (!multiFactorUserCache.has(userModular)) {\r\n multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));\r\n }\r\n return multiFactorUserCache.get(userModular);\r\n}\n\nconst STORAGE_AVAILABLE_KEY = '__sak';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// There are two different browser persistence types: local and session.\r\n// Both have the same implementation but use a different underlying storage\r\n// object.\r\nclass BrowserPersistenceClass {\r\n constructor(storageRetriever, type) {\r\n this.storageRetriever = storageRetriever;\r\n this.type = type;\r\n }\r\n _isAvailable() {\r\n try {\r\n if (!this.storage) {\r\n return Promise.resolve(false);\r\n }\r\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\r\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\r\n return Promise.resolve(true);\r\n }\r\n catch (_a) {\r\n return Promise.resolve(false);\r\n }\r\n }\r\n _set(key, value) {\r\n this.storage.setItem(key, JSON.stringify(value));\r\n return Promise.resolve();\r\n }\r\n _get(key) {\r\n const json = this.storage.getItem(key);\r\n return Promise.resolve(json ? JSON.parse(json) : null);\r\n }\r\n _remove(key) {\r\n this.storage.removeItem(key);\r\n return Promise.resolve();\r\n }\r\n get storage() {\r\n return this.storageRetriever();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _iframeCannotSyncWebStorage() {\r\n const ua = getUA();\r\n return _isSafari(ua) || _isIOS(ua);\r\n}\r\n// The polling period in case events are not supported\r\nconst _POLLING_INTERVAL_MS$1 = 1000;\r\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\r\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\r\nclass BrowserLocalPersistence extends BrowserPersistenceClass {\r\n constructor() {\r\n super(() => window.localStorage, \"LOCAL\" /* PersistenceType.LOCAL */);\r\n this.boundEventHandler = (event, poll) => this.onStorageEvent(event, poll);\r\n this.listeners = {};\r\n this.localCache = {};\r\n // setTimeout return value is platform specific\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.pollTimer = null;\r\n // Safari or iOS browser and embedded in an iframe.\r\n this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && _isIframe();\r\n // Whether to use polling instead of depending on window events\r\n this.fallbackToPolling = _isMobileBrowser();\r\n this._shouldAllowMigration = true;\r\n }\r\n forAllChangedKeys(cb) {\r\n // Check all keys with listeners on them.\r\n for (const key of Object.keys(this.listeners)) {\r\n // Get value from localStorage.\r\n const newValue = this.storage.getItem(key);\r\n const oldValue = this.localCache[key];\r\n // If local map value does not match, trigger listener with storage event.\r\n // Differentiate this simulated event from the real storage event.\r\n if (newValue !== oldValue) {\r\n cb(key, oldValue, newValue);\r\n }\r\n }\r\n }\r\n onStorageEvent(event, poll = false) {\r\n // Key would be null in some situations, like when localStorage is cleared\r\n if (!event.key) {\r\n this.forAllChangedKeys((key, _oldValue, newValue) => {\r\n this.notifyListeners(key, newValue);\r\n });\r\n return;\r\n }\r\n const key = event.key;\r\n // Check the mechanism how this event was detected.\r\n // The first event will dictate the mechanism to be used.\r\n if (poll) {\r\n // Environment detects storage changes via polling.\r\n // Remove storage event listener to prevent possible event duplication.\r\n this.detachListener();\r\n }\r\n else {\r\n // Environment detects storage changes via storage event listener.\r\n // Remove polling listener to prevent possible event duplication.\r\n this.stopPolling();\r\n }\r\n // Safari embedded iframe. Storage event will trigger with the delta\r\n // changes but no changes will be applied to the iframe localStorage.\r\n if (this.safariLocalStorageNotSynced) {\r\n // Get current iframe page value.\r\n const storedValue = this.storage.getItem(key);\r\n // Value not synchronized, synchronize manually.\r\n if (event.newValue !== storedValue) {\r\n if (event.newValue !== null) {\r\n // Value changed from current value.\r\n this.storage.setItem(key, event.newValue);\r\n }\r\n else {\r\n // Current value deleted.\r\n this.storage.removeItem(key);\r\n }\r\n }\r\n else if (this.localCache[key] === event.newValue && !poll) {\r\n // Already detected and processed, do not trigger listeners again.\r\n return;\r\n }\r\n }\r\n const triggerListeners = () => {\r\n // Keep local map up to date in case storage event is triggered before\r\n // poll.\r\n const storedValue = this.storage.getItem(key);\r\n if (!poll && this.localCache[key] === storedValue) {\r\n // Real storage event which has already been detected, do nothing.\r\n // This seems to trigger in some IE browsers for some reason.\r\n return;\r\n }\r\n this.notifyListeners(key, storedValue);\r\n };\r\n const storedValue = this.storage.getItem(key);\r\n if (_isIE10() &&\r\n storedValue !== event.newValue &&\r\n event.newValue !== event.oldValue) {\r\n // IE 10 has this weird bug where a storage event would trigger with the\r\n // correct key, oldValue and newValue but localStorage.getItem(key) does\r\n // not yield the updated value until a few milliseconds. This ensures\r\n // this recovers from that situation.\r\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\r\n }\r\n else {\r\n triggerListeners();\r\n }\r\n }\r\n notifyListeners(key, value) {\r\n this.localCache[key] = value;\r\n const listeners = this.listeners[key];\r\n if (listeners) {\r\n for (const listener of Array.from(listeners)) {\r\n listener(value ? JSON.parse(value) : value);\r\n }\r\n }\r\n }\r\n startPolling() {\r\n this.stopPolling();\r\n this.pollTimer = setInterval(() => {\r\n this.forAllChangedKeys((key, oldValue, newValue) => {\r\n this.onStorageEvent(new StorageEvent('storage', {\r\n key,\r\n oldValue,\r\n newValue\r\n }), \r\n /* poll */ true);\r\n });\r\n }, _POLLING_INTERVAL_MS$1);\r\n }\r\n stopPolling() {\r\n if (this.pollTimer) {\r\n clearInterval(this.pollTimer);\r\n this.pollTimer = null;\r\n }\r\n }\r\n attachListener() {\r\n window.addEventListener('storage', this.boundEventHandler);\r\n }\r\n detachListener() {\r\n window.removeEventListener('storage', this.boundEventHandler);\r\n }\r\n _addListener(key, listener) {\r\n if (Object.keys(this.listeners).length === 0) {\r\n // Whether browser can detect storage event when it had already been pushed to the background.\r\n // This may happen in some mobile browsers. A localStorage change in the foreground window\r\n // will not be detected in the background window via the storage event.\r\n // This was detected in iOS 7.x mobile browsers\r\n if (this.fallbackToPolling) {\r\n this.startPolling();\r\n }\r\n else {\r\n this.attachListener();\r\n }\r\n }\r\n if (!this.listeners[key]) {\r\n this.listeners[key] = new Set();\r\n // Populate the cache to avoid spuriously triggering on first poll.\r\n this.localCache[key] = this.storage.getItem(key);\r\n }\r\n this.listeners[key].add(listener);\r\n }\r\n _removeListener(key, listener) {\r\n if (this.listeners[key]) {\r\n this.listeners[key].delete(listener);\r\n if (this.listeners[key].size === 0) {\r\n delete this.listeners[key];\r\n }\r\n }\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.detachListener();\r\n this.stopPolling();\r\n }\r\n }\r\n // Update local cache on base operations:\r\n async _set(key, value) {\r\n await super._set(key, value);\r\n this.localCache[key] = JSON.stringify(value);\r\n }\r\n async _get(key) {\r\n const value = await super._get(key);\r\n this.localCache[key] = JSON.stringify(value);\r\n return value;\r\n }\r\n async _remove(key) {\r\n await super._remove(key);\r\n delete this.localCache[key];\r\n }\r\n}\r\nBrowserLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserLocalPersistence = BrowserLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass BrowserSessionPersistence extends BrowserPersistenceClass {\r\n constructor() {\r\n super(() => window.sessionStorage, \"SESSION\" /* PersistenceType.SESSION */);\r\n }\r\n _addListener(_key, _listener) {\r\n // Listeners are not supported for session storage since it cannot be shared across windows\r\n return;\r\n }\r\n _removeListener(_key, _listener) {\r\n // Listeners are not supported for session storage since it cannot be shared across windows\r\n return;\r\n }\r\n}\r\nBrowserSessionPersistence.type = 'SESSION';\r\n/**\r\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserSessionPersistence = BrowserSessionPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\r\n *\r\n * @param promises - Array of promises to wait on.\r\n */\r\nfunction _allSettled(promises) {\r\n return Promise.all(promises.map(async (promise) => {\r\n try {\r\n const value = await promise;\r\n return {\r\n fulfilled: true,\r\n value\r\n };\r\n }\r\n catch (reason) {\r\n return {\r\n fulfilled: false,\r\n reason\r\n };\r\n }\r\n }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface class for receiving messages.\r\n *\r\n */\r\nclass Receiver {\r\n constructor(eventTarget) {\r\n this.eventTarget = eventTarget;\r\n this.handlersMap = {};\r\n this.boundEventHandler = this.handleEvent.bind(this);\r\n }\r\n /**\r\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\r\n *\r\n * @param eventTarget - An event target (such as window or self) through which the underlying\r\n * messages will be received.\r\n */\r\n static _getInstance(eventTarget) {\r\n // The results are stored in an array since objects can't be keys for other\r\n // objects. In addition, setting a unique property on an event target as a\r\n // hash map key may not be allowed due to CORS restrictions.\r\n const existingInstance = this.receivers.find(receiver => receiver.isListeningto(eventTarget));\r\n if (existingInstance) {\r\n return existingInstance;\r\n }\r\n const newInstance = new Receiver(eventTarget);\r\n this.receivers.push(newInstance);\r\n return newInstance;\r\n }\r\n isListeningto(eventTarget) {\r\n return this.eventTarget === eventTarget;\r\n }\r\n /**\r\n * Fans out a MessageEvent to the appropriate listeners.\r\n *\r\n * @remarks\r\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\r\n * finished processing.\r\n *\r\n * @param event - The MessageEvent.\r\n *\r\n */\r\n async handleEvent(event) {\r\n const messageEvent = event;\r\n const { eventId, eventType, data } = messageEvent.data;\r\n const handlers = this.handlersMap[eventType];\r\n if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {\r\n return;\r\n }\r\n messageEvent.ports[0].postMessage({\r\n status: \"ack\" /* _Status.ACK */,\r\n eventId,\r\n eventType\r\n });\r\n const promises = Array.from(handlers).map(async (handler) => handler(messageEvent.origin, data));\r\n const response = await _allSettled(promises);\r\n messageEvent.ports[0].postMessage({\r\n status: \"done\" /* _Status.DONE */,\r\n eventId,\r\n eventType,\r\n response\r\n });\r\n }\r\n /**\r\n * Subscribe an event handler for a particular event.\r\n *\r\n * @param eventType - Event name to subscribe to.\r\n * @param eventHandler - The event handler which should receive the events.\r\n *\r\n */\r\n _subscribe(eventType, eventHandler) {\r\n if (Object.keys(this.handlersMap).length === 0) {\r\n this.eventTarget.addEventListener('message', this.boundEventHandler);\r\n }\r\n if (!this.handlersMap[eventType]) {\r\n this.handlersMap[eventType] = new Set();\r\n }\r\n this.handlersMap[eventType].add(eventHandler);\r\n }\r\n /**\r\n * Unsubscribe an event handler from a particular event.\r\n *\r\n * @param eventType - Event name to unsubscribe from.\r\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\r\n *\r\n */\r\n _unsubscribe(eventType, eventHandler) {\r\n if (this.handlersMap[eventType] && eventHandler) {\r\n this.handlersMap[eventType].delete(eventHandler);\r\n }\r\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\r\n delete this.handlersMap[eventType];\r\n }\r\n if (Object.keys(this.handlersMap).length === 0) {\r\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\r\n }\r\n }\r\n}\r\nReceiver.receivers = [];\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _generateEventId(prefix = '', digits = 10) {\r\n let random = '';\r\n for (let i = 0; i < digits; i++) {\r\n random += Math.floor(Math.random() * 10);\r\n }\r\n return prefix + random;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface for sending messages and waiting for a completion response.\r\n *\r\n */\r\nclass Sender {\r\n constructor(target) {\r\n this.target = target;\r\n this.handlers = new Set();\r\n }\r\n /**\r\n * Unsubscribe the handler and remove it from our tracking Set.\r\n *\r\n * @param handler - The handler to unsubscribe.\r\n */\r\n removeMessageHandler(handler) {\r\n if (handler.messageChannel) {\r\n handler.messageChannel.port1.removeEventListener('message', handler.onMessage);\r\n handler.messageChannel.port1.close();\r\n }\r\n this.handlers.delete(handler);\r\n }\r\n /**\r\n * Send a message to the Receiver located at {@link target}.\r\n *\r\n * @remarks\r\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\r\n * receiver has had a chance to fully process the event.\r\n *\r\n * @param eventType - Type of event to send.\r\n * @param data - The payload of the event.\r\n * @param timeout - Timeout for waiting on an ACK from the receiver.\r\n *\r\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\r\n */\r\n async _send(eventType, data, timeout = 50 /* _TimeoutDuration.ACK */) {\r\n const messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\r\n if (!messageChannel) {\r\n throw new Error(\"connection_unavailable\" /* _MessageError.CONNECTION_UNAVAILABLE */);\r\n }\r\n // Node timers and browser timers return fundamentally different types.\r\n // We don't actually care what the value is but TS won't accept unknown and\r\n // we can't cast properly in both environments.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n let completionTimer;\r\n let handler;\r\n return new Promise((resolve, reject) => {\r\n const eventId = _generateEventId('', 20);\r\n messageChannel.port1.start();\r\n const ackTimer = setTimeout(() => {\r\n reject(new Error(\"unsupported_event\" /* _MessageError.UNSUPPORTED_EVENT */));\r\n }, timeout);\r\n handler = {\r\n messageChannel,\r\n onMessage(event) {\r\n const messageEvent = event;\r\n if (messageEvent.data.eventId !== eventId) {\r\n return;\r\n }\r\n switch (messageEvent.data.status) {\r\n case \"ack\" /* _Status.ACK */:\r\n // The receiver should ACK first.\r\n clearTimeout(ackTimer);\r\n completionTimer = setTimeout(() => {\r\n reject(new Error(\"timeout\" /* _MessageError.TIMEOUT */));\r\n }, 3000 /* _TimeoutDuration.COMPLETION */);\r\n break;\r\n case \"done\" /* _Status.DONE */:\r\n // Once the receiver's handlers are finished we will get the results.\r\n clearTimeout(completionTimer);\r\n resolve(messageEvent.data.response);\r\n break;\r\n default:\r\n clearTimeout(ackTimer);\r\n clearTimeout(completionTimer);\r\n reject(new Error(\"invalid_response\" /* _MessageError.INVALID_RESPONSE */));\r\n break;\r\n }\r\n }\r\n };\r\n this.handlers.add(handler);\r\n messageChannel.port1.addEventListener('message', handler.onMessage);\r\n this.target.postMessage({\r\n eventType,\r\n eventId,\r\n data\r\n }, [messageChannel.port2]);\r\n }).finally(() => {\r\n if (handler) {\r\n this.removeMessageHandler(handler);\r\n }\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Lazy accessor for window, since the compat layer won't tree shake this out,\r\n * we need to make sure not to mess with window unless we have to\r\n */\r\nfunction _window() {\r\n return window;\r\n}\r\nfunction _setWindowLocation(url) {\r\n _window().location.href = url;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _isWorker() {\r\n return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\r\n typeof _window()['importScripts'] === 'function');\r\n}\r\nasync function _getActiveServiceWorker() {\r\n if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {\r\n return null;\r\n }\r\n try {\r\n const registration = await navigator.serviceWorker.ready;\r\n return registration.active;\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n}\r\nfunction _getServiceWorkerController() {\r\n var _a;\r\n return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;\r\n}\r\nfunction _getWorkerGlobalScope() {\r\n return _isWorker() ? self : null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebaseLocalStorageDb';\r\nconst DB_VERSION = 1;\r\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\r\nconst DB_DATA_KEYPATH = 'fbase_key';\r\n/**\r\n * Promise wrapper for IDBRequest\r\n *\r\n * Unfortunately we can't cleanly extend Promise since promises are not callable in ES6\r\n *\r\n */\r\nclass DBPromise {\r\n constructor(request) {\r\n this.request = request;\r\n }\r\n toPromise() {\r\n return new Promise((resolve, reject) => {\r\n this.request.addEventListener('success', () => {\r\n resolve(this.request.result);\r\n });\r\n this.request.addEventListener('error', () => {\r\n reject(this.request.error);\r\n });\r\n });\r\n }\r\n}\r\nfunction getObjectStore(db, isReadWrite) {\r\n return db\r\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\r\n .objectStore(DB_OBJECTSTORE_NAME);\r\n}\r\nfunction _deleteDatabase() {\r\n const request = indexedDB.deleteDatabase(DB_NAME);\r\n return new DBPromise(request).toPromise();\r\n}\r\nfunction _openDatabase() {\r\n const request = indexedDB.open(DB_NAME, DB_VERSION);\r\n return new Promise((resolve, reject) => {\r\n request.addEventListener('error', () => {\r\n reject(request.error);\r\n });\r\n request.addEventListener('upgradeneeded', () => {\r\n const db = request.result;\r\n try {\r\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n });\r\n request.addEventListener('success', async () => {\r\n const db = request.result;\r\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\r\n // same time. The only way to recover seems to be deleting the database\r\n // and re-initializing it.\r\n // https://github.com/firebase/firebase-js-sdk/issues/634\r\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\r\n // Need to close the database or else you get a `blocked` event\r\n db.close();\r\n await _deleteDatabase();\r\n resolve(await _openDatabase());\r\n }\r\n else {\r\n resolve(db);\r\n }\r\n });\r\n });\r\n}\r\nasync function _putObject(db, key, value) {\r\n const request = getObjectStore(db, true).put({\r\n [DB_DATA_KEYPATH]: key,\r\n value\r\n });\r\n return new DBPromise(request).toPromise();\r\n}\r\nasync function getObject(db, key) {\r\n const request = getObjectStore(db, false).get(key);\r\n const data = await new DBPromise(request).toPromise();\r\n return data === undefined ? null : data.value;\r\n}\r\nfunction _deleteObject(db, key) {\r\n const request = getObjectStore(db, true).delete(key);\r\n return new DBPromise(request).toPromise();\r\n}\r\nconst _POLLING_INTERVAL_MS = 800;\r\nconst _TRANSACTION_RETRY_COUNT = 3;\r\nclass IndexedDBLocalPersistence {\r\n constructor() {\r\n this.type = \"LOCAL\" /* PersistenceType.LOCAL */;\r\n this._shouldAllowMigration = true;\r\n this.listeners = {};\r\n this.localCache = {};\r\n // setTimeout return value is platform specific\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.pollTimer = null;\r\n this.pendingWrites = 0;\r\n this.receiver = null;\r\n this.sender = null;\r\n this.serviceWorkerReceiverAvailable = false;\r\n this.activeServiceWorker = null;\r\n // Fire & forget the service worker registration as it may never resolve\r\n this._workerInitializationPromise =\r\n this.initializeServiceWorkerMessaging().then(() => { }, () => { });\r\n }\r\n async _openDb() {\r\n if (this.db) {\r\n return this.db;\r\n }\r\n this.db = await _openDatabase();\r\n return this.db;\r\n }\r\n async _withRetries(op) {\r\n let numAttempts = 0;\r\n while (true) {\r\n try {\r\n const db = await this._openDb();\r\n return await op(db);\r\n }\r\n catch (e) {\r\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\r\n throw e;\r\n }\r\n if (this.db) {\r\n this.db.close();\r\n this.db = undefined;\r\n }\r\n // TODO: consider adding exponential backoff\r\n }\r\n }\r\n }\r\n /**\r\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\r\n * postMessage interface to send these events to the worker ourselves.\r\n */\r\n async initializeServiceWorkerMessaging() {\r\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\r\n }\r\n /**\r\n * As the worker we should listen to events from the main window.\r\n */\r\n async initializeReceiver() {\r\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope());\r\n // Refresh from persistence if we receive a KeyChanged message.\r\n this.receiver._subscribe(\"keyChanged\" /* _EventType.KEY_CHANGED */, async (_origin, data) => {\r\n const keys = await this._poll();\r\n return {\r\n keyProcessed: keys.includes(data.key)\r\n };\r\n });\r\n // Let the sender know that we are listening so they give us more timeout.\r\n this.receiver._subscribe(\"ping\" /* _EventType.PING */, async (_origin, _data) => {\r\n return [\"keyChanged\" /* _EventType.KEY_CHANGED */];\r\n });\r\n }\r\n /**\r\n * As the main window, we should let the worker know when keys change (set and remove).\r\n *\r\n * @remarks\r\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\r\n * may not resolve.\r\n */\r\n async initializeSender() {\r\n var _a, _b;\r\n // Check to see if there's an active service worker.\r\n this.activeServiceWorker = await _getActiveServiceWorker();\r\n if (!this.activeServiceWorker) {\r\n return;\r\n }\r\n this.sender = new Sender(this.activeServiceWorker);\r\n // Ping the service worker to check what events they can handle.\r\n const results = await this.sender._send(\"ping\" /* _EventType.PING */, {}, 800 /* _TimeoutDuration.LONG_ACK */);\r\n if (!results) {\r\n return;\r\n }\r\n if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&\r\n ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes(\"keyChanged\" /* _EventType.KEY_CHANGED */))) {\r\n this.serviceWorkerReceiverAvailable = true;\r\n }\r\n }\r\n /**\r\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\r\n * worker will just trigger a full sync anyway.\r\n *\r\n * @remarks\r\n * For now, we only support one service worker per page.\r\n *\r\n * @param key - Storage key which changed.\r\n */\r\n async notifyServiceWorker(key) {\r\n if (!this.sender ||\r\n !this.activeServiceWorker ||\r\n _getServiceWorkerController() !== this.activeServiceWorker) {\r\n return;\r\n }\r\n try {\r\n await this.sender._send(\"keyChanged\" /* _EventType.KEY_CHANGED */, { key }, \r\n // Use long timeout if receiver has previously responded to a ping from us.\r\n this.serviceWorkerReceiverAvailable\r\n ? 800 /* _TimeoutDuration.LONG_ACK */\r\n : 50 /* _TimeoutDuration.ACK */);\r\n }\r\n catch (_a) {\r\n // This is a best effort approach. Ignore errors.\r\n }\r\n }\r\n async _isAvailable() {\r\n try {\r\n if (!indexedDB) {\r\n return false;\r\n }\r\n const db = await _openDatabase();\r\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\r\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\r\n return true;\r\n }\r\n catch (_a) { }\r\n return false;\r\n }\r\n async _withPendingWrite(write) {\r\n this.pendingWrites++;\r\n try {\r\n await write();\r\n }\r\n finally {\r\n this.pendingWrites--;\r\n }\r\n }\r\n async _set(key, value) {\r\n return this._withPendingWrite(async () => {\r\n await this._withRetries((db) => _putObject(db, key, value));\r\n this.localCache[key] = value;\r\n return this.notifyServiceWorker(key);\r\n });\r\n }\r\n async _get(key) {\r\n const obj = (await this._withRetries((db) => getObject(db, key)));\r\n this.localCache[key] = obj;\r\n return obj;\r\n }\r\n async _remove(key) {\r\n return this._withPendingWrite(async () => {\r\n await this._withRetries((db) => _deleteObject(db, key));\r\n delete this.localCache[key];\r\n return this.notifyServiceWorker(key);\r\n });\r\n }\r\n async _poll() {\r\n // TODO: check if we need to fallback if getAll is not supported\r\n const result = await this._withRetries((db) => {\r\n const getAllRequest = getObjectStore(db, false).getAll();\r\n return new DBPromise(getAllRequest).toPromise();\r\n });\r\n if (!result) {\r\n return [];\r\n }\r\n // If we have pending writes in progress abort, we'll get picked up on the next poll\r\n if (this.pendingWrites !== 0) {\r\n return [];\r\n }\r\n const keys = [];\r\n const keysInResult = new Set();\r\n if (result.length !== 0) {\r\n for (const { fbase_key: key, value } of result) {\r\n keysInResult.add(key);\r\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\r\n this.notifyListeners(key, value);\r\n keys.push(key);\r\n }\r\n }\r\n }\r\n for (const localKey of Object.keys(this.localCache)) {\r\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\r\n // Deleted\r\n this.notifyListeners(localKey, null);\r\n keys.push(localKey);\r\n }\r\n }\r\n return keys;\r\n }\r\n notifyListeners(key, newValue) {\r\n this.localCache[key] = newValue;\r\n const listeners = this.listeners[key];\r\n if (listeners) {\r\n for (const listener of Array.from(listeners)) {\r\n listener(newValue);\r\n }\r\n }\r\n }\r\n startPolling() {\r\n this.stopPolling();\r\n this.pollTimer = setInterval(async () => this._poll(), _POLLING_INTERVAL_MS);\r\n }\r\n stopPolling() {\r\n if (this.pollTimer) {\r\n clearInterval(this.pollTimer);\r\n this.pollTimer = null;\r\n }\r\n }\r\n _addListener(key, listener) {\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.startPolling();\r\n }\r\n if (!this.listeners[key]) {\r\n this.listeners[key] = new Set();\r\n // Populate the cache to avoid spuriously triggering on first poll.\r\n void this._get(key); // This can happen in the background async and we can return immediately.\r\n }\r\n this.listeners[key].add(listener);\r\n }\r\n _removeListener(key, listener) {\r\n if (this.listeners[key]) {\r\n this.listeners[key].delete(listener);\r\n if (this.listeners[key].size === 0) {\r\n delete this.listeners[key];\r\n }\r\n }\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.stopPolling();\r\n }\r\n }\r\n}\r\nIndexedDBLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst indexedDBLocalPersistence = IndexedDBLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startSignInPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:start\" /* Endpoint.START_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeSignInPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:finalize\" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeSignInTotpMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:finalize\" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _SOLVE_TIME_MS = 500;\r\nconst _EXPIRATION_TIME_MS = 60000;\r\nconst _WIDGET_ID_START = 1000000000000;\r\nclass MockReCaptcha {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.counter = _WIDGET_ID_START;\r\n this._widgets = new Map();\r\n }\r\n render(container, parameters) {\r\n const id = this.counter;\r\n this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));\r\n this.counter++;\r\n return id;\r\n }\r\n reset(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());\r\n this._widgets.delete(id);\r\n }\r\n getResponse(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';\r\n }\r\n async execute(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());\r\n return '';\r\n }\r\n}\r\nclass MockWidget {\r\n constructor(containerOrId, appName, params) {\r\n this.params = params;\r\n this.timerId = null;\r\n this.deleted = false;\r\n this.responseToken = null;\r\n this.clickHandler = () => {\r\n this.execute();\r\n };\r\n const container = typeof containerOrId === 'string'\r\n ? document.getElementById(containerOrId)\r\n : containerOrId;\r\n _assert(container, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, { appName });\r\n this.container = container;\r\n this.isVisible = this.params.size !== 'invisible';\r\n if (this.isVisible) {\r\n this.execute();\r\n }\r\n else {\r\n this.container.addEventListener('click', this.clickHandler);\r\n }\r\n }\r\n getResponse() {\r\n this.checkIfDeleted();\r\n return this.responseToken;\r\n }\r\n delete() {\r\n this.checkIfDeleted();\r\n this.deleted = true;\r\n if (this.timerId) {\r\n clearTimeout(this.timerId);\r\n this.timerId = null;\r\n }\r\n this.container.removeEventListener('click', this.clickHandler);\r\n }\r\n execute() {\r\n this.checkIfDeleted();\r\n if (this.timerId) {\r\n return;\r\n }\r\n this.timerId = window.setTimeout(() => {\r\n this.responseToken = generateRandomAlphaNumericString(50);\r\n const { callback, 'expired-callback': expiredCallback } = this.params;\r\n if (callback) {\r\n try {\r\n callback(this.responseToken);\r\n }\r\n catch (e) { }\r\n }\r\n this.timerId = window.setTimeout(() => {\r\n this.timerId = null;\r\n this.responseToken = null;\r\n if (expiredCallback) {\r\n try {\r\n expiredCallback();\r\n }\r\n catch (e) { }\r\n }\r\n if (this.isVisible) {\r\n this.execute();\r\n }\r\n }, _EXPIRATION_TIME_MS);\r\n }, _SOLVE_TIME_MS);\r\n }\r\n checkIfDeleted() {\r\n if (this.deleted) {\r\n throw new Error('reCAPTCHA mock was already deleted!');\r\n }\r\n }\r\n}\r\nfunction generateRandomAlphaNumericString(len) {\r\n const chars = [];\r\n const allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n for (let i = 0; i < len; i++) {\r\n chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));\r\n }\r\n return chars.join('');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// ReCaptcha will load using the same callback, so the callback function needs\r\n// to be kept around\r\nconst _JSLOAD_CALLBACK = _generateCallbackName('rcb');\r\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\r\n/**\r\n * Loader for the GReCaptcha library. There should only ever be one of this.\r\n */\r\nclass ReCaptchaLoaderImpl {\r\n constructor() {\r\n var _a;\r\n this.hostLanguage = '';\r\n this.counter = 0;\r\n /**\r\n * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\r\n * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\r\n * `window.grecaptcha.render()` will not. Another load will add it.\r\n */\r\n this.librarySeparatelyLoaded = !!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render);\r\n }\r\n load(auth, hl = '') {\r\n _assert(isHostLanguageValid(hl), auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {\r\n return Promise.resolve(_window().grecaptcha);\r\n }\r\n return new Promise((resolve, reject) => {\r\n const networkTimeout = _window().setTimeout(() => {\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }, NETWORK_TIMEOUT_DELAY.get());\r\n _window()[_JSLOAD_CALLBACK] = () => {\r\n _window().clearTimeout(networkTimeout);\r\n delete _window()[_JSLOAD_CALLBACK];\r\n const recaptcha = _window().grecaptcha;\r\n if (!recaptcha || !isV2(recaptcha)) {\r\n reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\r\n return;\r\n }\r\n // Wrap the greptcha render function so that we know if the developer has\r\n // called it separately\r\n const render = recaptcha.render;\r\n recaptcha.render = (container, params) => {\r\n const widgetId = render(container, params);\r\n this.counter++;\r\n return widgetId;\r\n };\r\n this.hostLanguage = hl;\r\n resolve(recaptcha);\r\n };\r\n const url = `${_recaptchaV2ScriptUrl()}?${querystring({\r\n onload: _JSLOAD_CALLBACK,\r\n render: 'explicit',\r\n hl\r\n })}`;\r\n _loadJS(url).catch(() => {\r\n clearTimeout(networkTimeout);\r\n reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\r\n });\r\n });\r\n }\r\n clearedOneInstance() {\r\n this.counter--;\r\n }\r\n shouldResolveImmediately(hl) {\r\n var _a;\r\n // We can resolve immediately if:\r\n // • grecaptcha is already defined AND (\r\n // 1. the requested language codes are the same OR\r\n // 2. there exists already a ReCaptcha on the page\r\n // 3. the library was already loaded by the app\r\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\r\n // that are already in the page\r\n return (!!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render) &&\r\n (hl === this.hostLanguage ||\r\n this.counter > 0 ||\r\n this.librarySeparatelyLoaded));\r\n }\r\n}\r\nfunction isHostLanguageValid(hl) {\r\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\r\n}\r\nclass MockReCaptchaLoaderImpl {\r\n async load(auth) {\r\n return new MockReCaptcha(auth);\r\n }\r\n clearedOneInstance() { }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\r\nconst DEFAULT_PARAMS = {\r\n theme: 'light',\r\n type: 'image'\r\n};\r\n/**\r\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\r\n *\r\n * @remarks\r\n * `RecaptchaVerifier` does not work in a Node.js environment.\r\n *\r\n * @public\r\n */\r\nclass RecaptchaVerifier {\r\n /**\r\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\r\n *\r\n * @param containerOrId - The reCAPTCHA container parameter.\r\n *\r\n * @remarks\r\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\r\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\r\n * an element ID. The corresponding element must also must be in the DOM at the time of\r\n * initialization.\r\n *\r\n * @param parameters - The optional reCAPTCHA parameters.\r\n *\r\n * @remarks\r\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\r\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\r\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\r\n * 'invisible'.\r\n */\r\n constructor(authExtern, containerOrId, parameters = Object.assign({}, DEFAULT_PARAMS)) {\r\n this.parameters = parameters;\r\n /**\r\n * The application verifier type.\r\n *\r\n * @remarks\r\n * For a reCAPTCHA verifier, this is 'recaptcha'.\r\n */\r\n this.type = RECAPTCHA_VERIFIER_TYPE;\r\n this.destroyed = false;\r\n this.widgetId = null;\r\n this.tokenChangeListeners = new Set();\r\n this.renderPromise = null;\r\n this.recaptcha = null;\r\n this.auth = _castAuth(authExtern);\r\n this.isInvisible = this.parameters.size === 'invisible';\r\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n const container = typeof containerOrId === 'string'\r\n ? document.getElementById(containerOrId)\r\n : containerOrId;\r\n _assert(container, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.container = container;\r\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\r\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\r\n ? new MockReCaptchaLoaderImpl()\r\n : new ReCaptchaLoaderImpl();\r\n this.validateStartingState();\r\n // TODO: Figure out if sdk version is needed\r\n }\r\n /**\r\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\r\n *\r\n * @returns A Promise for the reCAPTCHA token.\r\n */\r\n async verify() {\r\n this.assertNotDestroyed();\r\n const id = await this.render();\r\n const recaptcha = this.getAssertedRecaptcha();\r\n const response = recaptcha.getResponse(id);\r\n if (response) {\r\n return response;\r\n }\r\n return new Promise(resolve => {\r\n const tokenChange = (token) => {\r\n if (!token) {\r\n return; // Ignore token expirations.\r\n }\r\n this.tokenChangeListeners.delete(tokenChange);\r\n resolve(token);\r\n };\r\n this.tokenChangeListeners.add(tokenChange);\r\n if (this.isInvisible) {\r\n recaptcha.execute(id);\r\n }\r\n });\r\n }\r\n /**\r\n * Renders the reCAPTCHA widget on the page.\r\n *\r\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\r\n */\r\n render() {\r\n try {\r\n this.assertNotDestroyed();\r\n }\r\n catch (e) {\r\n // This method returns a promise. Since it's not async (we want to return the\r\n // _same_ promise if rendering is still occurring), the API surface should\r\n // reject with the error rather than just throw\r\n return Promise.reject(e);\r\n }\r\n if (this.renderPromise) {\r\n return this.renderPromise;\r\n }\r\n this.renderPromise = this.makeRenderPromise().catch(e => {\r\n this.renderPromise = null;\r\n throw e;\r\n });\r\n return this.renderPromise;\r\n }\r\n /** @internal */\r\n _reset() {\r\n this.assertNotDestroyed();\r\n if (this.widgetId !== null) {\r\n this.getAssertedRecaptcha().reset(this.widgetId);\r\n }\r\n }\r\n /**\r\n * Clears the reCAPTCHA widget from the page and destroys the instance.\r\n */\r\n clear() {\r\n this.assertNotDestroyed();\r\n this.destroyed = true;\r\n this._recaptchaLoader.clearedOneInstance();\r\n if (!this.isInvisible) {\r\n this.container.childNodes.forEach(node => {\r\n this.container.removeChild(node);\r\n });\r\n }\r\n }\r\n validateStartingState() {\r\n _assert(!this.parameters.sitekey, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n }\r\n makeTokenCallback(existing) {\r\n return token => {\r\n this.tokenChangeListeners.forEach(listener => listener(token));\r\n if (typeof existing === 'function') {\r\n existing(token);\r\n }\r\n else if (typeof existing === 'string') {\r\n const globalFunc = _window()[existing];\r\n if (typeof globalFunc === 'function') {\r\n globalFunc(token);\r\n }\r\n }\r\n };\r\n }\r\n assertNotDestroyed() {\r\n _assert(!this.destroyed, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n async makeRenderPromise() {\r\n await this.init();\r\n if (!this.widgetId) {\r\n let container = this.container;\r\n if (!this.isInvisible) {\r\n const guaranteedEmpty = document.createElement('div');\r\n container.appendChild(guaranteedEmpty);\r\n container = guaranteedEmpty;\r\n }\r\n this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);\r\n }\r\n return this.widgetId;\r\n }\r\n async init() {\r\n _assert(_isHttpOrHttps() && !_isWorker(), this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n await domReady();\r\n this.recaptcha = await this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined);\r\n const siteKey = await getRecaptchaParams(this.auth);\r\n _assert(siteKey, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.parameters.sitekey = siteKey;\r\n }\r\n getAssertedRecaptcha() {\r\n _assert(this.recaptcha, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.recaptcha;\r\n }\r\n}\r\nfunction domReady() {\r\n let resolver = null;\r\n return new Promise(resolve => {\r\n if (document.readyState === 'complete') {\r\n resolve();\r\n return;\r\n }\r\n // Document not ready, wait for load before resolving.\r\n // Save resolver, so we can remove listener in case it was externally\r\n // cancelled.\r\n resolver = () => resolve();\r\n window.addEventListener('load', resolver);\r\n }).catch(e => {\r\n if (resolver) {\r\n window.removeEventListener('load', resolver);\r\n }\r\n throw e;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ConfirmationResultImpl {\r\n constructor(verificationId, onConfirmation) {\r\n this.verificationId = verificationId;\r\n this.onConfirmation = onConfirmation;\r\n }\r\n confirm(verificationCode) {\r\n const authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);\r\n return this.onConfirmation(authCredential);\r\n }\r\n}\r\n/**\r\n * Asynchronously signs in using a phone number.\r\n *\r\n * @remarks\r\n * This method sends a code via SMS to the given\r\n * phone number, and returns a {@link ConfirmationResult}. After the user\r\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\r\n * with the code to sign the user in.\r\n *\r\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\r\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\r\n * This function can work on other platforms that do not support the\r\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\r\n * third-party {@link ApplicationVerifier} implementation.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\r\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain a verificationCode from the user.\r\n * const credential = await confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n const verificationId = await _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => signInWithCredential(authInternal, cred));\r\n}\r\n/**\r\n * Links the user account with the given phone number.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(false, userInternal, \"phone\" /* ProviderId.PHONE */);\r\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => linkWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh phone credential.\r\n *\r\n * @remarks\r\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\r\n *\r\n * This method does not work in a Node.js environment or on any {@link User} signed in by\r\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => reauthenticateWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\r\n *\r\n */\r\nasync function _verifyPhoneNumber(auth, options, verifier) {\r\n var _a;\r\n const recaptchaToken = await verifier.verify();\r\n try {\r\n _assert(typeof recaptchaToken === 'string', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n let phoneInfoOptions;\r\n if (typeof options === 'string') {\r\n phoneInfoOptions = {\r\n phoneNumber: options\r\n };\r\n }\r\n else {\r\n phoneInfoOptions = options;\r\n }\r\n if ('session' in phoneInfoOptions) {\r\n const session = phoneInfoOptions.session;\r\n if ('phoneNumber' in phoneInfoOptions) {\r\n _assert(session.type === \"enroll\" /* MultiFactorSessionType.ENROLL */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const response = await startEnrollPhoneMfa(auth, {\r\n idToken: session.credential,\r\n phoneEnrollmentInfo: {\r\n phoneNumber: phoneInfoOptions.phoneNumber,\r\n recaptchaToken\r\n }\r\n });\r\n return response.phoneSessionInfo.sessionInfo;\r\n }\r\n else {\r\n _assert(session.type === \"signin\" /* MultiFactorSessionType.SIGN_IN */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||\r\n phoneInfoOptions.multiFactorUid;\r\n _assert(mfaEnrollmentId, auth, \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */);\r\n const response = await startSignInPhoneMfa(auth, {\r\n mfaPendingCredential: session.credential,\r\n mfaEnrollmentId,\r\n phoneSignInInfo: {\r\n recaptchaToken\r\n }\r\n });\r\n return response.phoneResponseInfo.sessionInfo;\r\n }\r\n }\r\n else {\r\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\r\n phoneNumber: phoneInfoOptions.phoneNumber,\r\n recaptchaToken\r\n });\r\n return sessionInfo;\r\n }\r\n }\r\n finally {\r\n verifier._reset();\r\n }\r\n}\r\n/**\r\n * Updates the user's phone number.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment or on any {@link User} signed in by\r\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * await updatePhoneNumber(user, phoneCredential);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param credential - A credential authenticating the new phone number.\r\n *\r\n * @public\r\n */\r\nasync function updatePhoneNumber(user, credential) {\r\n const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n await _link$1(userInternal, credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link PhoneAuthCredential}.\r\n *\r\n * @remarks\r\n * `PhoneAuthProvider` does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = await signInWithCredential(auth, phoneCredential);\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthProvider {\r\n /**\r\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\r\n *\r\n */\r\n constructor(auth) {\r\n /** Always set to {@link ProviderId}.PHONE. */\r\n this.providerId = PhoneAuthProvider.PROVIDER_ID;\r\n this.auth = _castAuth(auth);\r\n }\r\n /**\r\n *\r\n * Starts a phone number authentication flow by sending a verification code to the given phone\r\n * number.\r\n *\r\n * @example\r\n * ```javascript\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n * ```javascript\r\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const userCredential = confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\r\n * E.164 format (e.g. +16505550101).\r\n * @param applicationVerifier - For abuse prevention, this method also requires a\r\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\r\n * {@link RecaptchaVerifier}.\r\n *\r\n * @returns A Promise for a verification ID that can be passed to\r\n * {@link PhoneAuthProvider.credential} to identify this flow..\r\n */\r\n verifyPhoneNumber(phoneOptions, applicationVerifier) {\r\n return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));\r\n }\r\n /**\r\n * Creates a phone auth credential, given the verification ID from\r\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\r\n * mobile device.\r\n *\r\n * @example\r\n * ```javascript\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n * ```javascript\r\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const userCredential = await confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\r\n * @param verificationCode - The verification code sent to the user's mobile device.\r\n *\r\n * @returns The auth provider credential.\r\n */\r\n static credential(verificationId, verificationCode) {\r\n return PhoneAuthCredential._fromVerification(verificationId, verificationCode);\r\n }\r\n /**\r\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n const credential = userCredential;\r\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\r\n }\r\n /**\r\n * Returns an {@link AuthCredential} when passed an error.\r\n *\r\n * @remarks\r\n *\r\n * This method works for errors like\r\n * `auth/account-exists-with-different-credentials`. This is useful for\r\n * recovering when attempting to set a user's phone number but the number\r\n * in question is already tied to another account. For example, the following\r\n * code tries to update the current user's phone number, and if that\r\n * fails, links the user with the account associated with that number:\r\n *\r\n * ```js\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\r\n * try {\r\n * const code = ''; // Prompt the user for the verification code\r\n * await updatePhoneNumber(\r\n * auth.currentUser,\r\n * PhoneAuthProvider.credential(verificationId, code));\r\n * } catch (e) {\r\n * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\r\n * const cred = PhoneAuthProvider.credentialFromError(e);\r\n * await linkWithCredential(auth.currentUser, cred);\r\n * }\r\n * }\r\n *\r\n * // At this point, auth.currentUser.phoneNumber === number.\r\n * ```\r\n *\r\n * @param error - The error to generate a credential from.\r\n */\r\n static credentialFromError(error) {\r\n return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { phoneNumber, temporaryProof } = tokenResponse;\r\n if (phoneNumber && temporaryProof) {\r\n return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);\r\n }\r\n return null;\r\n }\r\n}\r\n/** Always set to {@link ProviderId}.PHONE. */\r\nPhoneAuthProvider.PROVIDER_ID = \"phone\" /* ProviderId.PHONE */;\r\n/** Always set to {@link SignInMethod}.PHONE. */\r\nPhoneAuthProvider.PHONE_SIGN_IN_METHOD = \"phone\" /* SignInMethod.PHONE */;\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Chooses a popup/redirect resolver to use. This prefers the override (which\r\n * is directly passed in), and falls back to the property set on the auth\r\n * object. If neither are available, this function errors w/ an argument error.\r\n */\r\nfunction _withDefaultResolver(auth, resolverOverride) {\r\n if (resolverOverride) {\r\n return _getInstance(resolverOverride);\r\n }\r\n _assert(auth._popupRedirectResolver, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return auth._popupRedirectResolver;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass IdpCredential extends AuthCredential {\r\n constructor(params) {\r\n super(\"custom\" /* ProviderId.CUSTOM */, \"custom\" /* ProviderId.CUSTOM */);\r\n this.params = params;\r\n }\r\n _getIdTokenResponse(auth) {\r\n return signInWithIdp(auth, this._buildIdpRequest());\r\n }\r\n _linkToIdToken(auth, idToken) {\r\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\r\n }\r\n _getReauthenticationResolver(auth) {\r\n return signInWithIdp(auth, this._buildIdpRequest());\r\n }\r\n _buildIdpRequest(idToken) {\r\n const request = {\r\n requestUri: this.params.requestUri,\r\n sessionId: this.params.sessionId,\r\n postBody: this.params.postBody,\r\n tenantId: this.params.tenantId,\r\n pendingToken: this.params.pendingToken,\r\n returnSecureToken: true,\r\n returnIdpCredential: true\r\n };\r\n if (idToken) {\r\n request.idToken = idToken;\r\n }\r\n return request;\r\n }\r\n}\r\nfunction _signIn(params) {\r\n return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nfunction _reauth(params) {\r\n const { auth, user } = params;\r\n _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nasync function _link(params) {\r\n const { auth, user } = params;\r\n _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return _link$1(user, new IdpCredential(params), params.bypassAuthState);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n */\r\nclass AbstractPopupRedirectOperation {\r\n constructor(auth, filter, resolver, user, bypassAuthState = false) {\r\n this.auth = auth;\r\n this.resolver = resolver;\r\n this.user = user;\r\n this.bypassAuthState = bypassAuthState;\r\n this.pendingPromise = null;\r\n this.eventManager = null;\r\n this.filter = Array.isArray(filter) ? filter : [filter];\r\n }\r\n execute() {\r\n return new Promise(async (resolve, reject) => {\r\n this.pendingPromise = { resolve, reject };\r\n try {\r\n this.eventManager = await this.resolver._initialize(this.auth);\r\n await this.onExecution();\r\n this.eventManager.registerConsumer(this);\r\n }\r\n catch (e) {\r\n this.reject(e);\r\n }\r\n });\r\n }\r\n async onAuthEvent(event) {\r\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\r\n if (error) {\r\n this.reject(error);\r\n return;\r\n }\r\n const params = {\r\n auth: this.auth,\r\n requestUri: urlResponse,\r\n sessionId: sessionId,\r\n tenantId: tenantId || undefined,\r\n postBody: postBody || undefined,\r\n user: this.user,\r\n bypassAuthState: this.bypassAuthState\r\n };\r\n try {\r\n this.resolve(await this.getIdpTask(type)(params));\r\n }\r\n catch (e) {\r\n this.reject(e);\r\n }\r\n }\r\n onError(error) {\r\n this.reject(error);\r\n }\r\n getIdpTask(type) {\r\n switch (type) {\r\n case \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */:\r\n case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\r\n return _signIn;\r\n case \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */:\r\n case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\r\n return _link;\r\n case \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */:\r\n case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\r\n return _reauth;\r\n default:\r\n _fail(this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n resolve(cred) {\r\n debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n this.pendingPromise.resolve(cred);\r\n this.unregisterAndCleanUp();\r\n }\r\n reject(error) {\r\n debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n this.pendingPromise.reject(error);\r\n this.unregisterAndCleanUp();\r\n }\r\n unregisterAndCleanUp() {\r\n if (this.eventManager) {\r\n this.eventManager.unregisterConsumer(this);\r\n }\r\n this.pendingPromise = null;\r\n this.cleanUp();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\r\n/**\r\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\r\n *\r\n * @remarks\r\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\r\n * unsuccessful, returns an error object containing additional information about the error.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function signInWithPopup(auth, provider, resolver) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_createError(auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */));\r\n }\r\n const authInternal = _castAuth(auth);\r\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n const action = new PopupOperation(authInternal, \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */, provider, resolverInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\r\n * OAuth flow.\r\n *\r\n * @remarks\r\n * If the reauthentication is successful, the returned result will contain the user and the\r\n * provider's credential.\r\n *\r\n * This method does not work in a Node.js environment or on any {@link User} signed in by\r\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n * // Reauthenticate using a popup.\r\n * await reauthenticateWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPopup(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_createError(userInternal.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */));\r\n }\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n const action = new PopupOperation(userInternal.auth, \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\r\n *\r\n * @remarks\r\n * If the linking is successful, the returned result will contain the user and the provider's credential.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPopup(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n const action = new PopupOperation(userInternal.auth, \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n *\r\n */\r\nclass PopupOperation extends AbstractPopupRedirectOperation {\r\n constructor(auth, filter, provider, resolver, user) {\r\n super(auth, filter, resolver, user);\r\n this.provider = provider;\r\n this.authWindow = null;\r\n this.pollId = null;\r\n if (PopupOperation.currentPopupAction) {\r\n PopupOperation.currentPopupAction.cancel();\r\n }\r\n PopupOperation.currentPopupAction = this;\r\n }\r\n async executeNotNull() {\r\n const result = await this.execute();\r\n _assert(result, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return result;\r\n }\r\n async onExecution() {\r\n debugAssert(this.filter.length === 1, 'Popup operations only handle one event');\r\n const eventId = _generateEventId();\r\n this.authWindow = await this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor\r\n eventId);\r\n this.authWindow.associatedEvent = eventId;\r\n // Check for web storage support and origin validation _after_ the popup is\r\n // loaded. These operations are slow (~1 second or so) Rather than\r\n // waiting on them before opening the window, optimistically open the popup\r\n // and check for storage support at the same time. If storage support is\r\n // not available, this will cause the whole thing to reject properly. It\r\n // will also close the popup, but since the promise has already rejected,\r\n // the popup closed by user poll will reject into the void.\r\n this.resolver._originValidation(this.auth).catch(e => {\r\n this.reject(e);\r\n });\r\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\r\n if (!isSupported) {\r\n this.reject(_createError(this.auth, \"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */));\r\n }\r\n });\r\n // Handle user closure. Notice this does *not* use await\r\n this.pollUserCancellation();\r\n }\r\n get eventId() {\r\n var _a;\r\n return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;\r\n }\r\n cancel() {\r\n this.reject(_createError(this.auth, \"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */));\r\n }\r\n cleanUp() {\r\n if (this.authWindow) {\r\n this.authWindow.close();\r\n }\r\n if (this.pollId) {\r\n window.clearTimeout(this.pollId);\r\n }\r\n this.authWindow = null;\r\n this.pollId = null;\r\n PopupOperation.currentPopupAction = null;\r\n }\r\n pollUserCancellation() {\r\n const poll = () => {\r\n var _a, _b;\r\n if ((_b = (_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {\r\n // Make sure that there is sufficient time for whatever action to\r\n // complete. The window could have closed but the sign in network\r\n // call could still be in flight. This is specifically true for\r\n // Firefox or if the opener is in an iframe, in which case the oauth\r\n // helper closes the popup.\r\n this.pollId = window.setTimeout(() => {\r\n this.pollId = null;\r\n this.reject(_createError(this.auth, \"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */));\r\n }, 8000 /* _Timeout.AUTH_EVENT */);\r\n return;\r\n }\r\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\r\n };\r\n poll();\r\n }\r\n}\r\n// Only one popup is ever shown at once. The lifecycle of the current popup\r\n// can be managed / cancelled by the constructor.\r\nPopupOperation.currentPopupAction = null;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\r\n// We only get one redirect outcome for any one auth, so just store it\r\n// in here.\r\nconst redirectOutcomeMap = new Map();\r\nclass RedirectAction extends AbstractPopupRedirectOperation {\r\n constructor(auth, resolver, bypassAuthState = false) {\r\n super(auth, [\r\n \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */,\r\n \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */,\r\n \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */,\r\n \"unknown\" /* AuthEventType.UNKNOWN */\r\n ], resolver, undefined, bypassAuthState);\r\n this.eventId = null;\r\n }\r\n /**\r\n * Override the execute function; if we already have a redirect result, then\r\n * just return it.\r\n */\r\n async execute() {\r\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\r\n if (!readyOutcome) {\r\n try {\r\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(this.resolver, this.auth);\r\n const result = hasPendingRedirect ? await super.execute() : null;\r\n readyOutcome = () => Promise.resolve(result);\r\n }\r\n catch (e) {\r\n readyOutcome = () => Promise.reject(e);\r\n }\r\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\r\n }\r\n // If we're not bypassing auth state, the ready outcome should be set to\r\n // null.\r\n if (!this.bypassAuthState) {\r\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\r\n }\r\n return readyOutcome();\r\n }\r\n async onAuthEvent(event) {\r\n if (event.type === \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */) {\r\n return super.onAuthEvent(event);\r\n }\r\n else if (event.type === \"unknown\" /* AuthEventType.UNKNOWN */) {\r\n // This is a sentinel value indicating there's no pending redirect\r\n this.resolve(null);\r\n return;\r\n }\r\n if (event.eventId) {\r\n const user = await this.auth._redirectUserForId(event.eventId);\r\n if (user) {\r\n this.user = user;\r\n return super.onAuthEvent(event);\r\n }\r\n else {\r\n this.resolve(null);\r\n }\r\n }\r\n }\r\n async onExecution() { }\r\n cleanUp() { }\r\n}\r\nasync function _getAndClearPendingRedirectStatus(resolver, auth) {\r\n const key = pendingRedirectKey(auth);\r\n const persistence = resolverPersistence(resolver);\r\n if (!(await persistence._isAvailable())) {\r\n return false;\r\n }\r\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\r\n await persistence._remove(key);\r\n return hasPendingRedirect;\r\n}\r\nasync function _setPendingRedirectStatus(resolver, auth) {\r\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\r\n}\r\nfunction _clearRedirectOutcomes() {\r\n redirectOutcomeMap.clear();\r\n}\r\nfunction _overrideRedirectResult(auth, result) {\r\n redirectOutcomeMap.set(auth._key(), result);\r\n}\r\nfunction resolverPersistence(resolver) {\r\n return _getInstance(resolver._redirectPersistence);\r\n}\r\nfunction pendingRedirectKey(auth) {\r\n return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Authenticates a Firebase client using a full-page redirect flow.\r\n *\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link signInWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction signInWithRedirect(auth, provider, resolver) {\r\n return _signInWithRedirect(auth, provider, resolver);\r\n}\r\nasync function _signInWithRedirect(auth, provider, resolver) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await authInternal._initializationPromise;\r\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n await _setPendingRedirectStatus(resolverInternal, authInternal);\r\n return resolverInternal._openRedirect(authInternal, provider, \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */);\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link reauthenticateWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * // Reauthenticate using a redirect.\r\n * await reauthenticateWithRedirect(result.user, provider);\r\n * // This will again trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction reauthenticateWithRedirect(user, provider, resolver) {\r\n return _reauthenticateWithRedirect(user, provider, resolver);\r\n}\r\nasync function _reauthenticateWithRedirect(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await userInternal.auth._initializationPromise;\r\n // Allow the resolver to error before persisting the redirect user\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n const eventId = await prepareUserForRedirect(userInternal);\r\n return resolverInternal._openRedirect(userInternal.auth, provider, \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link linkWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithRedirect(result.user, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction linkWithRedirect(user, provider, resolver) {\r\n return _linkWithRedirect(user, provider, resolver);\r\n}\r\nasync function _linkWithRedirect(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await userInternal.auth._initializationPromise;\r\n // Allow the resolver to error before persisting the redirect user\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n await _assertLinkedStatus(false, userInternal, provider.providerId);\r\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n const eventId = await prepareUserForRedirect(userInternal);\r\n return resolverInternal._openRedirect(userInternal.auth, provider, \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\r\n *\r\n * @remarks\r\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\r\n * error. If no redirect operation was called, returns `null`.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function getRedirectResult(auth, resolver) {\r\n await _castAuth(auth)._initializationPromise;\r\n return _getRedirectResult(auth, resolver, false);\r\n}\r\nasync function _getRedirectResult(auth, resolverExtern, bypassAuthState = false) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\r\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\r\n const result = await action.execute();\r\n if (result && !bypassAuthState) {\r\n delete result.user._redirectEventId;\r\n await authInternal._persistUserIfCurrent(result.user);\r\n await authInternal._setRedirectUser(null, resolverExtern);\r\n }\r\n return result;\r\n}\r\nasync function prepareUserForRedirect(user) {\r\n const eventId = _generateEventId(`${user.uid}:::`);\r\n user._redirectEventId = eventId;\r\n await user.auth._setRedirectUser(user);\r\n await user.auth._persistUserIfCurrent(user);\r\n return eventId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// The amount of time to store the UIDs of seen events; this is\r\n// set to 10 min by default\r\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\r\nclass AuthEventManager {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.cachedEventUids = new Set();\r\n this.consumers = new Set();\r\n this.queuedRedirectEvent = null;\r\n this.hasHandledPotentialRedirect = false;\r\n this.lastProcessedEventTime = Date.now();\r\n }\r\n registerConsumer(authEventConsumer) {\r\n this.consumers.add(authEventConsumer);\r\n if (this.queuedRedirectEvent &&\r\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {\r\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\r\n this.saveEventToCache(this.queuedRedirectEvent);\r\n this.queuedRedirectEvent = null;\r\n }\r\n }\r\n unregisterConsumer(authEventConsumer) {\r\n this.consumers.delete(authEventConsumer);\r\n }\r\n onEvent(event) {\r\n // Check if the event has already been handled\r\n if (this.hasEventBeenHandled(event)) {\r\n return false;\r\n }\r\n let handled = false;\r\n this.consumers.forEach(consumer => {\r\n if (this.isEventForConsumer(event, consumer)) {\r\n handled = true;\r\n this.sendToConsumer(event, consumer);\r\n this.saveEventToCache(event);\r\n }\r\n });\r\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\r\n // If we've already seen a redirect before, or this is a popup event,\r\n // bail now\r\n return handled;\r\n }\r\n this.hasHandledPotentialRedirect = true;\r\n // If the redirect wasn't handled, hang on to it\r\n if (!handled) {\r\n this.queuedRedirectEvent = event;\r\n handled = true;\r\n }\r\n return handled;\r\n }\r\n sendToConsumer(event, consumer) {\r\n var _a;\r\n if (event.error && !isNullRedirectEvent(event)) {\r\n const code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||\r\n \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */;\r\n consumer.onError(_createError(this.auth, code));\r\n }\r\n else {\r\n consumer.onAuthEvent(event);\r\n }\r\n }\r\n isEventForConsumer(event, consumer) {\r\n const eventIdMatches = consumer.eventId === null ||\r\n (!!event.eventId && event.eventId === consumer.eventId);\r\n return consumer.filter.includes(event.type) && eventIdMatches;\r\n }\r\n hasEventBeenHandled(event) {\r\n if (Date.now() - this.lastProcessedEventTime >=\r\n EVENT_DUPLICATION_CACHE_DURATION_MS) {\r\n this.cachedEventUids.clear();\r\n }\r\n return this.cachedEventUids.has(eventUid(event));\r\n }\r\n saveEventToCache(event) {\r\n this.cachedEventUids.add(eventUid(event));\r\n this.lastProcessedEventTime = Date.now();\r\n }\r\n}\r\nfunction eventUid(e) {\r\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\r\n}\r\nfunction isNullRedirectEvent({ type, error }) {\r\n return (type === \"unknown\" /* AuthEventType.UNKNOWN */ &&\r\n (error === null || error === void 0 ? void 0 : error.code) === `auth/${\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */}`);\r\n}\r\nfunction isRedirectEvent(event) {\r\n switch (event.type) {\r\n case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\r\n case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\r\n case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\r\n return true;\r\n case \"unknown\" /* AuthEventType.UNKNOWN */:\r\n return isNullRedirectEvent(event);\r\n default:\r\n return false;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _getProjectConfig(auth, request = {}) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/projects\" /* Endpoint.GET_PROJECT_CONFIG */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\r\nconst HTTP_REGEX = /^https?/;\r\nasync function _validateOrigin(auth) {\r\n // Skip origin validation if we are in an emulated environment\r\n if (auth.config.emulator) {\r\n return;\r\n }\r\n const { authorizedDomains } = await _getProjectConfig(auth);\r\n for (const domain of authorizedDomains) {\r\n try {\r\n if (matchDomain(domain)) {\r\n return;\r\n }\r\n }\r\n catch (_a) {\r\n // Do nothing if there's a URL error; just continue searching\r\n }\r\n }\r\n // In the old SDK, this error also provides helpful messages.\r\n _fail(auth, \"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */);\r\n}\r\nfunction matchDomain(expected) {\r\n const currentUrl = _getCurrentUrl();\r\n const { protocol, hostname } = new URL(currentUrl);\r\n if (expected.startsWith('chrome-extension://')) {\r\n const ceUrl = new URL(expected);\r\n if (ceUrl.hostname === '' && hostname === '') {\r\n // For some reason we're not parsing chrome URLs properly\r\n return (protocol === 'chrome-extension:' &&\r\n expected.replace('chrome-extension://', '') ===\r\n currentUrl.replace('chrome-extension://', ''));\r\n }\r\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\r\n }\r\n if (!HTTP_REGEX.test(protocol)) {\r\n return false;\r\n }\r\n if (IP_ADDRESS_REGEX.test(expected)) {\r\n // The domain has to be exactly equal to the pattern, as an IP domain will\r\n // only contain the IP, no extra character.\r\n return hostname === expected;\r\n }\r\n // Dots in pattern should be escaped.\r\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\r\n // Non ip address domains.\r\n // domain.com = *.domain.com OR domain.com\r\n const re = new RegExp('^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');\r\n return re.test(hostname);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\r\n/**\r\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\r\n * it will stop working after a retrial. This is a hack to fix this issue.\r\n */\r\nfunction resetUnloadedGapiModules() {\r\n // Clear last failed gapi.load state to force next gapi.load to first\r\n // load the failed gapi.iframes module.\r\n // Get gapix.beacon context.\r\n const beacon = _window().___jsl;\r\n // Get current hint.\r\n if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {\r\n // Get gapi hint.\r\n for (const hint of Object.keys(beacon.H)) {\r\n // Requested modules.\r\n beacon.H[hint].r = beacon.H[hint].r || [];\r\n // Loaded modules.\r\n beacon.H[hint].L = beacon.H[hint].L || [];\r\n // Set requested modules to a copy of the loaded modules.\r\n beacon.H[hint].r = [...beacon.H[hint].L];\r\n // Clear pending callbacks.\r\n if (beacon.CP) {\r\n for (let i = 0; i < beacon.CP.length; i++) {\r\n // Remove all failed pending callbacks.\r\n beacon.CP[i] = null;\r\n }\r\n }\r\n }\r\n }\r\n}\r\nfunction loadGapi(auth) {\r\n return new Promise((resolve, reject) => {\r\n var _a, _b, _c;\r\n // Function to run when gapi.load is ready.\r\n function loadGapiIframe() {\r\n // The developer may have tried to previously run gapi.load and failed.\r\n // Run this to fix that.\r\n resetUnloadedGapiModules();\r\n gapi.load('gapi.iframes', {\r\n callback: () => {\r\n resolve(gapi.iframes.getContext());\r\n },\r\n ontimeout: () => {\r\n // The above reset may be sufficient, but having this reset after\r\n // failure ensures that if the developer calls gapi.load after the\r\n // connection is re-established and before another attempt to embed\r\n // the iframe, it would work and would not be broken because of our\r\n // failed attempt.\r\n // Timeout when gapi.iframes.Iframe not loaded.\r\n resetUnloadedGapiModules();\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n },\r\n timeout: NETWORK_TIMEOUT.get()\r\n });\r\n }\r\n if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {\r\n // If gapi.iframes.Iframe available, resolve.\r\n resolve(gapi.iframes.getContext());\r\n }\r\n else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {\r\n // Gapi loader ready, load gapi.iframes.\r\n loadGapiIframe();\r\n }\r\n else {\r\n // Create a new iframe callback when this is called so as not to overwrite\r\n // any previous defined callback. This happens if this method is called\r\n // multiple times in parallel and could result in the later callback\r\n // overwriting the previous one. This would end up with a iframe\r\n // timeout.\r\n const cbName = _generateCallbackName('iframefcb');\r\n // GApi loader not available, dynamically load platform.js.\r\n _window()[cbName] = () => {\r\n // GApi loader should be ready.\r\n if (!!gapi.load) {\r\n loadGapiIframe();\r\n }\r\n else {\r\n // Gapi loader failed, throw error.\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }\r\n };\r\n // Load GApi loader.\r\n return _loadJS(`${_gapiScriptUrl()}?onload=${cbName}`)\r\n .catch(e => reject(e));\r\n }\r\n }).catch(error => {\r\n // Reset cached promise to allow for retrial.\r\n cachedGApiLoader = null;\r\n throw error;\r\n });\r\n}\r\nlet cachedGApiLoader = null;\r\nfunction _loadGapi(auth) {\r\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\r\n return cachedGApiLoader;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PING_TIMEOUT = new Delay(5000, 15000);\r\nconst IFRAME_PATH = '__/auth/iframe';\r\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\r\nconst IFRAME_ATTRIBUTES = {\r\n style: {\r\n position: 'absolute',\r\n top: '-100px',\r\n width: '1px',\r\n height: '1px'\r\n },\r\n 'aria-hidden': 'true',\r\n tabindex: '-1'\r\n};\r\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\r\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\r\nconst EID_FROM_APIHOST = new Map([\r\n [\"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */, 'p'],\r\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'],\r\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\r\n]);\r\nfunction getIframeUrl(auth) {\r\n const config = auth.config;\r\n _assert(config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\r\n const url = config.emulator\r\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\r\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\r\n const params = {\r\n apiKey: config.apiKey,\r\n appName: auth.name,\r\n v: SDK_VERSION\r\n };\r\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\r\n if (eid) {\r\n params.eid = eid;\r\n }\r\n const frameworks = auth._getFrameworks();\r\n if (frameworks.length) {\r\n params.fw = frameworks.join(',');\r\n }\r\n return `${url}?${querystring(params).slice(1)}`;\r\n}\r\nasync function _openIframe(auth) {\r\n const context = await _loadGapi(auth);\r\n const gapi = _window().gapi;\r\n _assert(gapi, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return context.open({\r\n where: document.body,\r\n url: getIframeUrl(auth),\r\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\r\n attributes: IFRAME_ATTRIBUTES,\r\n dontclear: true\r\n }, (iframe) => new Promise(async (resolve, reject) => {\r\n await iframe.restyle({\r\n // Prevent iframe from closing on mouse out.\r\n setHideOnLeave: false\r\n });\r\n const networkError = _createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);\r\n // Confirm iframe is correctly loaded.\r\n // To fallback on failure, set a timeout.\r\n const networkErrorTimer = _window().setTimeout(() => {\r\n reject(networkError);\r\n }, PING_TIMEOUT.get());\r\n // Clear timer and resolve pending iframe ready promise.\r\n function clearTimerAndResolve() {\r\n _window().clearTimeout(networkErrorTimer);\r\n resolve(iframe);\r\n }\r\n // This returns an IThenable. However the reject part does not call\r\n // when the iframe is not loaded.\r\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\r\n reject(networkError);\r\n });\r\n }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst BASE_POPUP_OPTIONS = {\r\n location: 'yes',\r\n resizable: 'yes',\r\n statusbar: 'yes',\r\n toolbar: 'no'\r\n};\r\nconst DEFAULT_WIDTH = 500;\r\nconst DEFAULT_HEIGHT = 600;\r\nconst TARGET_BLANK = '_blank';\r\nconst FIREFOX_EMPTY_URL = 'http://localhost';\r\nclass AuthPopup {\r\n constructor(window) {\r\n this.window = window;\r\n this.associatedEvent = null;\r\n }\r\n close() {\r\n if (this.window) {\r\n try {\r\n this.window.close();\r\n }\r\n catch (e) { }\r\n }\r\n }\r\n}\r\nfunction _open(auth, url, name, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT) {\r\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\r\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\r\n let target = '';\r\n const options = Object.assign(Object.assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top,\r\n left });\r\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\r\n // specified, even though the popup is not necessarily blocked.\r\n const ua = getUA().toLowerCase();\r\n if (name) {\r\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\r\n }\r\n if (_isFirefox(ua)) {\r\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\r\n url = url || FIREFOX_EMPTY_URL;\r\n // Firefox disables by default scrolling on popup windows, which can create\r\n // issues when the user has many Google accounts, for instance.\r\n options.scrollbars = 'yes';\r\n }\r\n const optionsString = Object.entries(options).reduce((accum, [key, value]) => `${accum}${key}=${value},`, '');\r\n if (_isIOSStandalone(ua) && target !== '_self') {\r\n openAsNewWindowIOS(url || '', target);\r\n return new AuthPopup(null);\r\n }\r\n // about:blank getting sanitized causing browsers like IE/Edge to display\r\n // brief error message before redirecting to handler.\r\n const newWin = window.open(url || '', target, optionsString);\r\n _assert(newWin, auth, \"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */);\r\n // Flaky on IE edge, encapsulate with a try and catch.\r\n try {\r\n newWin.focus();\r\n }\r\n catch (e) { }\r\n return new AuthPopup(newWin);\r\n}\r\nfunction openAsNewWindowIOS(url, target) {\r\n const el = document.createElement('a');\r\n el.href = url;\r\n el.target = target;\r\n const click = document.createEvent('MouseEvent');\r\n click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);\r\n el.dispatchEvent(click);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * URL for Authentication widget which will initiate the OAuth handshake\r\n *\r\n * @internal\r\n */\r\nconst WIDGET_PATH = '__/auth/handler';\r\n/**\r\n * URL for emulated environment\r\n *\r\n * @internal\r\n */\r\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\r\n/**\r\n * Fragment name for the App Check token that gets passed to the widget\r\n *\r\n * @internal\r\n */\r\nconst FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');\r\nasync function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {\r\n _assert(auth.config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\r\n _assert(auth.config.apiKey, auth, \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */);\r\n const params = {\r\n apiKey: auth.config.apiKey,\r\n appName: auth.name,\r\n authType,\r\n redirectUrl,\r\n v: SDK_VERSION,\r\n eventId\r\n };\r\n if (provider instanceof FederatedAuthProvider) {\r\n provider.setDefaultLanguage(auth.languageCode);\r\n params.providerId = provider.providerId || '';\r\n if (!isEmpty(provider.getCustomParameters())) {\r\n params.customParameters = JSON.stringify(provider.getCustomParameters());\r\n }\r\n // TODO set additionalParams from the provider as well?\r\n for (const [key, value] of Object.entries(additionalParams || {})) {\r\n params[key] = value;\r\n }\r\n }\r\n if (provider instanceof BaseOAuthProvider) {\r\n const scopes = provider.getScopes().filter(scope => scope !== '');\r\n if (scopes.length > 0) {\r\n params.scopes = scopes.join(',');\r\n }\r\n }\r\n if (auth.tenantId) {\r\n params.tid = auth.tenantId;\r\n }\r\n // TODO: maybe set eid as endipointId\r\n // TODO: maybe set fw as Frameworks.join(\",\")\r\n const paramsDict = params;\r\n for (const key of Object.keys(paramsDict)) {\r\n if (paramsDict[key] === undefined) {\r\n delete paramsDict[key];\r\n }\r\n }\r\n // Sets the App Check token to pass to the widget\r\n const appCheckToken = await auth._getAppCheckToken();\r\n const appCheckTokenFragment = appCheckToken\r\n ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`\r\n : '';\r\n // Start at index 1 to skip the leading '&' in the query string\r\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}${appCheckTokenFragment}`;\r\n}\r\nfunction getHandlerBase({ config }) {\r\n if (!config.emulator) {\r\n return `https://${config.authDomain}/${WIDGET_PATH}`;\r\n }\r\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The special web storage event\r\n *\r\n */\r\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\r\nclass BrowserPopupRedirectResolver {\r\n constructor() {\r\n this.eventManagers = {};\r\n this.iframes = {};\r\n this.originValidationPromises = {};\r\n this._redirectPersistence = browserSessionPersistence;\r\n this._completeRedirectFn = _getRedirectResult;\r\n this._overrideRedirectResult = _overrideRedirectResult;\r\n }\r\n // Wrapping in async even though we don't await anywhere in order\r\n // to make sure errors are raised as promise rejections\r\n async _openPopup(auth, provider, authType, eventId) {\r\n var _a;\r\n debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');\r\n const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\r\n return _open(auth, url, _generateEventId());\r\n }\r\n async _openRedirect(auth, provider, authType, eventId) {\r\n await this._originValidation(auth);\r\n const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\r\n _setWindowLocation(url);\r\n return new Promise(() => { });\r\n }\r\n _initialize(auth) {\r\n const key = auth._key();\r\n if (this.eventManagers[key]) {\r\n const { manager, promise } = this.eventManagers[key];\r\n if (manager) {\r\n return Promise.resolve(manager);\r\n }\r\n else {\r\n debugAssert(promise, 'If manager is not set, promise should be');\r\n return promise;\r\n }\r\n }\r\n const promise = this.initAndGetManager(auth);\r\n this.eventManagers[key] = { promise };\r\n // If the promise is rejected, the key should be removed so that the\r\n // operation can be retried later.\r\n promise.catch(() => {\r\n delete this.eventManagers[key];\r\n });\r\n return promise;\r\n }\r\n async initAndGetManager(auth) {\r\n const iframe = await _openIframe(auth);\r\n const manager = new AuthEventManager(auth);\r\n iframe.register('authEvent', (iframeEvent) => {\r\n _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, \"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */);\r\n // TODO: Consider splitting redirect and popup events earlier on\r\n const handled = manager.onEvent(iframeEvent.authEvent);\r\n return { status: handled ? \"ACK\" /* GapiOutcome.ACK */ : \"ERROR\" /* GapiOutcome.ERROR */ };\r\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n this.eventManagers[auth._key()] = { manager };\r\n this.iframes[auth._key()] = iframe;\r\n return manager;\r\n }\r\n _isIframeWebStorageSupported(auth, cb) {\r\n const iframe = this.iframes[auth._key()];\r\n iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, result => {\r\n var _a;\r\n const isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];\r\n if (isSupported !== undefined) {\r\n cb(!!isSupported);\r\n }\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n }\r\n _originValidation(auth) {\r\n const key = auth._key();\r\n if (!this.originValidationPromises[key]) {\r\n this.originValidationPromises[key] = _validateOrigin(auth);\r\n }\r\n return this.originValidationPromises[key];\r\n }\r\n get _shouldInitProactively() {\r\n // Mobile browsers and Safari need to optimistically initialize\r\n return _isMobileBrowser() || _isSafari() || _isIOS();\r\n }\r\n}\r\n/**\r\n * An implementation of {@link PopupRedirectResolver} suitable for browser\r\n * based applications.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @public\r\n */\r\nconst browserPopupRedirectResolver = BrowserPopupRedirectResolver;\n\nclass MultiFactorAssertionImpl {\r\n constructor(factorId) {\r\n this.factorId = factorId;\r\n }\r\n _process(auth, session, displayName) {\r\n switch (session.type) {\r\n case \"enroll\" /* MultiFactorSessionType.ENROLL */:\r\n return this._finalizeEnroll(auth, session.credential, displayName);\r\n case \"signin\" /* MultiFactorSessionType.SIGN_IN */:\r\n return this._finalizeSignIn(auth, session.credential);\r\n default:\r\n return debugFail('unexpected MultiFactorSessionType');\r\n }\r\n }\r\n}\n\n/**\r\n * {@inheritdoc PhoneMultiFactorAssertion}\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\r\n constructor(credential) {\r\n super(\"phone\" /* FactorId.PHONE */);\r\n this.credential = credential;\r\n }\r\n /** @internal */\r\n static _fromCredential(credential) {\r\n return new PhoneMultiFactorAssertionImpl(credential);\r\n }\r\n /** @internal */\r\n _finalizeEnroll(auth, idToken, displayName) {\r\n return finalizeEnrollPhoneMfa(auth, {\r\n idToken,\r\n displayName,\r\n phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n });\r\n }\r\n /** @internal */\r\n _finalizeSignIn(auth, mfaPendingCredential) {\r\n return finalizeSignInPhoneMfa(auth, {\r\n mfaPendingCredential,\r\n phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n });\r\n }\r\n}\r\n/**\r\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorGenerator {\r\n constructor() { }\r\n /**\r\n * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\r\n * @returns A {@link PhoneMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorResolver.resolveSignIn}\r\n */\r\n static assertion(credential) {\r\n return PhoneMultiFactorAssertionImpl._fromCredential(credential);\r\n }\r\n}\r\n/**\r\n * The identifier of the phone second factor: `phone`.\r\n */\r\nPhoneMultiFactorGenerator.FACTOR_ID = 'phone';\n\n/**\r\n * Provider for generating a {@link TotpMultiFactorAssertion}.\r\n *\r\n * @public\r\n */\r\nclass TotpMultiFactorGenerator {\r\n /**\r\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of\r\n * the TOTP (time-based one-time password) second factor.\r\n * This assertion is used to complete enrollment in TOTP second factor.\r\n *\r\n * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.\r\n * @param oneTimePassword One-time password from TOTP App.\r\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorUser.enroll}.\r\n */\r\n static assertionForEnrollment(secret, oneTimePassword) {\r\n return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);\r\n }\r\n /**\r\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.\r\n * This assertion is used to complete signIn with TOTP as the second factor.\r\n *\r\n * @param enrollmentId identifies the enrolled TOTP second factor.\r\n * @param oneTimePassword One-time password from TOTP App.\r\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorResolver.resolveSignIn}.\r\n */\r\n static assertionForSignIn(enrollmentId, oneTimePassword) {\r\n return TotpMultiFactorAssertionImpl._fromEnrollmentId(enrollmentId, oneTimePassword);\r\n }\r\n /**\r\n * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.\r\n * Creates a TOTP secret as part of enrolling a TOTP second factor.\r\n * Used for generating a QR code URL or inputting into a TOTP app.\r\n * This method uses the auth instance corresponding to the user in the multiFactorSession.\r\n *\r\n * @param session The {@link MultiFactorSession} that the user is part of.\r\n * @returns A promise to {@link TotpSecret}.\r\n */\r\n static async generateSecret(session) {\r\n var _a;\r\n const mfaSession = session;\r\n _assert(typeof ((_a = mfaSession.user) === null || _a === void 0 ? void 0 : _a.auth) !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const response = await startEnrollTotpMfa(mfaSession.user.auth, {\r\n idToken: mfaSession.credential,\r\n totpEnrollmentInfo: {}\r\n });\r\n return TotpSecret._fromStartTotpMfaEnrollmentResponse(response, mfaSession.user.auth);\r\n }\r\n}\r\n/**\r\n * The identifier of the TOTP second factor: `totp`.\r\n */\r\nTotpMultiFactorGenerator.FACTOR_ID = \"totp\" /* FactorId.TOTP */;\r\nclass TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\r\n constructor(otp, enrollmentId, secret) {\r\n super(\"totp\" /* FactorId.TOTP */);\r\n this.otp = otp;\r\n this.enrollmentId = enrollmentId;\r\n this.secret = secret;\r\n }\r\n /** @internal */\r\n static _fromSecret(secret, otp) {\r\n return new TotpMultiFactorAssertionImpl(otp, undefined, secret);\r\n }\r\n /** @internal */\r\n static _fromEnrollmentId(enrollmentId, otp) {\r\n return new TotpMultiFactorAssertionImpl(otp, enrollmentId);\r\n }\r\n /** @internal */\r\n async _finalizeEnroll(auth, idToken, displayName) {\r\n _assert(typeof this.secret !== 'undefined', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return finalizeEnrollTotpMfa(auth, {\r\n idToken,\r\n displayName,\r\n totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)\r\n });\r\n }\r\n /** @internal */\r\n async _finalizeSignIn(auth, mfaPendingCredential) {\r\n _assert(this.enrollmentId !== undefined && this.otp !== undefined, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n const totpVerificationInfo = { verificationCode: this.otp };\r\n return finalizeSignInTotpMfa(auth, {\r\n mfaPendingCredential,\r\n mfaEnrollmentId: this.enrollmentId,\r\n totpVerificationInfo\r\n });\r\n }\r\n}\r\n/**\r\n * Provider for generating a {@link TotpMultiFactorAssertion}.\r\n *\r\n * Stores the shared secret key and other parameters to generate time-based OTPs.\r\n * Implements methods to retrieve the shared secret key and generate a QR code URL.\r\n * @public\r\n */\r\nclass TotpSecret {\r\n // The public members are declared outside the constructor so the docs can be generated.\r\n constructor(secretKey, hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline, sessionInfo, auth) {\r\n this.sessionInfo = sessionInfo;\r\n this.auth = auth;\r\n this.secretKey = secretKey;\r\n this.hashingAlgorithm = hashingAlgorithm;\r\n this.codeLength = codeLength;\r\n this.codeIntervalSeconds = codeIntervalSeconds;\r\n this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;\r\n }\r\n /** @internal */\r\n static _fromStartTotpMfaEnrollmentResponse(response, auth) {\r\n return new TotpSecret(response.totpSessionInfo.sharedSecretKey, response.totpSessionInfo.hashingAlgorithm, response.totpSessionInfo.verificationCodeLength, response.totpSessionInfo.periodSec, new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(), response.totpSessionInfo.sessionInfo, auth);\r\n }\r\n /** @internal */\r\n _makeTotpVerificationInfo(otp) {\r\n return { sessionInfo: this.sessionInfo, verificationCode: otp };\r\n }\r\n /**\r\n * Returns a QR code URL as described in\r\n * https://github.com/google/google-authenticator/wiki/Key-Uri-Format\r\n * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.\r\n * If the optional parameters are unspecified, an accountName of and issuer of are used.\r\n *\r\n * @param accountName the name of the account/app along with a user identifier.\r\n * @param issuer issuer of the TOTP (likely the app name).\r\n * @returns A QR code URL string.\r\n */\r\n generateQrCodeUrl(accountName, issuer) {\r\n var _a;\r\n let useDefaults = false;\r\n if (_isEmptyString(accountName) || _isEmptyString(issuer)) {\r\n useDefaults = true;\r\n }\r\n if (useDefaults) {\r\n if (_isEmptyString(accountName)) {\r\n accountName = ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.email) || 'unknownuser';\r\n }\r\n if (_isEmptyString(issuer)) {\r\n issuer = this.auth.name;\r\n }\r\n }\r\n return `otpauth://totp/${issuer}:${accountName}?secret=${this.secretKey}&issuer=${issuer}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`;\r\n }\r\n}\r\n/** @internal */\r\nfunction _isEmptyString(input) {\r\n return typeof input === 'undefined' || (input === null || input === void 0 ? void 0 : input.length) === 0;\r\n}\n\nvar name = \"@firebase/auth\";\nvar version = \"1.7.3\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthInterop {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.internalListeners = new Map();\r\n }\r\n getUid() {\r\n var _a;\r\n this.assertAuthConfigured();\r\n return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;\r\n }\r\n async getToken(forceRefresh) {\r\n this.assertAuthConfigured();\r\n await this.auth._initializationPromise;\r\n if (!this.auth.currentUser) {\r\n return null;\r\n }\r\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\r\n return { accessToken };\r\n }\r\n addAuthTokenListener(listener) {\r\n this.assertAuthConfigured();\r\n if (this.internalListeners.has(listener)) {\r\n return;\r\n }\r\n const unsubscribe = this.auth.onIdTokenChanged(user => {\r\n listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);\r\n });\r\n this.internalListeners.set(listener, unsubscribe);\r\n this.updateProactiveRefresh();\r\n }\r\n removeAuthTokenListener(listener) {\r\n this.assertAuthConfigured();\r\n const unsubscribe = this.internalListeners.get(listener);\r\n if (!unsubscribe) {\r\n return;\r\n }\r\n this.internalListeners.delete(listener);\r\n unsubscribe();\r\n this.updateProactiveRefresh();\r\n }\r\n assertAuthConfigured() {\r\n _assert(this.auth._initializationPromise, \"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);\r\n }\r\n updateProactiveRefresh() {\r\n if (this.internalListeners.size > 0) {\r\n this.auth._startProactiveRefresh();\r\n }\r\n else {\r\n this.auth._stopProactiveRefresh();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getVersionForPlatform(clientPlatform) {\r\n switch (clientPlatform) {\r\n case \"Node\" /* ClientPlatform.NODE */:\r\n return 'node';\r\n case \"ReactNative\" /* ClientPlatform.REACT_NATIVE */:\r\n return 'rn';\r\n case \"Worker\" /* ClientPlatform.WORKER */:\r\n return 'webworker';\r\n case \"Cordova\" /* ClientPlatform.CORDOVA */:\r\n return 'cordova';\r\n case \"WebExtension\" /* ClientPlatform.WEB_EXTENSION */:\r\n return 'web-extension';\r\n default:\r\n return undefined;\r\n }\r\n}\r\n/** @internal */\r\nfunction registerAuth(clientPlatform) {\r\n _registerComponent(new Component(\"auth\" /* _ComponentName.AUTH */, (container, { options: deps }) => {\r\n const app = container.getProvider('app').getImmediate();\r\n const heartbeatServiceProvider = container.getProvider('heartbeat');\r\n const appCheckServiceProvider = container.getProvider('app-check-internal');\r\n const { apiKey, authDomain } = app.options;\r\n _assert(apiKey && !apiKey.includes(':'), \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });\r\n const config = {\r\n apiKey,\r\n authDomain,\r\n clientPlatform,\r\n apiHost: \"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */,\r\n tokenApiHost: \"securetoken.googleapis.com\" /* DefaultConfig.TOKEN_API_HOST */,\r\n apiScheme: \"https\" /* DefaultConfig.API_SCHEME */,\r\n sdkClientVersion: _getClientVersion(clientPlatform)\r\n };\r\n const authInstance = new AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config);\r\n _initializeAuthInstance(authInstance, deps);\r\n return authInstance;\r\n }, \"PUBLIC\" /* ComponentType.PUBLIC */)\r\n /**\r\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\r\n * For why we do this, See go/firebase-next-auth-init\r\n */\r\n .setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */)\r\n /**\r\n * Because all firebase products that depend on auth depend on auth-internal directly,\r\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\r\n */\r\n .setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => {\r\n const authInternalProvider = container.getProvider(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */);\r\n authInternalProvider.initialize();\r\n }));\r\n _registerComponent(new Component(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */, container => {\r\n const auth = _castAuth(container.getProvider(\"auth\" /* _ComponentName.AUTH */).getImmediate());\r\n return (auth => new AuthInterop(auth))(auth);\r\n }, \"PRIVATE\" /* ComponentType.PRIVATE */).setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */));\r\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\r\nconst authIdTokenMaxAge = getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\r\nlet lastPostedIdToken = null;\r\nconst mintCookieFactory = (url) => async (user) => {\r\n const idTokenResult = user && (await user.getIdTokenResult());\r\n const idTokenAge = idTokenResult &&\r\n (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1000;\r\n if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\r\n return;\r\n }\r\n // Specifically trip null => undefined when logged out, to delete any existing cookie\r\n const idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token;\r\n if (lastPostedIdToken === idToken) {\r\n return;\r\n }\r\n lastPostedIdToken = idToken;\r\n await fetch(url, {\r\n method: idToken ? 'POST' : 'DELETE',\r\n headers: idToken\r\n ? {\r\n 'Authorization': `Bearer ${idToken}`\r\n }\r\n : {}\r\n });\r\n};\r\n/**\r\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\r\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\r\n *\r\n * @param app - The Firebase App.\r\n *\r\n * @public\r\n */\r\nfunction getAuth(app = getApp()) {\r\n const provider = _getProvider(app, 'auth');\r\n if (provider.isInitialized()) {\r\n return provider.getImmediate();\r\n }\r\n const auth = initializeAuth(app, {\r\n popupRedirectResolver: browserPopupRedirectResolver,\r\n persistence: [\r\n indexedDBLocalPersistence,\r\n browserLocalPersistence,\r\n browserSessionPersistence\r\n ]\r\n });\r\n const authTokenSyncPath = getExperimentalSetting('authTokenSyncURL');\r\n // Only do the Cookie exchange in a secure context\r\n if (authTokenSyncPath &&\r\n typeof isSecureContext === 'boolean' &&\r\n isSecureContext) {\r\n // Don't allow urls (XSS possibility), only paths on the same domain\r\n const authTokenSyncUrl = new URL(authTokenSyncPath, location.origin);\r\n if (location.origin === authTokenSyncUrl.origin) {\r\n const mintCookie = mintCookieFactory(authTokenSyncUrl.toString());\r\n beforeAuthStateChanged(auth, mintCookie, () => mintCookie(auth.currentUser));\r\n onIdTokenChanged(auth, user => mintCookie(user));\r\n }\r\n }\r\n const authEmulatorHost = getDefaultEmulatorHost('auth');\r\n if (authEmulatorHost) {\r\n connectAuthEmulator(auth, `http://${authEmulatorHost}`);\r\n }\r\n return auth;\r\n}\r\nfunction getScriptParentElement() {\r\n var _a, _b;\r\n return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;\r\n}\r\n_setExternalJSProvider({\r\n loadJS(url) {\r\n // TODO: consider adding timeout support & cancellation\r\n return new Promise((resolve, reject) => {\r\n const el = document.createElement('script');\r\n el.setAttribute('src', url);\r\n el.onload = resolve;\r\n el.onerror = e => {\r\n const error = _createError(\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n error.customData = e;\r\n reject(error);\r\n };\r\n el.type = 'text/javascript';\r\n el.charset = 'UTF-8';\r\n getScriptParentElement().appendChild(el);\r\n });\r\n },\r\n gapiScript: 'https://apis.google.com/js/api.js',\r\n recaptchaV2Script: 'https://www.google.com/recaptcha/api.js',\r\n recaptchaEnterpriseScript: 'https://www.google.com/recaptcha/enterprise.js?render='\r\n});\r\nregisterAuth(\"Browser\" /* ClientPlatform.BROWSER */);\n\nexport { TwitterAuthProvider as $, ActionCodeOperation as A, updateCurrentUser as B, signOut as C, revokeAccessToken as D, deleteUser as E, FactorId as F, debugErrorMap as G, prodErrorMap as H, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as I, initializeAuth as J, connectAuthEmulator as K, AuthCredential as L, EmailAuthCredential as M, OAuthCredential as N, OperationType as O, PhoneAuthProvider as P, PhoneAuthCredential as Q, RecaptchaVerifier as R, SignInMethod as S, TotpMultiFactorGenerator as T, inMemoryPersistence as U, EmailAuthProvider as V, FacebookAuthProvider as W, GoogleAuthProvider as X, GithubAuthProvider as Y, OAuthProvider as Z, SAMLAuthProvider as _, browserSessionPersistence as a, signInAnonymously as a0, signInWithCredential as a1, linkWithCredential as a2, reauthenticateWithCredential as a3, signInWithCustomToken as a4, sendPasswordResetEmail as a5, confirmPasswordReset as a6, applyActionCode as a7, checkActionCode as a8, verifyPasswordResetCode as a9, _isIOS7Or8 as aA, _createError as aB, _assert as aC, AuthEventManager as aD, _getInstance as aE, _persistenceKeyName as aF, _getRedirectResult as aG, _overrideRedirectResult as aH, _clearRedirectOutcomes as aI, _castAuth as aJ, UserImpl as aK, AuthImpl as aL, _getClientVersion as aM, _generateEventId as aN, AuthPopup as aO, FetchProvider as aP, SAMLAuthCredential as aQ, createUserWithEmailAndPassword as aa, signInWithEmailAndPassword as ab, sendSignInLinkToEmail as ac, isSignInWithEmailLink as ad, signInWithEmailLink as ae, fetchSignInMethodsForEmail as af, sendEmailVerification as ag, verifyBeforeUpdateEmail as ah, ActionCodeURL as ai, parseActionCodeURL as aj, updateProfile as ak, updateEmail as al, updatePassword as am, getIdToken as an, getIdTokenResult as ao, unlink as ap, getAdditionalUserInfo as aq, reload as ar, getMultiFactorResolver as as, multiFactor as at, debugAssert as au, _isIOS as av, _isAndroid as aw, _fail as ax, _getRedirectUrl as ay, _getProjectConfig as az, browserLocalPersistence as b, signInWithPopup as c, linkWithPopup as d, reauthenticateWithPopup as e, signInWithRedirect as f, linkWithRedirect as g, reauthenticateWithRedirect as h, indexedDBLocalPersistence as i, getRedirectResult as j, browserPopupRedirectResolver as k, linkWithPhoneNumber as l, PhoneMultiFactorGenerator as m, TotpSecret as n, getAuth as o, ProviderId as p, setPersistence as q, reauthenticateWithPhoneNumber as r, signInWithPhoneNumber as s, initializeRecaptchaConfig as t, updatePhoneNumber as u, validatePassword as v, onIdTokenChanged as w, beforeAuthStateChanged as x, onAuthStateChanged as y, useDeviceLanguage as z };\n//# sourceMappingURL=index-d0d29856.js.map\n","import { initializeApp } from 'firebase/app'\n\n// Add the Firebase products that you want to use\nimport {\n getAuth,\n onAuthStateChanged,\n createUserWithEmailAndPassword,\n signInWithEmailAndPassword,\n signInWithPhoneNumber,\n signInWithCustomToken,\n RecaptchaVerifier,\n sendEmailVerification,\n sendPasswordResetEmail,\n updateProfile,\n signOut\n} from 'firebase/auth'\n//import \"firebase/compat/firestore\"\nconst cookiePrefix = import.meta.env.VITE_COOKIE_PREFIX\n\nconst handleError = (error) => {\n // var errorCode = error.code;\n const errorMessage = error.message\n return errorMessage\n}\n\nclass FirebaseAuthBackend {\n constructor(firebaseConfig, setFirebaseAuthSuccess) {\n if (firebaseConfig) {\n // Initialize Firebase\n initializeApp(firebaseConfig)\n const auth = getAuth()\n onAuthStateChanged(auth, () => {\n setFirebaseAuthSuccess(true)\n })\n }\n }\n\n /**\n * Registers the user with given details\n */\n registerUser = (email, password, displayName) => {\n return new Promise((resolve, reject) => {\n const auth = getAuth()\n createUserWithEmailAndPassword(auth, email, password)\n .then(userCredential => {\n updateProfile(userCredential.user, { displayName })\n sendEmailVerification(userCredential.user)\n resolve(userCredential.user)\n },\n error => {\n reject(handleError(error))\n })\n })\n }\n\n /**\n * Login user with given details\n */\n loginUser = (email, password) => {\n return new Promise((resolve, reject) => {\n const auth = getAuth()\n signInWithEmailAndPassword(auth, email, password)\n .then((userCredential) => {\n resolve(userCredential.user.getIdToken())\n },\n error => {\n reject(handleError(error))\n })\n })\n }\n\n loginUserMobile = (phoneNumber) => {\n return new Promise((resolve, reject) => {\n const auth = getAuth()\n window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {\n size: 'invisible'\n }, auth)\n signInWithPhoneNumber(auth, `+91${phoneNumber}`, window.recaptchaVerifier)\n .then((confirmationResult) => {\n window.confirmationResult = confirmationResult\n resolve()\n },\n error => {\n reject(handleError(error))\n })\n })\n }\n\n loginWithCustomToken = (token) => {\n return new Promise((resolve, reject) => {\n const auth = getAuth()\n signInWithCustomToken(auth, token)\n .then((userCredential) => {\n const user = userCredential.user\n resolve(user)\n })\n .catch((error) => {\n console.log('error in loginWithCustomToken', error)\n reject(handleError(error))\n })\n })\n }\n\n resendOTP = (phoneNumber) => {\n return new Promise((resolve, reject) => {\n const auth = getAuth()\n signInWithPhoneNumber(auth, `+91${phoneNumber}`, window.recaptchaVerifier)\n .then((confirmationResult) => {\n window.confirmationResult = confirmationResult\n resolve()\n },\n error => {\n reject(handleError(error))\n })\n })\n }\n\n invisibleRecaptcha = (signInButton) => {\n return new Promise((resolve, reject) => {\n const auth = getAuth()\n window.recaptchaVerifier = new RecaptchaVerifier(signInButton, {\n size: 'invisible',\n callback: () => {\n resolve()\n },\n 'expired-callback': () => {\n console.log('Recaptcha expired')\n reject(handleError('Recaptcha expired'))\n },\n error: () => {\n console.log('Error')\n }\n }, auth)\n })\n }\n\n confirmCodeUserMobile = (code) => {\n return new Promise((resolve, reject) => {\n window.confirmationResult.confirm(code)\n .then((result) => {\n resolve(result.user)\n },\n error => {\n reject(handleError(error))\n })\n })\n }\n\n /**\n * Login user with given details\n */\n getIDTokenUser = () => {\n return new Promise((resolve) => {\n const auth = getAuth()\n resolve(auth.currentUser.getIdToken())\n })\n }\n\n /**\n * forgot Password user with given details\n */\n forgotPassword = email => {\n return new Promise((resolve, reject) => {\n const auth = getAuth()\n sendPasswordResetEmail(auth, email, {\n url: `${window.location.protocol}//${window.location.host}/login`\n })\n .then(() => {\n resolve(true)\n })\n .catch(error => {\n reject(handleError(error))\n })\n })\n }\n\n /**\n * Logout the user\n */\n logoutUser = () => {\n return new Promise((resolve, reject) => {\n const auth = getAuth()\n signOut(auth)\n .then(() => {\n resolve(true)\n localStorage.removeItem(`${cookiePrefix}authUser`)\n })\n .catch(error => {\n reject(handleError(error))\n })\n })\n }\n\n /*addNewUserToFirestore = user => {\n const collection = firebase.firestore().collection(\"users\")\n const { profile } = user.additionalUserInfo\n const details = {\n firstName: profile.given_name ? profile.given_name : profile.first_name,\n lastName: profile.family_name ? profile.family_name : profile.last_name,\n fullName: profile.name,\n email: profile.email,\n picture: profile.picture,\n createdDtm: firebase.firestore.FieldValue.serverTimestamp(),\n lastLoginTime: firebase.firestore.FieldValue.serverTimestamp()\n }\n collection.doc(firebase.auth().currentUser.uid).set(details)\n return { user, details }\n }*/\n}\n\nlet _fireBaseBackend = null\n\n/**\n * Initilize the backend\n * @param {*} config\n */\nconst initFirebaseBackend = (config, setFirebaseAuthSuccess) => {\n if (!_fireBaseBackend) {\n _fireBaseBackend = new FirebaseAuthBackend(config, setFirebaseAuthSuccess)\n }\n return _fireBaseBackend\n}\n\n/**\n * Returns the firebase backend\n */\nconst getFirebaseBackend = () => {\n return _fireBaseBackend\n}\n\nexport { initFirebaseBackend, getFirebaseBackend }\n","import { Global } from '@emotion/react'\n\nconst Fonts = () => (\n \n)\n\nexport default Fonts","import { inputAnatomy } from '@chakra-ui/anatomy'\nimport { createMultiStyleConfigHelpers } from '@chakra-ui/react'\n\nconst { definePartsStyle, defineMultiStyleConfig } =\n createMultiStyleConfigHelpers(inputAnatomy.keys)\n\nconst baseStyle = definePartsStyle({\n // define the part you're going to style\n field: {\n _light: {\n border: '1px solid',\n borderColor: 'purple.100',\n background: 'purple.50',\n _hover: {\n border: '2px solid',\n borderColor: 'purple.100'\n },\n color: 'gray.600'\n },\n _dark: {\n border: '1px solid',\n borderColor: 'gray.600',\n background: 'rgb(28, 32, 57)',\n _hover: {\n border: '2px solid',\n borderColor: 'gray.400'\n },\n color: 'gray.400'\n }\n }\n})\n\nexport const inputTheme = defineMultiStyleConfig({ baseStyle })","import { modalAnatomy as parts } from '@chakra-ui/anatomy'\nimport { createMultiStyleConfigHelpers } from '@chakra-ui/styled-system'\n\nconst { definePartsStyle, defineMultiStyleConfig } =\n createMultiStyleConfigHelpers(parts.keys)\n\nconst baseStyle = definePartsStyle({\n // define the part you're going to style\n \n dialog: {\n _light: {\n color: 'gray.700',\n bg: 'purple.50'\n },\n _dark: {\n color: 'gray.100',\n bg: 'rgb(28, 32, 57)'\n }\n }\n})\n\nexport const modalTheme = defineMultiStyleConfig({\n baseStyle\n})","import { menuAnatomy } from '@chakra-ui/anatomy'\nimport { createMultiStyleConfigHelpers } from '@chakra-ui/react'\n\nconst { definePartsStyle, defineMultiStyleConfig } =\n createMultiStyleConfigHelpers(menuAnatomy.keys)\n\n// define the base component styles\nconst baseStyle = definePartsStyle({\n // define the part you're going to style\n button: {\n // this will style the MenuButton component\n _light: {\n color: 'gray.700',\n bg: 'purple.100'\n },\n _dark: {\n color: 'gray.100',\n bg: 'rgb(30, 35, 64)'\n }\n },\n list: {\n // this will style the MenuList component\n _light: {\n bg: 'purple.100',\n borderRadius: 'xl',\n border: 'none'\n },\n _dark: {\n borderRadius: 'xl',\n border: 'none', \n color: 'gray.100',\n bg: 'rgb(30, 35, 64)'\n }\n },\n item: {\n // this will style the MenuItem and MenuItemOption components\n _light: {\n color: 'gray.700',\n bg: 'purple.100',\n _hover: {\n bg: 'purple.50'\n },\n _focus: {\n bg: 'purple.50'\n }\n },\n _dark: {\n color: 'gray.100',\n bg: 'rgb(30, 35, 64)',\n _hover: {\n bg: '#19204D'\n },\n _focus: {\n bg: '#19204D'\n }\n }\n },\n groupTitle: {\n // this will style the text defined by the title prop\n // in the MenuGroup and MenuOptionGroup components\n textTransform: 'uppercase',\n color: 'white',\n textAlign: 'center',\n letterSpacing: 'wider',\n opacity: '0.7'\n },\n command: {\n // this will style the text defined by the command\n // prop in the MenuItem and MenuItemOption components\n opacity: '0.8',\n fontFamily: 'mono',\n fontSize: 'sm',\n letterSpacing: 'tighter',\n pl: '4'\n },\n divider: {\n // this will style the MenuDivider component\n my: '4',\n borderColor: 'white',\n borderBottom: '1px'\n }\n})\n// export the base styles in the component theme\nexport const menuTheme = defineMultiStyleConfig({ baseStyle })","\nimport { extendTheme } from '@chakra-ui/react'\nimport { inputTheme } from '@components/theme/Input.jsx'\nimport { modalTheme } from '@components/theme/modal.jsx'\nimport { menuTheme } from '@components/theme/menu.jsx'\n\n\nconst Theme = extendTheme({\n styles: {\n global: (props) => ({\n 'html, body': {\n color: props.colorMode === 'dark' ? 'gray.200' : 'gray.700',\n bg: props.colorMode === 'dark' ? 'rgb(28, 32, 57)' : 'purple.50',\n lineHeight: 'tall'\n }\n })\n },\n config: { initialColorMode: 'dark', useSystemColorMode: false},\n fonts: {\n heading: `'Heading Font Name', MYRIADPRO-BOLD`,\n body: `'Body Font Name', MYRIADPRO-REGULAR`\n },\n components: {\n Modal: modalTheme,\n Form: {\n baseStyle: {\n fontStyle:\"bold\"\n }\n },\n Menu: menuTheme,\n Button: {\n baseStyle: {\n borderRadius: 'none',\n fontWeight: 'bold',\n color: \"grey.700\"\n }\n },\n Input: {\n ...inputTheme,\n sizes: {\n xs: {\n field: {\n borderRadius: 'none'\n }\n },\n sm: {\n field: {\n borderRadius: 'none'\n }\n },\n md: {\n field: {\n borderRadius: 'none'\n }\n },\n lg: {\n field: {\n borderRadius: 'none'\n }\n }\n }\n }\n }\n})\n\nexport default Theme","import { useEffect, useState, Suspense, useCallback } from 'react'\nimport { useDispatch, useSelector } from 'react-redux'\nimport ReactGA from 'react-ga4'\nimport { useQuery } from '@tanstack/react-query'\nimport * as Sentry from '@sentry/react'\nimport Router from './router/Router'\nimport { checkToken, getRefreshToken } from '@services/AuthenticationService'\nimport { useLocation, useNavigate, useSearchParams } from 'react-router-dom'\nimport { initFirebaseBackend } from '@utility/FirebaseHelper'\nimport { handleLogin, handleLogout } from '@store/auth'\nimport { ChakraProvider, Spinner, Center, useToast } from '@chakra-ui/react'\nimport Fonts from '@components/theme/fonts'\nimport Theme from '@components/theme/theme'\n\nconst firebaseConfig = {\n apiKey: import.meta.env.VITE_APP_APIKEY,\n authDomain: import.meta.env.VITE_APP_AUTHDOMAIN,\n databaseURL: import.meta.env.VITE_APP_DATABASEURL,\n projectId: import.meta.env.VITE_APP_PROJECTID,\n storageBucket: import.meta.env.VITE_APP_STORAGEBUCKET,\n messagingSenderId: import.meta.env.VITE_APP_MESSAGINGSENDERID,\n appId: import.meta.env.VITE_APP_APPID,\n measurementId: import.meta.env.VITE_APP_MEASUREMENTID\n}\n\nconst TRACKING_ID = import.meta.env.VITE_APP_GA\n\n\nconst ROUTES_WHICH_DO_NOT_NEED_LOGIN = [\n '/home',\n '/collectible',\n '/collection',\n '/airdrop',\n '/lease',\n '/brand'\n]\n\nconst App = () => {\n const [firebaseAuthSuccess, setFirebaseAuthSuccess] = useState(false)\n const location = useLocation()\n const dispatch = useDispatch()\n const navigate = useNavigate()\n const { userData } = useSelector(state => state.auth)\n const toast = useToast()\n const [searchParams] = useSearchParams()\n\n\n // init firebase backend\n const fireBaseBackend = initFirebaseBackend(\n firebaseConfig,\n setFirebaseAuthSuccess\n )\n\n const logoutUser = useCallback(error => {\n toast({\n title: 'Authentication Failed',\n description: \"Error in authentication. Please login.\" + error,\n status: 'error',\n duration: 5000,\n isClosable: true\n })\n dispatch(handleLogout())\n navigate('/')\n },[dispatch, navigate, toast])\n\n const checkAndRefreshToken = () => {\n return new Promise((resolve, reject) => {\n checkToken()\n .then(response => {\n if (\n new Date(response.data.expiry * 1000) <\n new Date(new Date().getTime() + (10 * 24 * 60 * 60 * 1000))\n ) {\n fireBaseBackend.getIDTokenUser()\n .then(token => getRefreshToken({oauth_token: token, provider:'firebase'}))\n .then(response => {\n dispatch(\n handleLogin({\n userData: response.data,\n authToken:\n response.data &&\n response.data.access_keys &&\n response.data.access_keys.access_token\n ? response.data.access_keys.access_token\n : null\n })\n )\n resolve(response)\n })\n } else {\n resolve(response)\n }\n })\n .catch(error => {\n reject(error.message)\n })\n })\n }\n\n const tokenQuery = useQuery({\n queryKey: ['token'],\n queryFn: () => checkAndRefreshToken()\n .then(response => response.data)\n .catch(error => {\n console.log(error)\n toast({\n title: 'Auth session expired',\n description: \"You auth session has expired, please try to login again\",\n status: 'error',\n duration: 5000,\n isClosable: true\n }) \n }),\n enabled: !!(firebaseAuthSuccess && userData.account_id && userData.user_name)\n })\n\n useEffect(() => {\n if (tokenQuery.isError) {\n logoutUser(tokenQuery.error)\n }\n },[logoutUser, tokenQuery.error, tokenQuery.isError])\n\n useEffect(() => {\n if (!userData) {\n\n if (location.pathname === '/') {\n navigate(location)\n } else {\n const found = ROUTES_WHICH_DO_NOT_NEED_LOGIN.find(route =>\n location.pathname.includes(route)\n )\n\n if (found) {\n navigate(location)\n } else {\n navigate(`/login${location.search}`)\n }\n }\n\n Sentry.setUser(null)\n ReactGA.initialize(TRACKING_ID)\n ReactGA.set({ page: location.pathname })\n } else {\n Sentry.setUser({\n id: userData.account_id,\n username: userData.user_name\n })\n\n ReactGA.initialize([\n {\n trackingId: TRACKING_ID,\n gaOptions: {\n userId: userData.account_id\n }\n }\n ])\n\n ReactGA.set({ page: location.pathname, userId: userData.account_id })\n }\n\n // If new route is login and if user is already logged in\n if (userData?.account_id && location.pathname === '/login') {\n const search = location.search\n const collection_id = new URLSearchParams(search).get('collection_id')\n const airdrop_id = new URLSearchParams(search).get('airdrop_id')\n const collectible_id = new URLSearchParams(search).get('collectible_id')\n const redirectTo = searchParams.get('redirectTo')\n console.log(redirectTo)\n if (airdrop_id) {\n navigate(`/airdrop/${airdrop_id}`)\n } else if (collection_id) {\n navigate(`/collection/${collection_id}`)\n } else if (collectible_id) {\n navigate(`/collectible/${collectible_id}`)\n } else {\n if (redirectTo) {\n navigate(redirectTo)\n } else {\n navigate('/profile')\n }\n }\n }\n }, [location, location.pathname, navigate, searchParams, userData])\n\n return (\n \n \n {firebaseAuthSuccess ? (\n \n \n \n ) : (\n

Loading...
\n )}\n \n )\n}\n\nexport default App\n","// ** React Imports\nimport { Suspense } from 'react'\nimport { createRoot } from 'react-dom/client'\nimport { BrowserRouter } from 'react-router-dom'\nimport { store } from './redux/store'\nimport { Provider } from 'react-redux'\nimport { Spinner, Center } from \"@chakra-ui/react\"\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query'\nimport ScrollToTop from '@components/layout/ScrollToTop'\nimport \"./instrument\";\nimport App from './App'\n\n// ** Lazy load app\nconst queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n refetchOnWindowFocus: false,\n refetchOnMount: true,\n retry: 1\n }\n }\n})\n\nconst container = document.getElementById('root')\nconst root = createRoot(container)\n\nroot.render(\n \n \n \n }>\n \n \n \n \n \n \n \n)\n\n"],"file":"assets/index-B4tUSVCK.js"}